text
stringlengths
8
6.88M
/* * TestClass.hpp * * Created on: Apr 30, 2017 * Author: Patryk */ #ifndef INCLUDE_TESTCLASS_HPP_ #define INCLUDE_TESTCLASS_HPP_ #include <Templates.hpp> #include <Window.hpp> #include <iostream> #include <InputManager.hpp> class TestClass : public IInput { public: TestClass() = default; void key_input(GLFWwindow *win,int key,int scancode,int action,int mods) override { if(action == GLFW_PRESS) if(key == GLFW_KEY_F10) std::cout << "Clicked F10\n"; } }; #endif /* INCLUDE_TESTCLASS_HPP_ */
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 2111 struct Tp { int x, y; } a[N]; int h[N], hn = 0, IT; int was[N]; int pr[N]; vector<int> g[N]; bool kuhn(int x) { if (was[x] == IT) return false; was[x] = IT; for (int i = 0; i < g[x].size(); ++i) { if (pr[ g[x][i] ] == -1 || kuhn(pr[ g[x][i] ])) { pr[ g[x][i] ] = x; return true; } } return false; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); hn = 0; for (int i = 0; i < n; ++i) { scanf("%d%d", &a[i].x, &a[i].y); h[hn++] = a[i].x; h[hn++] = a[i].y; } sort(h, h + hn); hn = unique(h, h + hn) - h; for (int i = 0; i < hn; ++i) { pr[i] = -1; g[i].clear(); } for (int i = 0; i < n; ++i) g[ lower_bound(h, h + hn, a[i].x) - h ].push_back(lower_bound(h, h + hn, a[i].y) - h); int ans = 0; for (int i = 0; i < hn; ++i) { ++IT; ans += kuhn(i); } printf("%d\n", ans); } return 0; }
/* * MIT License * * Copyright (c) 2017 by J. Daly at Michigan State University * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "TreeBuilder.h" #include "../Utilities/MapExtensions.h" #include <limits> #include <unordered_map> #include <unordered_set> using namespace std; #define MaxDelta 16 SpanRange GetSpan(const Rule& rule, uint8_t dim, uint8_t left, uint8_t right) { Point lp = rule.range[dim].low; Point rp = rule.range[dim].high; uint32_t mask = 0xFFFFFFFF >> (left + right); uint32_t l = (lp >> right) & mask; uint32_t r = (rp >> right) & mask; return SpanRange(l, r); } tuple<uint8_t, uint8_t, uint8_t, size_t> TreeBuilder::BestSpan(const vector<Rule>& rules, Allower isAllowed, int penaltyRate) { size_t bestCost = std::numeric_limits<size_t>::max(); uint8_t bestDim = 0; uint8_t bestNl = 0; uint8_t bestNr = 0; for (uint8_t delta = BitsPerNybble; delta <= MaxDelta; delta += BitsPerNybble) { for (uint8_t dim : allowableDims) { for (uint8_t nl = 0; nl + delta <= BitsPerField; nl += BitsPerNybble) { uint8_t nr = BitsPerField - nl - delta; unordered_map<Point, size_t> counts; size_t penalty = 0; for (const Rule& r : rules) { if (isAllowed(r, dim, nl, nr)) { SpanRange span = GetSpan(r, dim, nl, nr); for (Point i = span.first; i <= span.second; i++) { counts[i]++; } } else { penalty += 1; } } size_t fitness = 0; for (auto pair : counts) { if (pair.second > fitness) fitness = pair.second; } fitness += penalty * penaltyRate; if (fitness < bestCost) { bestCost = fitness; bestDim = dim; bestNl = nl; bestNr = nr; } } } } return tuple<uint8_t, uint8_t, uint8_t, size_t>(bestDim, bestNl, bestNr, bestCost); } tuple<uint8_t, uint8_t, uint8_t, size_t> TreeBuilder::BestSpanMinPart(const vector<Rule>& rules, Allower isAllowed, int penaltyRate) { size_t bestCost = std::numeric_limits<size_t>::max(); size_t bestPart = std::numeric_limits<size_t>::max(); uint8_t bestDim = 0; uint8_t bestNl = 0; uint8_t bestNr = 0; for (uint8_t delta = BitsPerNybble; delta <= MaxDelta; delta += BitsPerNybble) { for (uint8_t dim : allowableDims) { for (uint8_t nl = 0; nl + delta <= BitsPerField; nl += BitsPerNybble) { uint8_t nr = BitsPerField - nl - delta; unordered_map<Point, size_t> counts; size_t penalty = 0; for (const Rule& r : rules) { if (isAllowed(r, dim, nl, nr)) { SpanRange span = GetSpan(r, dim, nl, nr); for (Point i = span.first; i <= span.second; i++) { counts[i]++; } } else { penalty += 1; } } size_t fitness = 0; for (auto pair : counts) { if (pair.second > fitness) fitness = pair.second; } size_t cost = fitness + penalty * penaltyRate; if ((fitness > 0 && fitness < bestPart) || (fitness == bestPart && cost < bestCost)) { bestCost = cost; bestPart = fitness; bestDim = dim; bestNl = nl; bestNr = nr; } } } } printf("Chosen: %lu\n", bestPart); return tuple<uint8_t, uint8_t, uint8_t, size_t>(bestDim, bestNl, bestNr, bestCost); } tuple<uint8_t, uint8_t, uint8_t, size_t> TreeBuilder::BestSpanMinPenalty(const vector<Rule>& rules, Allower isAllowed, int penaltyRate) { size_t bestCost = std::numeric_limits<size_t>::max(); size_t bestPenalty = std::numeric_limits<size_t>::max(); uint8_t bestDim = 0; uint8_t bestNl = 0; uint8_t bestNr = 0; for (uint8_t delta = BitsPerNybble; delta <= MaxDelta; delta += BitsPerNybble) { for (uint8_t dim : allowableDims) { for (uint8_t nl = 0; nl + delta <= BitsPerField; nl += BitsPerNybble) { uint8_t nr = BitsPerField - nl - delta; unordered_map<Point, size_t> counts; size_t penalty = 0; for (const Rule& r : rules) { if (isAllowed(r, dim, nl, nr)) { SpanRange span = GetSpan(r, dim, nl, nr); for (Point i = span.first; i <= span.second; i++) { counts[i]++; } } else { penalty += 1; } } size_t fitness = 0; for (auto pair : counts) { if (pair.second > fitness) fitness = pair.second; } size_t cost = fitness + penalty * penaltyRate; if (penalty < bestPenalty || (penalty == bestPenalty && cost < bestCost)) { bestCost = cost; bestPenalty = penalty; bestDim = dim; bestNl = nl; bestNr = nr; } } } } return tuple<uint8_t, uint8_t, uint8_t, size_t>(bestDim, bestNl, bestNr, bestCost); } tuple<uint8_t, uint16_t, size_t> TreeBuilder::BestSplit(const vector<Rule>& rules) { size_t bestCost = numeric_limits<size_t>::max(); uint8_t bestDim = 0; uint16_t bestSplit = 0; for (uint8_t dim : splitDims) { set<Point> splits; for (const Rule& r : rules) { splits.insert(r.range[dim].high); } for (Point s : splits) { size_t lc = 0, rc = 0; for (const Rule& r : rules) { if (r.range[dim].low <= s) { lc++; } if (r.range[dim].high > s) { rc++; } } size_t cost = max(lc, rc); if (cost < bestCost) { bestCost = cost; bestDim = dim; bestSplit = s; } } } return tuple<uint8_t, uint16_t, size_t>(bestDim, bestSplit, bestCost); } bool AllowAll(const Rule& r, uint8_t dim, uint8_t nl, uint8_t nr) { return true; } bool BlockSplit(const Rule& r, uint8_t dim, uint8_t nl, uint8_t nr) { SpanRange s = GetSpan(r, dim, nl, nr); return s.first == s.second; } bool LimitedSplit(const Rule& r, uint8_t dim, uint8_t nl, uint8_t nr) { SpanRange s = GetSpan(r, dim, nl, nr); return s.first + 16 >= s.second; } void CleanRules(vector<Rule>& rules) { SortRules(rules); rules.erase(unique(rules.begin(), rules.end(), [](const Rule& r1, const Rule& r2) { return r1.priority == r2.priority;} ), rules.end()); } ByteCutsNode* TreeBuilder::BuildNode(const vector<Rule>& rules, vector<Rule>& remain, int depth, int penaltyRate) { return BuildNodeHelper(rules, remain, depth, LimitedSplit, [&](const vector<Rule>& rl, vector<Rule>& rmn, int dep, int pr) { return BuildNode(rl, rmn, dep, pr); }, penaltyRate); } ByteCutsNode* TreeBuilder::BuildPrimaryRoot(const vector<Rule>& rules, vector<Rule>& remain) { numNodes = 0; return BuildNode(rules, remain, 0, 5); } ByteCutsNode* TreeBuilder::BuildSecondaryRoot(const vector<Rule>& rules, vector<Rule>& remain) { numNodes = 0; auto node = BuildRootHelper(rules, remain, 0, LimitedSplit, [&](const vector<Rule>& rl, vector<Rule>& rmn, int depth, int pr) { return BuildNode(rl, rmn, depth, pr); }, 1); CleanRules(remain); return node; } ByteCutsNode* TreeBuilder::BuildCutNode(const vector<Rule>& rules, vector<Rule>& remain, int depth, Allower isAllowed, Builder builder, int penaltyRate, uint8_t d, uint8_t nl, uint8_t nr) { vector<Rule> inrules; for (const Rule& rule : rules) { if (isAllowed(rule, d, nl, nr)) { inrules.push_back(rule); } else { remain.push_back(rule); } } if (inrules.empty()) { // Shouldn't happen ByteCutsNode* node = new ByteCutsNode(); ByteCutsNode::LeafNode(*node, rules); remain.clear(); PrintRules(rules); return node; } size_t numChildren = 0x1 << (BitsPerField - nl - nr); unordered_map<vector<bool>, ByteCutsNode*> composer; ByteCutsNode** children = new ByteCutsNode*[numChildren]; for (size_t i = 0; i < numChildren; i++) { vector<bool> brl(inrules.size(), false); for (size_t j = 0; j < inrules.size(); j++) { const Rule& rule = inrules[j]; auto s = GetSpan(rule, d, nl, nr); if (s.first <= i && i <= s.second) { brl[j] = true; } } if (!composer.count(brl)) { vector<Rule> rl; for (size_t j = 0; j < inrules.size(); j++) { if (brl[j]){ rl.push_back(inrules[j]); } } auto node = builder(rl, remain, depth + 1, penaltyRate); composer[brl] = node; } children[i] = composer[brl]; } ByteCutsNode* node = new ByteCutsNode(); ByteCutsNode::CutNode(*node, d, nl, nr, children); return node; } ByteCutsNode* TreeBuilder::BuildRootHelper(const vector<Rule>& rules, vector<Rule>& remain, int depth, Allower isAllowed, Builder builder, int penaltyRate) { numNodes++; if (rules.size() <= leafSize) { ByteCutsNode* node = new ByteCutsNode(); ByteCutsNode::LeafNode(*node, rules); return node; } else { vector<Rule> remainCost, remainPart, remainPenalty; uint8_t d, nl, nr; size_t c; tie(d, nl, nr, c) = BestSpan(rules, isAllowed, penaltyRate); ByteCutsNode* costNode = BuildCutNode(rules, remainCost, depth, isAllowed, builder, penaltyRate, d, nl, nr); tie(d, nl, nr, c) = BestSpanMinPart(rules, isAllowed, penaltyRate); ByteCutsNode* partNode = BuildCutNode(rules, remainPart, depth, isAllowed, builder, penaltyRate, d, nl, nr); tie(d, nl, nr, c) = BestSpanMinPenalty(rules, isAllowed, penaltyRate); ByteCutsNode* penaltyNode = BuildCutNode(rules, remainPenalty, depth, isAllowed, builder, penaltyRate, d, nl, nr); size_t minRemain = min({remainCost.size(), remainPart.size(), remainPenalty.size()}); if (remainCost.size() == minRemain) { remain = remainCost; delete partNode; delete penaltyNode; return costNode; } else if (remainPart.size() == minRemain) { remain = remainPart; delete costNode; delete penaltyNode; return partNode; } else { remain = remainPenalty; delete costNode; delete partNode; return penaltyNode; } } } ByteCutsNode* TreeBuilder::BuildNodeHelper(const vector<Rule>& rules, vector<Rule>& remain, int depth, Allower isAllowed, Builder builder, int penaltyRate) { numNodes++; if (rules.size() <= leafSize) { ByteCutsNode* node = new ByteCutsNode(); ByteCutsNode::LeafNode(*node, rules); return node; } else { uint8_t d, nl, nr; size_t c; tie(d, nl, nr, c) = BestSpan(rules, isAllowed, penaltyRate); uint8_t ds; uint16_t ss; size_t cs; tie(ds, ss, cs) = BestSplit(rules); size_t cMin = min(c, cs); if (cMin == rules.size()) { // degenerate case: no improvement ByteCutsNode* node = new ByteCutsNode(); ByteCutsNode::LeafNode(*node, rules); return node; } else if (c == cMin) { return BuildCutNode(rules, remain, depth, isAllowed, builder, penaltyRate, d, nl, nr); } else { madeHyperSplit = true; vector<Rule> lefts; vector<Rule> rights; for (const Rule& r : rules) { if (r.range[ds].low <= ss) lefts.push_back(r); if (r.range[ds].high > ss) rights.push_back(r); } ByteCutsNode* lc = builder(lefts, remain, depth + 1, penaltyRate); ByteCutsNode* rc = builder(rights, remain, depth + 1, penaltyRate); ByteCutsNode* node = new ByteCutsNode(); ByteCutsNode::SplitNode(*node, ds, ss, lc, rc); return node; } } }
#include <string.h> #include <vector> #include <iostream> #include <stdio.h> #include <map>
#include <iostream> using namespace std; int main() { double n, m; char op; cout << "Enter operation: "; cin >> op; if (op != '+' && op != '-' && op != '*' && op != '/') { cout << "Invalid operation\n"; return -1; } cout << "Enter arg1: "; cin >> n; cout << "Enter arg2: "; cin >> m; switch (op) { case '+': cout << "Sum: " << n + m << endl; break; case '-': cout << "Sub: " << n - m << endl; break; case '*': cout << "Mult: " << n * m << endl; break; case '/': cout << "Div: " << n / m << endl; break; default: break; } return 0; }
#include <iostream> #include <cmath> #include "point.h" #include "integrate.h" #include "Double.h" int main() { const unsigned int k = 2; Double u[k][k][k]; Double phi[k][k]; Double omega[k]; for (unsigned int j=0; j<k; ++j) { double x = 1.*j/(k-1); omega[j].value = 1./k; phi[0][j].value = 1.; for (unsigned int i=1; i<k; ++i) phi[j][i].value = phi[i-1][j].value*j/k; } Double point_val; Double integral; for (unsigned int i=0; i<1000; ++i) { #ifndef FACTOR point_val.operator+=(point<k>(u, phi[1])); integral.operator+=(integrate<k,k>(u, phi, omega)); #else point_val.operator+=(point_fact<k>(u, phi[1])); integral.operator+=(integrate_fact<k,k>(u, phi, omega)); #endif } std::cout << "Evaluate " << point_val.value << ' ' << integral.value << std::endl; }
#ifndef QXTMETAOBJECT_H /**************************************************************************** ** Copyright (c) 2006 - 2011, the LibQxt project. ** See the Qxt AUTHORS file for a list of authors and copyright holders. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the LibQxt project nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** <http://libqxt.org> <foundation@libqxt.org> *****************************************************************************/ #define QXTMETAOBJECT_H #include <QMetaObject> #include <QVariant> #include <QGenericArgument> #include <typeinfo> #include "qxtnullable.h" #include "qxtglobal.h" QT_FORWARD_DECLARE_CLASS(QByteArray) class QxtBoundArgument; class QxtBoundFunction; #define QXT_PROTO_10ARGS(T) T p1 = T(), T p2 = T(), T p3 = T(), T p4 = T(), T p5 = T(), T p6 = T(), T p7 = T(), T p8 = T(), T p9 = T(), T p10 = T() #define QXT_PROTO_9ARGS(T) T p2 = T(), T p3 = T(), T p4 = T(), T p5 = T(), T p6 = T(), T p7 = T(), T p8 = T(), T p9 = T(), T p10 = T() #define QXT_IMPL_10ARGS(T) T p1, T p2, T p3, T p4, T p5, T p6, T p7, T p8, T p9, T p10 class QXT_CORE_EXPORT QxtGenericFunctionPointer { template<typename FUNCTION> friend QxtGenericFunctionPointer qxtFuncPtr(FUNCTION funcPtr); public: QxtGenericFunctionPointer(const QxtGenericFunctionPointer& other) { funcPtr = other.funcPtr; typeName = other.typeName; } typedef void(voidFunc)(); voidFunc* funcPtr; QByteArray typeName; protected: QxtGenericFunctionPointer(voidFunc* ptr, const QByteArray& typeIdName) { funcPtr = ptr; typeName = typeIdName; } }; template<typename FUNCTION> QxtGenericFunctionPointer qxtFuncPtr(FUNCTION funcPtr) { return QxtGenericFunctionPointer(reinterpret_cast<QxtGenericFunctionPointer::voidFunc*>(funcPtr), typeid(funcPtr).name()); } namespace QxtMetaObject { QXT_CORE_EXPORT QByteArray methodName(const char* method); QXT_CORE_EXPORT QByteArray methodSignature(const char* method); QXT_CORE_EXPORT bool isSignalOrSlot(const char* method); QXT_CORE_EXPORT QxtBoundFunction* bind(QObject* recv, const char* invokable, QXT_PROTO_10ARGS(QGenericArgument)); QXT_CORE_EXPORT QxtBoundFunction* bind(QObject* recv, const char* invokable, QVariant p1, QXT_PROTO_9ARGS(QVariant)); QXT_CORE_EXPORT bool connect(QObject* sender, const char* signal, QxtBoundFunction* slot, Qt::ConnectionType type = Qt::AutoConnection); QXT_CORE_EXPORT bool invokeMethod(QObject* object, const char* member, const QVariant& arg0 = QVariant(), const QVariant& arg1 = QVariant(), const QVariant& arg2 = QVariant(), const QVariant& arg3 = QVariant(), const QVariant& arg4 = QVariant(), const QVariant& arg5 = QVariant(), const QVariant& arg6 = QVariant(), const QVariant& arg7 = QVariant(), const QVariant& arg8 = QVariant(), const QVariant& arg9 = QVariant()); QXT_CORE_EXPORT bool invokeMethod(QObject* object, const char* member, Qt::ConnectionType type, const QVariant& arg0 = QVariant(), const QVariant& arg1 = QVariant(), const QVariant& arg2 = QVariant(), const QVariant& arg3 = QVariant(), const QVariant& arg4 = QVariant(), const QVariant& arg5 = QVariant(), const QVariant& arg6 = QVariant(), const QVariant& arg7 = QVariant(), const QVariant& arg8 = QVariant(), const QVariant& arg9 = QVariant()); } /*! * \relates QxtMetaObject * Refers to the n'th parameter of QxtBoundFunction::invoke() or of a signal connected to * a QxtBoundFunction. * \sa QxtMetaObject::bind */ #define QXT_BIND(n) QGenericArgument("QxtBoundArgument", reinterpret_cast<void*>(n)) #endif // QXTMETAOBJECT_H
class Mother { public: Mother(); void sayHi(); int getSomeVar(); ~Mother(); private: int var; protected: int someVar; }; class Daughter:public Mother { public: Daughter(); ~Daughter(); };
#pragma once #include <wrl/client.h> #include <memory> #include <string> class Shader { Microsoft::WRL::ComPtr<struct ID3D11VertexShader> m_pVsh; Microsoft::WRL::ComPtr<struct ID3D11PixelShader> m_pPsh; Microsoft::WRL::ComPtr<struct ID3D11InputLayout> m_pInputLayout; std::shared_ptr<class InputAssemblerSource> m_IASource; std::shared_ptr<class ConstantBuffer> m_constant; std::shared_ptr<class Texture> m_texture; public: Shader(); bool Initialize( const Microsoft::WRL::ComPtr<struct ID3D11Device> &pDevice , const std::string &shaderSource, const std::wstring &textureFile); void Draw( const Microsoft::WRL::ComPtr<struct ID3D11DeviceContext> &pDeviceContext); void Animation(); private: bool createShaders( const Microsoft::WRL::ComPtr<struct ID3D11Device> &pDevice , const std::string &shaderSource, const std::string &vsFunc, const std::string &psFunc); };
#pragma once #include <boost/scoped_ptr.hpp> #include <boost/scoped_array.hpp> #include <unistd.h> #include "Dynamixel.hpp" #include "Motor.h" #define maxDynamixel 12 #define numServo 2 class CActuator { public: unsigned int baudRate; boost::asio::io_service io; boost::scoped_ptr<boost::thread> serialThreadArm; boost::scoped_ptr<SerialComm> serialArm; boost::scoped_ptr<boost::thread> serialThreadGripper; boost::scoped_ptr<SerialComm> serialGripper; boost::scoped_array<ServoControl> servoControls; Motor joint[maxDynamixel]; int jointInitAng[maxDynamixel]; CActuator() { SerialInitArm(); SerialInitGripper(); ServoInit(); } CActuator(int jointNum, int* jointID, int* _jointInitAng, int* jointSpeed) { Initialize(jointNum, jointID, _jointInitAng, jointSpeed); SerialInitArm(); SerialInitGripper(); ServoInit(); } ~CActuator() { } void Initialize(int jointNum, int* jointID, int* _jointInitAng, int* jointSpeed) { joint[0].SetNum(jointNum); for(int i=0; i<jointNum; i++) { jointInitAng[i] = _jointInitAng[i]; joint[i].SetID(jointID[i]); // Set joint motor's ID: 0~253 joint[i].SetSpeed(jointSpeed[i]); // Speed range (joint motor): 0~1023 joint[i].SetAng(jointInitAng[i]); // Angle range: -150(deg)~150(deg) } } // Initialize serial communication void SerialInitArm() { baudRate = 57600; std::string port("/dev/ttyUSB0"); std::cout << "Arm "; serialArm.reset(new SerialComm(io, baudRate, port)); SetMargin(); serialThreadArm.reset(new boost::thread(boost::bind(&boost::asio::io_service::run, &io))); } void SerialInitGripper() { baudRate = 115200; std::string port("/dev/ttyO2"); std::cout << "Gripper "; serialGripper.reset(new SerialComm(io, baudRate, port)); SetMargin(); serialThreadGripper.reset(new boost::thread(boost::bind(&boost::asio::io_service::run, &io))); } // Initialize servo motor void ServoInit() { const float minAngle = 0; const float midAngle = 90; const float maxAngle = 180; const int minPWM = 400; const int maxPWM = 1800; const std::string servoName[numServo] ={"P8_19", "P9_14"}; servoControls.reset(new ServoControl[numServo] { ServoControl(servoName[0], midAngle, minAngle, maxAngle, minPWM, maxPWM), ServoControl(servoName[1], midAngle, minAngle, maxAngle, minPWM, maxPWM)}); for (int i=0; i<numServo; i++) servoControls[i].Enable(); } // Set servo motor angle void ServoSetAng(int idx, int angle) { if (idx < numServo) { servoControls[idx].SetAngle(angle); servoControls[idx].UpdatePWMSignal(); } else std::cout<<"Out of servo idx"<<std::endl; } // Set servo motor to initialize angle void ExeInitAng() { for (int i=0; i<joint[0].GetNum(); i++) joint[i].SetAng(jointInitAng[i]); // Angle range: -150(deg)~150(deg) ExeAng(); } void SetMargin() { unsigned char buffer[12]; buffer[0] = 0xff; buffer[1] = 0xff; buffer[2] = BROADCASTING_ID; buffer[3] = 7; buffer[4] = WRITE_DATA; buffer[5] = CW_COMPLIANCE_MARGIN; buffer[6] = 5; buffer[7] = 5; buffer[8] = 0x32; buffer[9] = 0x32; buffer[10] = ~(buffer[2]+buffer[3]+buffer[4]+buffer[5]+buffer[6]+buffer[7]+buffer[8]+buffer[9]); serialArm->write(buffer, 11); } void ExeJointSpeed() { unsigned char buffer[50]; unsigned int idx = 7; unsigned char checksum = 0; int speed = 0; buffer[0] = 0xff; buffer[1] = 0xff; buffer[2] = BROADCASTING_ID; buffer[3] = 3 * joint[0].GetNum() + 4; buffer[4] = SYNC_WRITE; buffer[5] = MOVING_SPEED; buffer[6] = 2; for (int i=2; i<=6; i++) checksum += buffer[i]; for (int i=0; i<joint[0].GetNum(); i++) { speed = joint[i].GetBiasedSpeed(); buffer[idx++] = joint[i].GetID(); buffer[idx++] = lowbyte(speed); buffer[idx++] = highbyte(speed); checksum += (buffer[idx-1] + buffer[idx-2] + buffer[idx-3]); } buffer[idx++] = ~checksum; serialArm->write(buffer, idx); } void ExeAng() { unsigned char buffer[50]; unsigned int idx = 7; unsigned char checksum = 0; int angle = 0; buffer[0] = 0xff; buffer[1] = 0xff; buffer[2] = BROADCASTING_ID; buffer[3] = 3 * joint[0].GetNum() + 4; buffer[4] = SYNC_WRITE; buffer[5] = GOAL_POSITION; buffer[6] = 2; for (int i=2; i<=6; i++) checksum += buffer[i]; for (int i=0; i<joint[0].GetNum(); i++) { angle = joint[i].GetBiasedAng(); buffer[idx++] = joint[i].GetID(); buffer[idx++] = lowbyte(angle); buffer[idx++] = highbyte(angle); checksum += (buffer[idx-1] + buffer[idx-2] + buffer[idx-3]); } buffer[idx++] = ~checksum; serialArm->write(buffer, idx); } int ReadOneRegistor(int ID, int REG) { unsigned char txBuffer[10]; unsigned char rxBuffer[10]; int rxBufLen; txBuffer[0] = 0xff; txBuffer[1] = 0xff; txBuffer[2] = ID; txBuffer[3] = 0x04; txBuffer[4] = READ_DATA; txBuffer[5] = REG; txBuffer[6] = 0x01; txBuffer[7] = ~(txBuffer[2]+txBuffer[3]+txBuffer[4]+txBuffer[5]+txBuffer[6]); serialArm->write(txBuffer,8); rxBufLen = serialArm->read_all(rxBuffer,7); if((rxBufLen==7)&&(rxBuffer[rxBufLen-7]==0xff)&&(rxBuffer[rxBufLen-6]==0xff)) return rxBuffer[rxBufLen-2]; return 0; } int SetOneRegistor(int ID, int REG, int DATA) { unsigned char txBuffer[10]; unsigned char rxBuffer[10]; int rxBufLen; txBuffer[0] = 0xff; txBuffer[1] = 0xff; txBuffer[2] = ID; txBuffer[3] = 0x04; txBuffer[4] = WRITE_DATA; txBuffer[5] = REG; txBuffer[6] = (DATA&0x00ff); txBuffer[7] = ~(txBuffer[2]+txBuffer[3]+txBuffer[4]+txBuffer[5]+txBuffer[6]); serialArm->write(txBuffer,8); rxBufLen = serialArm->read_all(rxBuffer,6); if((rxBufLen==6)&&(rxBuffer[0]==0xff)&&(rxBuffer[1]==0xff)&&(rxBuffer[4]==0x00)) return 1; return 0; } int SetTwoRegistor(int ID, int REG, int DATA) { unsigned char txBuffer[10]; unsigned char rxBuffer[10]; int rxBufLen; txBuffer[0] = 0xff; txBuffer[1] = 0xff; txBuffer[2] = ID; txBuffer[3] = 0x05; txBuffer[4] = WRITE_DATA; txBuffer[5] = REG; txBuffer[6] = (DATA & 0x00ff); txBuffer[7] = ((DATA & 0xff00) >> 8); txBuffer[8] = ~(txBuffer[2]+txBuffer[3]+txBuffer[4]+txBuffer[5]+txBuffer[6]+txBuffer[7]); serialArm->write(txBuffer,9); rxBufLen = serialArm->read_all(rxBuffer,6); if((rxBufLen==6)&&(rxBuffer[0]==0xff)&&(rxBuffer[1]==0xff)&&(rxBuffer[4]==0x00)) return 1; return 0; } void SendGripperCommand(int selection) { unsigned char txBuffer[10]; unsigned char rxBuffer[10]; int rxBufLen; if(selection == 17) { int value; std::cout << "Position value = " << std::endl; std::cin >> value; txBuffer[0] = 0x70; txBuffer[1] = ((value & 0xff00) >> 8); txBuffer[2] = (value & 0x00ff); txBuffer[3] = 0x0d; serialGripper->write(txBuffer,4); } else { if(selection == 11) txBuffer[0] = 0x69; else if(selection == 12) txBuffer[0] = 0x6f; else if(selection == 13) txBuffer[0] = 0x63; else if(selection == 14) txBuffer[0] = 0x71; else if(selection == 15) txBuffer[0] = 0x75; else if(selection == 16) txBuffer[0] = 0x72; else { std::cout << "Wrong Input!!" << std::endl; return; } txBuffer[1] = 0x0d; serialGripper->write(txBuffer,2); } if(selection == 14) { rxBufLen = serialGripper->read_all(rxBuffer,4); if((rxBuffer[rxBufLen-4] == 0x70) && (rxBuffer[rxBufLen-1] == 0x0d)) { int encoderPosition = ((rxBuffer[rxBufLen-3] & 0x00ff) << 8) + (rxBuffer[rxBufLen-2] & 0x00ff); std::cout << "Encoder position = " << encoderPosition << std::endl; } } else { rxBufLen = serialGripper->read_all(rxBuffer,1); std::cout << rxBuffer[rxBufLen-1] << std::endl; } } };
#pragma once #include "LayerNode.hpp" #include "Utils/NotNull.hpp" #include <algorithm> #include <cmath> template<class Type> struct ReLULayerNode : LayerNode<Type> // add passthrough LayerNode that doesn't need numOutputs because it should get them from parent { ReLULayerNode(NotNull<ComputationNode<Type>> inputLayer) : m_inputLayer(inputLayer) , m_errors(inputLayer->getNumOutputs()) , m_outputs(inputLayer->getNumOutputs()) { } void forwardPass() override { auto inputs = m_inputLayer->getOutputValues(); for(auto i = 0u; i < m_outputs.size(); ++i) { m_outputs[i] = std::max(inputs[i], Type{}); } std::fill(std::begin(m_errors), std::end(m_errors), Type{}); } std::size_t getNumOutputs() const override { return m_outputs.size(); } ArrayView<Type const> getOutputValues() const override { return m_outputs; } void backPropagate(ArrayView<Type const> errors) override { for(std::size_t i = 0; i < errors.size(); ++i) { m_errors[i] += m_inputLayer->getOutputValues()[i] > 0.0 ? errors[i] : Type{}; } } void backPropagationPass() override { m_inputLayer->backPropagate(m_errors); // TODO this may go to base class because it is the same for every activation } private: NotNull<ComputationNode<Type>> m_inputLayer; std::vector<Type> m_errors; std::vector<Type> m_outputs; };
#include "ExCoefficients.h" ExCoefficients::ExCoefficients(const Eigen::MatrixXd &f1_mat, const Eigen::MatrixXd &f2_mat) : m_mat_f1(f1_mat), m_mat_f2(f2_mat) { m_mat_f1x = diff_about_x(m_mat_f1); m_mat_f1y = diff_about_y(m_mat_f1); m_mat_f2x = diff_about_x(m_mat_f2); m_mat_f2y = diff_about_y(m_mat_f2); } ExCoefficients::~ExCoefficients() { } itv ExCoefficients::estimate_range(const Eigen::MatrixXd &src, const itv &xrange, const itv &yrange) { itv result(0, 0); for (int i = 0; i < src.rows(); ++i) { for (int j = 0; j < src.cols(); ++j) { result += pow(xrange, i) * pow(yrange, j) * src(i, j); } } return itv(result.lower(), result.upper()); } IntervalVec<itv> ExCoefficients::F_value(const itv &xrange, const itv &yrange) { return IntervalVec<itv>(estimate_range(m_mat_f1, xrange, yrange), estimate_range(m_mat_f2, xrange, yrange)); } MatrixXd ExCoefficients::diff_about_x(const MatrixXd &src) { if (src.rows() == 1) { MatrixXd result(1, 1); result << 0; return result; } MatrixXd result(src.rows() - 1, src.cols()); for (int i = 1; i < src.rows(); i++) { for (int j = 0; j < src.cols(); j++) { result(i - 1, j) = src(i, j) * i; } } return result; } MatrixXd ExCoefficients::diff_about_y(const MatrixXd &src) { if (src.cols() == 1) { MatrixXd result(1, 1); result << 0; return result; } MatrixXd result(src.rows(), src.cols() - 1); for (int i = 0; i < src.rows(); ++i) { for (int j = 1; j < src.cols(); ++j) { result(i, j - 1) = src(i, j) * j; } } return result; } IntervalMat<itv> ExCoefficients::F_prime_value(const itv &xrange, const itv &yrange) { return IntervalMat<itv>(estimate_range(m_mat_f1x, xrange, yrange), estimate_range(m_mat_f1y, xrange, yrange), estimate_range(m_mat_f2x, xrange, yrange), estimate_range(m_mat_f2y, xrange, yrange)); } IntervalVec<itv> ExCoefficients::calculate_K(const IntervalVec<itv> &initial) { IntervalMat<itv> F_prime_value_result = F_prime_value(initial.x, initial.y); Region Y = F_prime_value_result.mid_value().inverse_mat(); vec2d mX = vec2d(mid(initial.x), mid(initial.y)); vec2d FmX = F_value(itv(mX.x, mX.x), itv(mX.y, mX.y)).mid_vec(); IntervalMat<itv> R = Region(1.0, 0.0, 0.0, 1.0) - Y*F_prime_value_result; IntervalVec<itv> delta = initial - mX; IntervalVec<itv> K = (mX - Y*FmX) + R*delta; return K; }
#include "treeface/scene/guts/Geometry_guts.h" #include <treecore/ArrayRef.h> using namespace treecore; namespace treeface { Geometry::Guts::Guts( const VertexTemplate& vtx_temp, GLPrimitive primitive, bool is_dynamic ) : vtx_temp( vtx_temp ) , primitive( primitive ) , dynamic( is_dynamic ) , buf_vtx( new GLBuffer( TFGL_BUFFER_VERTEX, is_dynamic ? TFGL_BUFFER_DYNAMIC_DRAW : TFGL_BUFFER_STATIC_DRAW ) ) , buf_idx( new GLBuffer( TFGL_BUFFER_INDEX, is_dynamic ? TFGL_BUFFER_DYNAMIC_DRAW : TFGL_BUFFER_STATIC_DRAW ) ) , host_data_vtx( vtx_temp.vertex_size() ) {} Geometry::Guts::~Guts() { treecore_assert( user_head == nullptr ); treecore_assert( user_tail == nullptr ); } void Geometry::Guts::upload_data() { treecore_assert( !drawing ); treecore_assert( buf_vtx->is_bound() ); treecore_assert( buf_idx->is_bound() ); if (dirty) { num_idx = host_data_idx.size(); buf_vtx->upload_data( host_data_vtx.get_raw_data_ptr(), host_data_vtx.num_byte() ); buf_idx->upload_data( ArrayRef<IndexType>( host_data_idx ) ); if (!dynamic) { host_data_vtx.clear(); host_data_idx.clear(); } dirty = false; } } void Geometry::Guts::invalidate_user_uniform_cache() { for (VisualObject::Impl* curr = user_head; curr != nullptr; curr = curr->same_geom_next) curr->uniform_cache_dirty = true; } } // namespace treeface
#include "GamePch.h" #include "AI_ChargeUp.h" void AI_ChargeUp::LoadFromXML( tinyxml2::XMLElement* data ) { const char* anim = data->Attribute( "anim" ); m_Anim = WSID(anim); m_Duration = 2.0f; data->QueryFloatAttribute( "duration", &m_Duration ); } void AI_ChargeUp::Init( Hourglass::Entity* entity ) { m_Timer = 0.0f; entity->GetComponent<hg::Animation>()->Play( m_Anim, 1.0f ); } Hourglass::IBehavior::Result AI_ChargeUp::Update( Hourglass::Entity* entity ) { m_Timer += hg::g_Time.Delta(); return (m_Timer < m_Duration) ? kRUNNING : kSUCCESS; } Hourglass::IBehavior* AI_ChargeUp::MakeCopy() const { AI_ChargeUp* copy = (AI_ChargeUp*)IBehavior::Create( SID(AI_ChargeUp) ); copy->m_Anim = m_Anim; copy->m_Duration = m_Duration; return copy; }
/* ----------------------------------------------------------------------------------------- Laboratory : POO2 - Laboratoire 14 File : test.cpp Author : Thomas Benjamin, Gobet Alain Date : 22.03.2018 Class : POO - A Goal : Definition of a class Test to test all the features of the class String Remark(s) : - ---------------------------------------------------------------------------------------- */ #include <iostream> #include <stdexcept> #include "test.h" #include "cstring.h" using namespace std; //si temps, créer fct avec lamba expr pour //pour le return bool // if equals return true, else attendu/obtenu return false //si temps, facto deux-trois prem op avec constante string pour affich //plus choisir nb char print pour affichage homogene Test::Test() { constructorTest(); lenTest(); getStrTest(); getCharTest(); substringTest(); equalsStringTest(); equalsCharPointerTest(); copyStringTest(); copyCharPointerTest(); appendStringTest(); appendCharPointerTest(); appendSelfStringTest(); appendSelfCharPointerTest(); reserveAndCopyTest(); operatorStringPlusStringTest(); operatorStringPlusCharPointerTest(); operatorCharPointerPlusStringTest(); operatorEqualStringTest(); operatorEqualCharPointerTest(); operatorPlusEqualStringTest(); operatorPlusEqualCharPointerTest(); operatorCinTest(); } //Goal: Test the constructors //Arguments: - //Exceptions: - bool Test::constructorTest() const{ cout << "------------Constructor test------------" << endl << endl; cout << "1) String(): " << endl; String emptyStr = String(); cout << "Expected value: " << endl; cout << "Obtained value: " << emptyStr.getStr() << endl << endl; cout << "2) String(const char* s): " << endl; char* charPtr = new char[4]; *(charPtr) = 'h'; *(charPtr + 1) = 'e'; *(charPtr + 2) = 'y'; *(charPtr + 3) = '\0'; String strCharPtr = String(charPtr); cout << "Expected value: " << charPtr << endl; cout << "Obtained value: " << (strCharPtr.getStr()) << endl << endl; delete[] charPtr; cout << "3) String(const String& s): " << endl; String strString = String(strCharPtr); cout << "Expected value: " << (strCharPtr.getStr()) << endl; cout << "Obtained value: " << (strString.getStr()) << endl << endl; cout << "4) String(char): " << endl; String strChar = String('?'); cout << "Expected value: ?" << endl; cout << "Obtained value: " << (strChar.getStr()) << endl << endl; cout << "5) String(int): " << endl; String strInt = String(17456); cout << "Expected value: 17456" << endl; cout << "Obtained value: " << (strInt.getStr()) << endl << endl; cout << "6) String(double): " << endl; String strDouble = String(-1.144); cout << "Expected value: -1.144000" << endl; cout << "Obtained value: " << (strDouble.getStr()) << endl << endl; cout << "7) String(bool): " << endl; String strBool = String(true); cout << "Expected value: true" << endl; cout << "Obtained value: " << (strBool.getStr()) << endl << endl; cout << "8) String(bool copy): " << endl; String strnCopy = String(strBool, 3); cout << "Expected value: tru" << endl; cout << "Obtained value: " << (strnCopy.getStr()) << endl << endl; } //Goal: Test the len() method //Arguments: - //Exceptions: - bool Test::lenTest() const{ String strInt(17456); cout << "------------len() test------------" << endl << endl; cout << "Expected value: 5" << endl; cout << "Obtained value: " << strInt.len() << endl << endl; } //Goal: Test the getStr() method //Arguments: - //Exceptions: - bool Test::getStrTest() const{ String strInt(17456); cout << "------------getStr() test------------" << endl << endl; cout << "Expected value: 17456" << endl; cout << "Obtained value: " << (strInt.getStr()) << endl << endl; } //Goal: Test the getChar() method //Arguments: - //Exceptions: invalid_argument bool Test::getCharTest() const{ String strInt(17456); cout << "------------getChar() test------------" << endl << endl; cout << "1) Basic test" << endl; cout << "Expected value: 4" << endl; cout << "Obtained value: " << strInt.getChar(2) << endl << endl; cout << "2) Modification test" << endl; strInt.getChar(2) = '5'; cout << "Expected value: 5" << endl; cout << "Obtained value: " << strInt.getChar(2) << endl << endl; cout << "3) Out of limit test" << endl; cout << "Expected value: The index value must be inferior to str's length" << endl; cout << "Obtained value: "; try{ strInt.getChar(10); }catch(const invalid_argument& e){ cout << e.what() << endl << endl; } } //Goal: Test the subString() method //Arguments: - //Exceptions: invalid_argument bool Test::substringTest() const{ String strInt(17456); cout << "------------substring() test------------" << endl << endl; cout << "1) Basic test:" << endl; cout << "Expected value: 45" << endl; cout << "Obtained value: " << strInt.subString(2, 3) << endl << endl; cout << "2) Inverted limits test:" << endl; cout << "Expected value: 45" << endl; cout << "Obtained value: " << strInt.subString(3, 2) << endl << endl; cout << "3) Out of limits test:" << endl; cout << "Expected value: The index values must be inferior to str's length" << endl; cout << "Obtained value: "; try{ strInt.subString(2, 10); }catch(const invalid_argument& e){ cout << e.what() << endl << endl; } } //Goal: Test the equals() method with a String //Arguments: - //Exceptions: - bool Test::equalsStringTest() const{ String strInt1(17456); String strInt2(17456); String strInt3(174456); cout << "------------equals(const String&) test------------" << endl << endl; cout << "1) True result test: " << endl; cout << "Expected value: 1" << endl; cout << "Obtained value: " << strInt1.equals(strInt2) << endl << endl; cout << "2) False result test: " << endl; cout << "Expected value: 0" << endl; cout << "Obtained value: " << strInt1.equals(strInt3) << endl << endl; } //Goal: Test the equals() method with a char* //Arguments: - //Exceptions: - bool Test::equalsCharPointerTest() const{ String strInt(17); char* charPtr1 = new char[3]; *(charPtr1) = '1'; *(charPtr1 + 1) = '7'; *(charPtr1 + 2) = '\0'; char* charPtr2 = new char[2]; *(charPtr2) = 'h'; *(charPtr2 + 1) = '\0'; cout << "------------equals(const char*) test------------" << endl << endl; cout << "1) True result test: " << endl; cout << "Expected value: 1" << endl; cout << "Obtained value: " << strInt.equals(charPtr1) << endl << endl; cout << "2) False result test: " << endl; cout << "Expected value: 0" << endl; cout << "Obtained value: " << strInt.equals(charPtr2) << endl << endl; delete[] charPtr1; delete[] charPtr2; } //Goal: Test the copy() method with a String //Arguments: - //Exceptions: - bool Test::copyStringTest() const{ String strInt1(17456); String strInt2(1235); cout << "------------copy(const String&) test------------" << endl << endl; cout << "Expected value: 1235" << endl; cout << "Obtained value: " << strInt1.copy(strInt2) << endl << endl; } //Goal: Test the copy() method with a char* //Arguments: - //Exceptions: - bool Test::copyCharPointerTest() const{ String strInt(2342); char* charPtr = new char[3]; *(charPtr) = '1'; *(charPtr + 1) = '7'; *(charPtr + 2) = '\0'; cout << "------------copy(const char*) test------------" << endl << endl; cout << "Expected value: 17" << endl; cout << "Obtained value: " << strInt.copy(charPtr) << endl << endl; delete[] charPtr; } //Goal: Test the append() method with a String //Arguments: - //Exceptions: - bool Test::appendStringTest() const{ String strInt(17456); cout << "------------append(const String&) test------------" << endl << endl; cout << "Expected value: 1745617456" << endl; cout << "Obtained value: " << strInt.append(strInt) << endl << endl; } //Goal: Test the append() method with a char* //Arguments: - //Exceptions: - bool Test::appendCharPointerTest() const{ String strInt(2342); char* charPtr = new char[3]; *(charPtr) = '1'; *(charPtr + 1) = '7'; *(charPtr + 2) = '\0'; cout << "------------append(const char*) test--------------" << endl << endl; cout << "Expected value: 234217" << endl; cout << "Obtained value: " << strInt.append(charPtr) << endl << endl; delete[] charPtr; } //Goal: Test the appendSelf() method with a String //Arguments: - //Exceptions: - bool Test::appendSelfStringTest() const{ String strInt1(17456); String strInt2(1235); cout << "------------appendSelf(const String&) test----------" << endl << endl; cout << "1) Basic test: " << endl; cout << "Expected value: 174561235" << endl; strInt1.appendSelf(strInt2); cout << "Obtained value: " << strInt1 << endl << endl; cout << "2) Append this to this test: " << endl; cout << "Expected value: 12351235" << endl; strInt2.appendSelf(strInt2); cout << "Obtained value: " << strInt2 << endl << endl; } //Goal: Test the appendSelf() method with a char* //Arguments: - //Exceptions: - bool Test::appendSelfCharPointerTest() const{ String strInt(2342); char* charPtr = new char[3]; *(charPtr) = '1'; *(charPtr + 1) = '7'; *(charPtr + 2) = '\0'; cout << "------------appendSelf(const char*) test--------------" << endl << endl; cout << "Expected value: 234217" << endl; strInt.appendSelf(charPtr); cout << "Obtained value: " << strInt << endl << endl; delete[] charPtr; } //Goal: Test the reserveAndCopy() method with //Arguments: - //Exceptions: - bool Test::reserveAndCopyTest() const{ String strInt(2342); char* charPtr = new char[3]; *(charPtr) = '1'; *(charPtr + 1) = '7'; *(charPtr + 2) = '\0'; cout << "------------reserveAndCopy(const char* s) test----------" << endl << endl; cout << "Expected value: 17" << endl; strInt.reserveAndCopy(charPtr); cout << "Obtained value: " << strInt << endl << endl; delete[] charPtr; } //Goal: Test the overload of the = operator with a String //Arguments: - //Exceptions: - bool Test::operatorEqualStringTest() const { String strCharPtr1("Test"); String strEqual = String(); strEqual = strCharPtr1; cout << "-------------------- = String test-------------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strEqual << endl << endl; } //Goal: Test the overload of the = operator with a char* //Arguments: - //Exceptions: - bool Test::operatorEqualCharPointerTest() const { String strEqual = String(); strEqual = "Test"; cout << "-------------------- = String test-------------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strEqual << endl << endl; } //Goal: Test the overload of the + operator with String + String //Arguments: - //Exceptions: - bool Test::operatorStringPlusStringTest() const { String strCharPtr1("Te"); String strCharPtr2("st"); String strPlus = strCharPtr1 + strCharPtr2; cout << "------------------String + String test-----------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strPlus << endl << endl; } //Goal: Test the overload of the + operator with String + char* //Arguments: - //Exceptions: - bool Test::operatorStringPlusCharPointerTest() const { String strCharPtr("Te"); String strPlus = strCharPtr + "st"; cout << "------------------String + char* test-----------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strPlus << endl << endl; } //Goal: Test the overload of the + operator with char* + String //Arguments: - //Exceptions: - bool Test::operatorCharPointerPlusStringTest() const { String strCharPtr("st"); String strPlus = "Te" + strCharPtr; cout << "------------------String + char* test-----------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strPlus << endl << endl; } //Goal: Test the overload of the += operator with a String //Arguments: - //Exceptions: - bool Test::operatorPlusEqualStringTest() const { String strPlusEqual = String("Te"); String strPlusEqual2 = String("st"); strPlusEqual += strPlusEqual2; cout << "-------------------- += String test-------------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strPlusEqual << endl << endl; } //Goal: Test the overload of the += operator with a char* //Arguments: - //Exceptions: - bool Test::operatorPlusEqualCharPointerTest() const { String strPlusEqual = String("Te"); strPlusEqual += "st"; cout << "-------------------- += String test-------------------" << endl << endl; cout << "Expected value: Test" << endl; cout << "Obtained value: " << strPlusEqual << endl << endl; } //Goal: Test the overload of the operator << //Arguments: - //Exceptions: - bool Test::operatorCinTest() const { String strCin; cout << "----------------------- << test-----------------------" << endl << endl; while (!strCin.equals("Test")) { cout << "Please enter: Test" << endl; cin >> strCin; } cout << "Expected value: Test" << endl; cout << "Obtained value: " << strCin << endl << endl; }
// // Created by roy on 12/18/18. // #ifndef PROJECTPART1_LINEPARSER_H #define PROJECTPART1_LINEPARSER_H #include <vector> #include <string> #include <iostream> #include "CommandMap.h" #include "SmallLexer.h" #include "BigLexer.h" #include "SymbolTable.h" #include "Utilities.h" #include "ConnectCommand.h" #include "OpenServerCommand.h" #include "DataReaderServer.h" #include "IfCommand.h" #include "SleepCommand.h" #include "PrintCommand.h" #include "VarCommand.h" #include "EqualCommand.h" using namespace std; /** * Line parser iterates over a single line and creates the fitting * command out of it, then it executes the command and continues. */ class LineParser { CommandMap commandMap; SymbolTable* symbolTable; SmallLexer smallLexer; Utilities util; DataReaderServer *dataReaderServer; DataSender *dataSender; public: int parse(vector<string> stringVector, int startIndex); LineParser(SymbolTable* symbolTable, DataReaderServer *dataReaderServer, DataSender * dataSender); }; #endif //PROJECTPART1_LINEPARSER_H
// // main.cpp // BYU Box // // Created by Jesse Millar on 9/16/13. // Copyright (c) 2013 Jesse Millar. All rights reserved. // #include <iostream> using namespace std; int main() { cout << "BYU\n\nBYU\n\nBYU"; }
#include <iostream> #include <fstream> #include <set> #include <string> #include <algorithm> #include <boost/regex.hpp> #include "Configfile.h" #include "Helpers.h" #include "CLArguments.h" std::string GetFileContent(const std::string& filename) { std::string content; std::ifstream in(filename.c_str()); if(in.fail()) { std::cout<<"Could not open "<<filename<<"!"<<std::endl; return ""; } while(!in.eof()) { content += in.get(); } in.close(); return content; } std::string GetFileExtension(const std::string& filename) { std::string::size_type lastDotPos = filename.find_last_of('.'); if(lastDotPos == std::string::npos) return ""; return filename.substr(lastDotPos+1); } enum ResourceType { RT_NULL, RT_TEXTURE, RT_MODEL, RT_MODEL2, RT_MODEL3, RT_SOUND, RT_SCRIPT, RT_EFFECT, RT_MUSIC, RT_PATCHTEX, RT_SHADER, RT_ALPHAMAP }; void AddNextToSetAndTrimInput(std::string& input, std::string::size_type start, std::set<std::string>& set, ResourceType rt) { if(start == std::string::npos) { std::cout<<"AddNextToSetAndTrimInput called with npos start!"<<std::endl; return; } if(input == "") { std::cout<<"AddNextToSetAndTrimInput called with empty input!"<<std::endl; } input.erase(0, start); std::string::size_type end = std::string::npos; if(rt == RT_SCRIPT) { input.erase(0, 9); end = input.find('"'); } else if (rt == RT_EFFECT) { input.erase(0, 10); end = input.find('"'); } else if (rt == RT_PATCHTEX) { input.erase(0, 12); end = input.find('\n'); } else if (rt == RT_SHADER) { input.erase(0, 10); end = input.find('"'); } else if (rt == RT_ALPHAMAP) { input.erase(0, 12); end = input.find('"'); } else if (rt == RT_MODEL2) { input.erase(0, 10); end = input.find('"'); } else if (rt == RT_MODEL3) { input.erase(0, 9); end = input.find('"'); } else { end = input.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-./\\()&+"); //std::cout<<"ELSE!"<<((end==std::string::npos) ? "npos" : Helpers::IntToString(end))<<std::endl; } if(end == std::string::npos) { std::cout<<"Error: sudden end of file! Type: "<< rt << ". Last 50 characters: \""<<input.substr(0, 50)<<"\""; //ensure we don't get stuck here if(!input.empty()) input.erase(0, 1); std::cout<<" dammit."<<std::endl; return; } std::string insme = input.substr(0, end); insme = Helpers::ToLower(Helpers::Replace(insme, "\\", "/")); if(rt == RT_SCRIPT) insme = "scripts/" + insme; else if(rt == RT_PATCHTEX && insme.substr(0, 9) != "textures/") insme = "textures/" + insme; else if(rt == RT_SHADER && insme.substr(0, 9) != "textures/") insme = "textures/" + insme; else if(rt == RT_EFFECT && insme.substr(0, 8) != "effects/") insme = "effects/" + insme; set.insert(insme); input.erase(0, end); } void SearchForResources(std::string& content, std::set<std::string>& output) { while(true) { std::string::size_type nextTexturePos = content.find("textures/"); if(nextTexturePos == std::string::npos) nextTexturePos = content.find("textures\\"); std::string::size_type nextModel2Pos = content.find("\"model2\" \""); std::string::size_type nextModel3Pos = content.find("\"model\" \""); std::string::size_type nextModelPos = content.find("models/"); if(nextModelPos == std::string::npos) nextModelPos = content.find("models\\"); std::string::size_type nextSoundPos = content.find("sound/"); if(nextSoundPos == std::string::npos) nextSoundPos = content.find("sound\\"); std::string::size_type nextScriptPos = content.find("script\" \""); std::string::size_type nextEffectPos = content.find("\"fxfile\" \""); std::string::size_type nextPatchTexPos = content.find("patchdef2\n{\n"); std::string::size_type nextAlphamapPos = content.find("\"alphamap\" \""); std::string::size_type nextShaderPos = content.find("\"shader\" \""); std::string::size_type nextMusicPos = content.find("music/"); if(nextMusicPos == std::string::npos) nextMusicPos = content.find("music\\"); std::string::size_type nextPos = std::string::npos; std::vector<std::string::size_type> positions; positions.push_back(nextEffectPos); positions.push_back(nextModelPos); positions.push_back(nextModel2Pos); positions.push_back(nextModel3Pos); positions.push_back(nextMusicPos); positions.push_back(nextScriptPos); positions.push_back(nextSoundPos); positions.push_back(nextTexturePos); positions.push_back(nextPatchTexPos); for(std::vector<std::string::size_type>::iterator it = positions.begin();it != positions.end(); ++it) { nextPos = std::min(nextPos, *it); } std::cout<<"nextPos = "<<nextPos<<std::endl; if(nextPos == std::string::npos) break; ResourceType nextResource = RT_NULL; if (nextPos == nextEffectPos ) nextResource = RT_EFFECT; else if(nextPos == nextModelPos ) nextResource = RT_MODEL; else if(nextPos == nextModel2Pos ) nextResource = RT_MODEL2; else if(nextPos == nextModel3Pos ) nextResource = RT_MODEL3; else if(nextPos == nextMusicPos ) nextResource = RT_MUSIC; else if(nextPos == nextScriptPos ) nextResource = RT_SCRIPT; else if(nextPos == nextSoundPos ) nextResource = RT_SOUND; else if(nextPos == nextPatchTexPos) nextResource = RT_PATCHTEX; else if(nextPos == nextShaderPos ) nextResource = RT_SHADER; else if(nextPos == nextAlphamapPos) nextResource = RT_ALPHAMAP; else if(nextPos == nextTexturePos ) nextResource = RT_TEXTURE; std::cout<<"nextPos = "<<nextPos<<std::endl; std::cout<<"nextTexturePos: "<<nextTexturePos<<" nextPos: "<<nextPos << " nextResource: "<<nextResource<<std::endl; AddNextToSetAndTrimInput(content, nextPos, output, nextResource); } } int main(int argc, char** argv) { cppag::CLArguments arg(argc, argv); std::cout << "This program parses a given .map file and creates a list containing all the textures and models used in it, plus the textures those models use." << std::endl << "Usage: ResourceLister.exe mapname.map" << std::endl << "Note: Can only parse textures in md3 and ase files" << std::endl; if(argc <= 1) { std::cout <<"Error: No map given!" << std::endl; //Exit std::cout<<"Press Enter to exit"; std::fflush(stdin); std::getchar(); return EXIT_FAILURE; } WGF::Configfile config; if(!config.LoadFromFile(arg.GetWorkingDirectory()+"ResourceLister.cfg")) { std::cout<<"Error: Couldn't load config file ResourceLister.cfg"<<std::endl; //Exit std::cout<<"Press Enter to exit"; std::fflush(stdin); std::getchar(); return EXIT_FAILURE; } std::string basepath = config.GetString("basepath"); std::string listpath = config.GetString("listpath"); std::string modpath = config.GetString("modpath"); std::cout<<"Using basepath \""<<basepath<<"\"."<<std::endl; std::cout<<"Using modpath \""<<modpath<<"\"."<<std::endl; std::cout<<"Outputting list to \""<<listpath<<"\"."<<std::endl; std::string content = Helpers::ToLower(GetFileContent(argv[1])); if(content == "") { std::cout<<"Error: Couldn't open map \""<<argv[1]<<"\"!"<<std::endl; //Exit std::cout<<"Press Enter to exit"; std::fflush(stdin); std::getchar(); return EXIT_FAILURE; } std::cout<<"Successfully loaded the file."<<std::endl; std::set<std::string> resources; std::cout<<"Parsing brush faces..."<<std::endl; //parse for brush face textures { std::string contentCopy = content; const boost::regex regex_brushface("(\\(( -?[0-9]+(\\.[0-9]+)?){3} \\) ){3}([^ ()]+)( -?[0-9]+(\\.[0-9]+)?){8}"); boost::match_results<std::string::iterator> result; while(boost::regex_search(contentCopy.begin(), contentCopy.end(), result, regex_brushface)) { std::string str = result[4].str(); if(str.substr(0, 7) != "models/") { str = "textures/" + str; } resources.insert(str); contentCopy.erase(contentCopy.begin(), result[0].second); } } //parse for textures and models std::cout<<"Parsing keys & values..."<<std::endl; SearchForResources(content, resources); std::cout<<"Map parsed. Parsing found models..."<<std::endl; std::set<std::string> oldResources = resources; for(std::set<std::string>::iterator it = oldResources.begin(); it != oldResources.end(); ++it) { std::string fileExt = Helpers::ToLower(GetFileExtension(*it)); if(fileExt == "md3" || fileExt == "ase") { std::cout<<"Parsing "<<*it<<"..."<<std::endl; std::string modelContent = ""; if(basepath != "") modelContent = GetFileContent(basepath + (*it)); if(modelContent == "") { modelContent = GetFileContent(modpath + (*it)); } if(modelContent == "") continue; SearchForResources(modelContent, resources); } } std::cout<<"Models parsed."<<std::endl; std::string outName = argv[1]; outName.erase(0, outName.find_last_of("/\\")+1); outName += ".Resources.txt"; outName = listpath + outName; std::ofstream out(outName.c_str()); if(out.fail()) { std::cout<<"Error: Couldn't create output file "<<outName<<"!"<<std::endl<<"Resources in this map: "<<std::endl; for(std::set<std::string>::iterator it = resources.begin(); it != resources.end(); ++it) { std::cout<<(*it)<<std::endl; } } else { for(std::set<std::string>::iterator it = resources.begin(); it != resources.end(); ++it) { out<<*it<<std::endl; } out.close(); std::cout<<"List written to "<<outName<<std::endl; } //Exit std::cout<<"Press Enter to exit"; std::fflush(stdin); std::getchar(); return EXIT_SUCCESS; }
// Created on: 1995-05-29 // Created by: Xavier BENVENISTE // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _AdvApprox_ApproxAFunction_HeaderFile #define _AdvApprox_ApproxAFunction_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <TColStd_HArray1OfReal.hxx> #include <Standard_Real.hxx> #include <GeomAbs_Shape.hxx> #include <Standard_Boolean.hxx> #include <TColStd_HArray2OfReal.hxx> #include <TColgp_HArray2OfPnt2d.hxx> #include <TColgp_HArray2OfPnt.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <Standard_Address.hxx> #include <AdvApprox_EvaluatorFunction.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <TColgp_Array1OfPnt.hxx> #include <Standard_OStream.hxx> class AdvApprox_Cutting; //! this approximate a given function class AdvApprox_ApproxAFunction { public: DEFINE_STANDARD_ALLOC //! Constructs approximator tool. //! //! Warning: //! the Func should be valid reference to object of type //! inherited from class EvaluatorFunction from Approx //! with life time longer than that of the approximator tool; //! //! the result should be formatted in the following way : //! <--Num1DSS--> <--2 * Num2DSS--> <--3 * Num3DSS--> //! R[0] .... R[Num1DSS]..... R[Dimension-1] //! //! the order in which each Subspace appears should be consistent //! with the tolerances given in the create function and the //! results will be given in that order as well that is : //! Curve2d(n) will correspond to the nth entry //! described by Num2DSS, Curve(n) will correspond to //! the nth entry described by Num3DSS //! The same type of schema applies to the Poles1d, Poles2d and //! Poles. Standard_EXPORT AdvApprox_ApproxAFunction(const Standard_Integer Num1DSS, const Standard_Integer Num2DSS, const Standard_Integer Num3DSS, const Handle(TColStd_HArray1OfReal)& OneDTol, const Handle(TColStd_HArray1OfReal)& TwoDTol, const Handle(TColStd_HArray1OfReal)& ThreeDTol, const Standard_Real First, const Standard_Real Last, const GeomAbs_Shape Continuity, const Standard_Integer MaxDeg, const Standard_Integer MaxSeg, const AdvApprox_EvaluatorFunction& Func); //! Approximation with user methode of cutting Standard_EXPORT AdvApprox_ApproxAFunction(const Standard_Integer Num1DSS, const Standard_Integer Num2DSS, const Standard_Integer Num3DSS, const Handle(TColStd_HArray1OfReal)& OneDTol, const Handle(TColStd_HArray1OfReal)& TwoDTol, const Handle(TColStd_HArray1OfReal)& ThreeDTol, const Standard_Real First, const Standard_Real Last, const GeomAbs_Shape Continuity, const Standard_Integer MaxDeg, const Standard_Integer MaxSeg, const AdvApprox_EvaluatorFunction& Func, const AdvApprox_Cutting& CutTool); Standard_EXPORT static void Approximation (const Standard_Integer TotalDimension, const Standard_Integer TotalNumSS, const TColStd_Array1OfInteger& LocalDimension, const Standard_Real First, const Standard_Real Last, AdvApprox_EvaluatorFunction& Evaluator, const AdvApprox_Cutting& CutTool, const Standard_Integer ContinuityOrder, const Standard_Integer NumMaxCoeffs, const Standard_Integer MaxSegments, const TColStd_Array1OfReal& TolerancesArray, const Standard_Integer code_precis, Standard_Integer& NumCurves, TColStd_Array1OfInteger& NumCoeffPerCurveArray, TColStd_Array1OfReal& LocalCoefficientArray, TColStd_Array1OfReal& IntervalsArray, TColStd_Array1OfReal& ErrorMaxArray, TColStd_Array1OfReal& AverageErrorArray, Standard_Integer& ErrorCode); Standard_Boolean IsDone() const; Standard_Boolean HasResult() const; //! returns the poles from the algorithms as is Handle(TColStd_HArray2OfReal) Poles1d() const; //! returns the poles from the algorithms as is Handle(TColgp_HArray2OfPnt2d) Poles2d() const; //! -- returns the poles from the algorithms as is Handle(TColgp_HArray2OfPnt) Poles() const; //! as the name says Standard_EXPORT Standard_Integer NbPoles() const; //! returns the poles at Index from the 1d subspace Standard_EXPORT void Poles1d (const Standard_Integer Index, TColStd_Array1OfReal& P) const; //! returns the poles at Index from the 2d subspace Standard_EXPORT void Poles2d (const Standard_Integer Index, TColgp_Array1OfPnt2d& P) const; //! returns the poles at Index from the 3d subspace Standard_EXPORT void Poles (const Standard_Integer Index, TColgp_Array1OfPnt& P) const; Standard_Integer Degree() const; Standard_Integer NbKnots() const; Standard_Integer NumSubSpaces (const Standard_Integer Dimension) const; Handle(TColStd_HArray1OfReal) Knots() const; Handle(TColStd_HArray1OfInteger) Multiplicities() const; //! returns the error as is in the algorithms Standard_EXPORT Handle(TColStd_HArray1OfReal) MaxError (const Standard_Integer Dimension) const; //! returns the error as is in the algorithms Standard_EXPORT Handle(TColStd_HArray1OfReal) AverageError (const Standard_Integer Dimension) const; Standard_EXPORT Standard_Real MaxError (const Standard_Integer Dimension, const Standard_Integer Index) const; Standard_EXPORT Standard_Real AverageError (const Standard_Integer Dimension, const Standard_Integer Index) const; //! display information on approximation. Standard_EXPORT void Dump (Standard_OStream& o) const; protected: private: Standard_EXPORT void Perform (const Standard_Integer Num1DSS, const Standard_Integer Num2DSS, const Standard_Integer Num3DSS, const AdvApprox_Cutting& CutTool); Standard_Integer myNumSubSpaces[3]; Handle(TColStd_HArray1OfReal) my1DTolerances; Handle(TColStd_HArray1OfReal) my2DTolerances; Handle(TColStd_HArray1OfReal) my3DTolerances; Standard_Real myFirst; Standard_Real myLast; GeomAbs_Shape myContinuity; Standard_Integer myMaxDegree; Standard_Integer myMaxSegments; Standard_Boolean myDone; Standard_Boolean myHasResult; Handle(TColStd_HArray2OfReal) my1DPoles; Handle(TColgp_HArray2OfPnt2d) my2DPoles; Handle(TColgp_HArray2OfPnt) my3DPoles; Handle(TColStd_HArray1OfReal) myKnots; Handle(TColStd_HArray1OfInteger) myMults; Standard_Integer myDegree; Standard_Address myEvaluator; Handle(TColStd_HArray1OfReal) my1DMaxError; Handle(TColStd_HArray1OfReal) my1DAverageError; Handle(TColStd_HArray1OfReal) my2DMaxError; Handle(TColStd_HArray1OfReal) my2DAverageError; Handle(TColStd_HArray1OfReal) my3DMaxError; Handle(TColStd_HArray1OfReal) my3DAverageError; }; #include <AdvApprox_ApproxAFunction.lxx> #endif // _AdvApprox_ApproxAFunction_HeaderFile
#pragma once #include "naive_async_dictionary.hpp" #include "naive_dictionary.hpp" #include "scenario.hpp" #include "tools.hpp" #include "trie.hpp" #include "trie_async.hpp" #include "trie_async_global.hpp" #include <functional> #include <gtest/gtest.h> #include <thread>
#include "AAObject.h" #include "AAWorld.h" AAObject::AAObject(const char *name) { this->name = name; glm::mat4 modelTransformationMatrix; glm::mat4 projectionMatrix; this->objectTransformationMatrix = glm::translate(glm::mat4(1.f), glm::vec3(0.0f, 0.0f, 0.0f)); this->objectScaleMatrix = glm::scale(glm::mat4(1.f), glm::vec3(0.0f, 0.0f, 0.0f)); this->objectRotationMatrix = glm::rotate(glm::mat4(), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f)); this->forward = AAWorld::getForwardVector(); this->up = AAWorld::getUpVector(); } AAObject::~AAObject() { } //setters void AAObject::setPosition(glm::vec3 position) { this->position = position; this->objectTransformationMatrix = glm::translate(glm::mat4(1.f), this->position); } void AAObject::setObjectTransformationMatrix(glm::mat4 modelTransformationMatrix) { this->objectTransformationMatrix = modelTransformationMatrix; } void AAObject::setObjectRotationMatrix(glm::mat4 objectRotationMatrix) { this->objectTransformationMatrix = objectRotationMatrix; } void AAObject::setObjectScaleMatrix(glm::mat4 objectScaleMatrix) { this->objectScaleMatrix = objectScaleMatrix; } //getters const glm::vec3 AAObject::getPosition() const { return this->position; } const glm::vec3 AAObject::getForwardVector() const { return this->forward; } const glm::vec3 AAObject::getBackwardVector() const { return this->getForwardVector() * -1.0f; } const glm::vec3 AAObject::getUpVector() const { return this->up; } const glm::vec3 AAObject::getDownVector() const { return this->getUpVector() * -1.0f; } const glm::vec3 AAObject::getRightVector() const { return glm::cross(this->getForwardVector(), this->getUpVector()); } const glm::vec3 AAObject::getLeftVector() const { return this->getRightVector() * -1.0f; } const glm::mat4 AAObject::getObjectTransformationMatrix() const { return this->objectTransformationMatrix; } const glm::mat4 AAObject::getObjectScaleMatrix() const { return this->objectScaleMatrix; } const glm::mat4 AAObject::getObjectRotationMatrix() const { return this->objectRotationMatrix; } const char * AAObject::getName() { return this->name; } //Member function ********************************************************** void AAObject::moveForward(float scalar) { this->setPosition(this->getPosition() + this->getForwardVector()*scalar); } void AAObject::moveBackward(float scalar) { this->setPosition(this->getPosition() + this->getBackwardVector()*scalar); } void AAObject::moveLeft(float scalar) { this->setPosition(this->getPosition() + this->getLeftVector()*scalar); } void AAObject::moveRight(float scalar) { this->setPosition(this->getPosition() + this->getRightVector()*scalar); } void AAObject::rotate(float degree, glm::vec3 vect) { this->forward = glm::mat3(glm::rotate(degree, vect)) * this->forward; this->up = glm::mat3(glm::rotate(degree, vect)) * this->up; this->objectRotationMatrix = glm::rotate(degree, vect)*this->objectRotationMatrix; //this->objectRotationMatrix = glm::lookAt(this->getPosition(), this->getForwardVector() - this->getPosition(), this->up); } void AAObject::rotateUp(float degree) { this->rotate(degree, this->getRightVector()); } void AAObject::rotateDown(float degree) { this->rotate(-degree, this->getRightVector()); } void AAObject::rotateLeft(float degree) { this->rotate(degree, this->getUpVector()); } void AAObject::rotateRight(float degree) { this->rotate(-degree, this->getUpVector()); }
#pragma once #include<string> class Evenement{ private: public: virtual std:: string method() const = 0; // J'ai mis cette méthode ici juste pour que ce soit une classe abstraite pour le moment };
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; const double PI = 3.14159265358979323846; const ll MOD = 998244353; int main(){ ll A,B,C; cin >> A >> B >> C; ll a = A*(A+1) / 2; a %= MOD; ll b = B*(B+1) / 2; b %= MOD; ll c = C*(C+1)/2; c %= MOD; ll ans = a * b %MOD * c; cout << ans % MOD << endl; return 0; }
#ifndef TRAJECTORY_H #define TRAJECTORY_H #include "point.h" #include <QList> #include "node.h" #include "CGLA/Mat4x4f.h" #include "CGLA/Mat1x4f.h" #include "CGLA/Mat3x4f.h" #include "CGLA/Mat1x3f.h" #include "CGLA/ArithMat.h" #include "qmath.h" #include "matrix.h" #include "vertex.h" #include "rocketship.h" #include "particle.h" using namespace CGLA; class Trajectory : public Node { public: Trajectory(int objId); void paintShape(); void showTextures(bool *i); Point* generateEquation(double time, int currentBlock); void addVertex(PointVertex *p); PointVertex* getPoint(int objectId); int getLastObjId(); void addObject(RocketShip *rocket); void recalculateBSpline(); void setTimePtr(double *time); void calculateRotation(Point *origin, Point *end, double *phi, double *theta, double *rho); void drawParticles(Point *currentPos, double currentTime, float * vectorPoints); bool isEmpty(); private: //pour les particules RocketShip* object; int nbPart_ = 200; Particle* particle_ = new Particle[nbPart_]; Vec3f result; QList<PointVertex *> pList; QList<int> vertexObjIds; Mat4x4f bSplineMat = Mat4x4f(Vec4f(-1.0,3.0,-3.0,1.0), Vec4f(3.0,-6.0,3.0,0.0), Vec4f(-3.0,0.0,3.0,0.0), Vec4f(1.0,4.0,1.0,0.0)); const double INTERVAL = 200; //pointeur du temps double *time; }; #endif // TRAJECTORY_H
#include "LCDNumber.h" #include <QDebug> #include <QApplication> #if defined(Q_OS_UNIX) #include <QLibrary> #include <QtX11Extras/QX11Info> #include <X11/Xutil.h> #elif defined(Q_OS_WIN) #include <windows.h> #endif // Q_OS_MACRO LCDNumber::LCDNumber(QWidget *parent) : QLCDNumber(parent) { timer = new QTimer(this); QObject::connect(timer, SIGNAL(timeout()), this, SLOT(setDisplay())); } LCDNumber::~LCDNumber() { // Empty destructor } void LCDNumber::setDisplay() { if ((idleTime() < 1000) && !firstTick) { qApp->exit(); } if (timeEnd == 0) { shutDownComputer(); qApp->exit(); } // qDebug() << timeEnd << idleTime(); this->timeValue->setHMS(0,this->timeValue->addSecs(-1).minute(),this->timeValue->addSecs(-1).second()); this->display(this->timeValue->toString()); timeEnd -= 1; firstTick = false; } void LCDNumber::set_Time(int minutes, int seconds) { timeValue = new QTime(0, minutes, seconds); this->display(timeValue->toString()); timeEnd = minutes * 60 + seconds; firstTick = true; } void LCDNumber::start_Timer(int sec) { timer->start(sec); } #if defined(Q_OS_UNIX) bool LCDNumber::shutDownComputer() { system("systemctl poweroff"); return true; } typedef struct { Window window; /* screen saver window - may not exist */ int state; /* ScreenSaverOff, ScreenSaverOn, ScreenSaverDisabled*/ int kind; /* ScreenSaverBlanked, ...Internal, ...External */ unsigned long til_or_since; /* time til or since screen saver */ unsigned long idle; /* total time since last user input */ unsigned long eventMask; /* currently selected events for this client */ } XScreenSaverInfo; typedef XScreenSaverInfo* (*XScreenSaverAllocInfo)(); typedef Status (*XScreenSaverQueryInfo)(Display* display, Drawable* drawable, XScreenSaverInfo* info); static XScreenSaverAllocInfo _xScreenSaverAllocInfo = 0; static XScreenSaverQueryInfo _xScreenSaverQueryInfo = 0; uint LCDNumber::idleTime() { static bool xssResolved = false; if (!xssResolved) { QLibrary xssLib(QLatin1String("Xss"), 1); if (xssLib.load()) { _xScreenSaverAllocInfo = (XScreenSaverAllocInfo) xssLib.resolve("XScreenSaverAllocInfo"); _xScreenSaverQueryInfo = (XScreenSaverQueryInfo) xssLib.resolve("XScreenSaverQueryInfo"); xssResolved = true; } } uint idle = 0; if (xssResolved) { XScreenSaverInfo* info = _xScreenSaverAllocInfo(); const int screen = QX11Info::appScreen(); Qt::HANDLE rootWindow = (void *) QX11Info::appRootWindow(screen); _xScreenSaverQueryInfo(QX11Info::display(), (Drawable*) rootWindow, info); idle = info->idle; if (info) XFree(info); } return idle; } #elif defined(Q_OS_WIN) bool LCDNumber::shutDownComputer() { HANDLE hToken; TOKEN_PRIVILEGES tkp; // Get a token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return( FALSE ); // Get the LUID for the shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid); tkp.PrivilegeCount = 1; // one privilege to set tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process. AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0); if (GetLastError() != ERROR_SUCCESS) return FALSE; // Shut down the system and force all applications to close. if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED)) return FALSE; //shutdown was successful return TRUE; } uint LCDNumber::idleTime() { uint idle = -1; LASTINPUTINFO info; info.cbSize = sizeof(LASTINPUTINFO); if (::GetLastInputInfo(&info)) idle = ::GetTickCount() - info.dwTime; return idle; } #endif // Q_OS_MACRO
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; vector <string> table; void build(string str){ if( str.size() > 5 ) return; table.push_back(str); for(char i = str.size()==0?'a':str.back()+1 ; i <= 'z' ; i++ ) build(str+i); } bool cmp(string a, string b){ if( a.size() == b.size() ) return a < b; return a.size() < b.size(); } int main(int argc, char const *argv[]) { build(""); sort(table.begin(), table.end(),cmp); map <string,int> ans; for(int i = 0 ; i < table.size() ; i++ ) ans[table[i]] = i; string str; while( cin >> str ){ if( ans.find(str) != ans.end() ) cout << ans[str] << endl; else cout << "0" << endl; } return 0; }
#include <iostream> #include <queue> using namespace std; typedef int Dado; enum Posicao { DIR, ESQ }; class Noh { friend class ABB; public: Noh(Dado d); bool FilhoDaDireita(); Dado MenorRecursivo(); bool Sucessor(Dado *ptResultado); private: Dado valor; Noh *esq; Noh *dir; Noh *pai; }; class ABB { public: ABB() { raiz = NULL; } ~ABB(); Noh *Busca(Dado d); void EscreverNivelANivel(std::ostream &saida); void Inserir(Dado d); bool Sucessor(Dado d, Dado *ptResultado); void destruirRecursivamente(Noh *atual); void posOrdem() { posOrdem(raiz); } void posOrdem(Noh *atual); private: Noh *raiz; }; Noh::Noh(Dado d) { esq = NULL; dir = NULL; pai = NULL; valor = d; } bool Noh::FilhoDaDireita() { Noh *aux = this; if (aux->dir == NULL) return false; return true; } Dado Noh::MenorRecursivo() { Noh *SubArvore = this; if (SubArvore->esq == NULL) { return valor; } return esq->MenorRecursivo(); } bool Noh::Sucessor(Dado *ptResultado) { if (FilhoDaDireita()) { *ptResultado = dir->MenorRecursivo(); return true; } return false; } ABB::~ABB() { destruirRecursivamente(raiz); } void ABB::destruirRecursivamente(Noh *atual) { if (atual != NULL) { posOrdem(atual->esq); posOrdem(atual->dir); delete atual; } } void ABB::posOrdem(Noh *atual) { if (atual != NULL) { posOrdem(atual->esq); posOrdem(atual->dir); } } void ABB::Inserir(Dado d) { Noh *novo = new Noh(d); if (raiz == NULL) { raiz = novo; } else { Noh *atual = raiz; Noh *anterior = NULL; while (atual != NULL) { anterior = atual; if (atual->valor > d) { atual = atual->esq; } else { atual = atual->dir; } } novo->pai = anterior; if (anterior->valor > novo->valor) { anterior->esq = novo; } else { anterior->dir = novo; } } } bool ABB::Sucessor(Dado d, Dado *ptResultado) { Noh *chave = Busca(d); if (chave->FilhoDaDireita() == false) { while (chave->valor <= d and chave != raiz) { chave = chave->pai; } if (chave->valor > d) { *ptResultado = chave->valor; return true; } return false; } chave->Sucessor(ptResultado); return true; } Noh *ABB::Busca(Dado d) { Noh *atual = raiz; while (atual != NULL) { if (atual->valor == d) return atual; else if (atual->valor > d) { atual = atual->esq; } else { atual = atual->dir; } } return atual; } void ABB::EscreverNivelANivel(ostream &saida) { queue<Noh *> filhos; Noh noh = Dado(); Noh *fimDeNivel = &noh; filhos.push(raiz); filhos.push(fimDeNivel); while (not filhos.empty()) { Noh *ptNoh = filhos.front(); filhos.pop(); if (ptNoh == fimDeNivel) { saida << "\n"; if (not filhos.empty()) filhos.push(fimDeNivel); } else { saida << '['; if (ptNoh != NULL) { saida << ptNoh->valor; filhos.push(ptNoh->esq); filhos.push(ptNoh->dir); } saida << ']'; } } } int main() { ABB arvore; Dado chave; char operacao; do { cin >> operacao; switch (operacao) { case 'i': cin >> chave; arvore.Inserir(chave); break; case 'e': arvore.EscreverNivelANivel(cout); break; case 's': { cin >> chave; Dado sucessor; while (arvore.Sucessor(chave, &sucessor)) { cout << sucessor << ' '; chave = sucessor; } cout << endl; break; } } } while (operacao != 'f'); return 0; }
#pragma once #include <BWAPI.h> #include <map> #include <vector> #include <set> enum class UnitOrder { COLLECT_MINERALS, COLLECT_GAS, SCOUT_CONFUSION_MICRO, BUILD, CAMP, CAMP_MOVE, SCOUT, RALLY }; class UnitManager { // <unit id, UnitOrders> std::map<int, UnitOrder> m_unitOrders; std::set<int> m_campers; double m_scoutConfusionAngle = 30.0; BWAPI::Position m_centerPosition = BWAPI::Positions::Invalid; std::map<BWAPI::TilePosition, int> m_enroute; UnitManager(); void setupScouts(); void runOrders(); bool performScouting(BWAPI::Unit scout); void performScoutConfusionMicro(BWAPI::Unit scout); bool collectMinerals(BWAPI::Unit worker); bool collectGas(BWAPI::Unit worker); void idleWorkersCollectMinerals(); void camp(BWAPI::Unit unit, bool move = false); void rally(BWAPI::Unit unit); void sendCamper(); bool isSomeoneCamping(); void printInfo(); void replenishCampers(); int unitsWithOrder(UnitOrder order); void setRallyUnits(); public: static UnitManager& Instance() { static UnitManager instance; return instance; } void attack(); void onFrame(); void onStart(); void onCreate(BWAPI::Unit unit); void onDead(BWAPI::Unit unit); void setOrder(int unitID, UnitOrder order); bool isCamper(int unitID); UnitOrder getOrder(int unitID); BWAPI::Unit getBuildUnit(BWAPI::UnitType builderType, UnitOrder order = UnitOrder::COLLECT_MINERALS); };
/********************************************** ** Description: Header file of Player *********************************************/ #ifndef PLAYER_HPP // PLAYER.hpp is the Player class specification file. #define PLAYER_HPP #include<string> class Player { private: //This is member variables. std::string name; int points; int rebounds; int assists; public: //default constructor Player(){ name = ""; points = -100; rebounds = -100; assists = -100; } Player(std::string, int, int, int); //constructor with paramenters std::string getName(); //getter function int getPoints(); int getRebounds(); int getAssists(); void setPoints(int); //setter function void setRebounds(int); void setAssists(int); bool hasMorePointsThan(Player); //bool function }; #endif
#include<iostream> #include<cstring> using namespace std; long long f[100010]; int main() {int t; freopen("test.in","r",stdin); scanf("%d",&t); while (t--) {int n; long long ans = 0; scanf("%d",&n); memset(f,0,sizeof(f)); for (int i = 0;i < (n+1)/2; i++) {f[i+1]=f[i]+n-2*i; f[n-i]=f[i+1]; } for (int i = 1;i <= n; i++) {long long x; scanf("%lld",&x); if (f[i]%2) ans^=x; } printf("%lld\n",ans); } return 0; }
#include "engine/net/ServerNet.hpp" ServerNet::ServerNet(){ pthread_mutex_init( &mutex, NULL); pthread_mutex_init( &mutex1, NULL); pthread_cond_init( &connectionSignal, NULL); ServerNet::Init(); } int ServerNet::Init(){ if (enet_initialize () != 0) { fprintf (stderr, "An error occurred while initializing ENet.\n"); return 0; } atexit (enet_deinitialize); address.host = ENET_HOST_ANY; // This allows /* Bind the server to port 7777. */ address.port = 7777; server = enet_host_create (&address /* the address to bind the server host to */, 32 /* allow up to 32 clients and/or outgoing connections */, 1 /* allow up to 1 channel to be used, 0. */, 0 /* assume any amount of incoming bandwidth */, 0 /* assume any amount of outgoing bandwidth */); if (server == NULL) { printf("An error occurred while trying to create an ENet server host."); return 0; } running = true; return 1; } void ServerNet::SendMap(ENetPeer* peer, std::vector<std::vector<bool>> &map){ char send_data[1024] = {'\0'}; int total_len = map.size()*map[0].size(); sprintf(send_data, "1|%d|", total_len); for (auto x: map){ for (bool y:x){ if (y){ strcat(send_data, "1"); } else{ strcat(send_data, "0"); } } } SendPacket(peer, send_data); } int ServerNet::Destroy(){ enet_host_destroy(server); running = false; return 1; } bool ServerNet::isRunning(){ pthread_mutex_lock(&mutex1); bool run_val = running; pthread_mutex_unlock(&mutex1); return run_val; } void ServerNet::setRunning(){ pthread_mutex_lock(&mutex1); running = true; pthread_mutex_unlock(&mutex1); } void ServerNet::setNotRunning(){ pthread_mutex_lock(&mutex1); running = false; pthread_mutex_unlock(&mutex1); } void ServerNet::waitForConnection(){ pthread_mutex_lock(&mutex); while (!connected){ pthread_cond_wait(&connectionSignal, &mutex); } pthread_mutex_unlock(&mutex); } void ServerNet::SendRoundEndSignal(PlayerObj winner){ char send_data[1024] = {'\0'}; sprintf(send_data, "6|%d", winner); SendPacket(peer, send_data); } void ServerNet::sendDisconnectRequest(){ char send_data[1024] = {'\0'}; sprintf(send_data, "8"); SendPacket(peer, send_data); } void ServerNet::sendPlayerDead(int type){ char send_data[1024] = {'\0'}; sprintf(send_data, "9|%d", type); SendPacket(peer, send_data); }
/* Copyright (c) 2005-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #ifndef _ISHIKO_CPP_TESTFRAMEWORK_CORE_TESTAPPLICATIONERRORCODES_HPP_ #define _ISHIKO_CPP_TESTFRAMEWORK_CORE_TESTAPPLICATIONERRORCODES_HPP_ namespace Ishiko { class TestApplicationReturnCode { public: enum Value { ok = 0, configurationProblem = -1, exception = -3, testFailure = -4 }; }; } #endif
#ifndef __residlerParameterFormat__ #define __residlerParameterFormat__ #include "pluginterfaces/base/ftypes.h" #include <vector> namespace Steinberg { namespace Vst { namespace residler { using namespace std; //----------------------------------------------------------------------------- class residlerParameterFormat { public: enum paramIds { kMasterVolume = 0, kMasterTune, kMaxPolyphony, kVoice0On, //kOnOffType kVoice0Tune, kVoice0PW, kVoice0Waveform, //WaveformTypes list kVoice0RingMod, //kOnOffType kVoice0Sync, //kOnOffType kVoice0FilterOn, //kOnOffType kVoice0EnvAttack, kVoice0EnvDecay, kVoice0EnvSustain, kVoice0EnvRelease, kVoice1On, //kOnOffType kVoice1Tune, kVoice1PW, kVoice1Waveform, //WaveformTypes list kVoice1RingMod, //kOnOffType kVoice1Sync, //kOnOffType kVoice1FilterOn, //kOnOffType kVoice1EnvAttack, kVoice1EnvDecay, kVoice1EnvSustain, kVoice1EnvRelease, kVoice2On, //kOnOffType kVoice2Tune, kVoice2PW, kVoice2Waveform, //waveformTypes list kVoice2RingMod, //kOnOffType kVoice2Sync, //kOnOffType kVoice2FilterOn, //kOnOffType kVoice2EnvAttack, kVoice2EnvDecay, kVoice2EnvSustain, kVoice2EnvRelease, kFilterCutoff, kFilterResonance, kFilterHP, //kOnOffType kFilterBP, //kOnOffType kFilterLP, //kOnOffType kLFO1Type, kLFO1Rate, kLFO1Depth, kRoutingSource0, //routingSourceList kRoutingSource1, //routingSourceList kRoutingSource2, //routingSourceList kRoutingSource3, //routingSourceList kRoutingDestination0, //routingDestinationList kRoutingDestination1, //routingDestinationList kRoutingDestination2, //routingDestinationList kRoutingDestination3, //routingDestinationList kGlideRate, kGlideBend, kGlideType, //GlideTypes list //end of list knumParameters }; enum WaveformTypes { kWaveformNoise = 0, kWaveformPulse, kWaveformTriangle, kWaveformSaw, kWaveformPulseTriangle, kWaveformPulseSaw, kWaveformPulseTriangleSaw, kWaveformTriangleSaw, //end of list knumWaveformTypes }; enum kRoutingSources { kSourceVelocity, kSourceNotePitch, kSourceSIDVoice3, kSourceSIDEnv3, kSourceLFO1, //end of list knumRoutingSources }; enum kRoutingDestinations { kDestMasterVolume, kDestMasterTune, kDestVoice0Tune, kDestVoice1Tune, kDestVoice2Tune, kDestVoice0PW, kDestVoice1PW, kDestVoice2PW, kDestEnv0Att, kDestEnv0Dec, kDestEnv0Sus, kDestEnv0Rel, kDestEnv1Att, kDestEnv1Dec, kDestEnv1Sus, kDestEnv1Rel, kDestEnv2Att, kDestEnv2Dec, kDestEnv2Sus, kDestEnv2Rel, kDestFilterCutoff, kDestFilterRes, kDestLFO1Rate, kDestLFO1Depth, //end of list knumRoutingDestinations }; enum GlideTypes { kPoly = 0, kPolyLegato, kPolyGlide, kMono, kMonoLegato, kMonoGlide, //end of list knumGlideTypes }; enum OnOffType { kOff = 0, kOn, //end of list kOnOffType }; //todo: get rid of these hard coded presets, file based system needed enum factoryPresets { knumPresets = 10//get rid of these }; static float programParams[knumPresets][knumParameters]; //----------------------------------------------------------------------------- residlerParameterFormat (); //----------------------------------------------------------------------------- public: const vector<string>* paramNameList() const { return &paramList; } const vector<string>* routingSourceNameList() const { return &routingSourceList; } const vector<string>* routingDestinationNameList() const { return &routingDestinationList; } const vector<string>* glideNameList() const { return &glideList; } const vector<string>* waveformNameList() const { return &waveformList; } const vector<string>* onOffNameList() const { return &onOffList; } //----------------------------------------------------------------------------- private: //void setParam(paramIds SIDparam, unsigned char value) {} vector<string> paramList; vector<string> routingSourceList; vector<string> routingDestinationList; vector<string> glideList; vector<string> waveformList; vector<string> onOffList; }; }}} // namespaces #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/QuickGrid/GridLayouter.h" #include "adjunct/desktop_util/rtl/uidirection.h" #include "adjunct/quick_toolkit/widgets/WidgetSizes.h" GridLayouter::GridLayouter() : m_calculated_columns(FALSE) , m_calculated_rows(FALSE) , m_column_info(0) , m_row_info(0) , m_col_count(0) , m_row_count(0) , m_minimum_width(0) , m_minimum_height(0) { } GridLayouter::~GridLayouter() { OP_DELETEA(m_column_info); OP_DELETEA(m_row_info); } OP_STATUS GridLayouter::SetColumnCount(unsigned col_count) { m_col_count = col_count; return InitializeSizeInfo(m_column_info, m_col_count); } OP_STATUS GridLayouter::SetRowCount(unsigned row_count) { m_row_count = row_count; return InitializeSizeInfo(m_row_info, m_row_count); } /** Initializes a SizeInfo array * @param sizeinfo_array Array to initialize * @param sizeinfo_count Number of elements to create in array */ OP_STATUS GridLayouter::InitializeSizeInfo(SizeInfo*& sizeinfo_array, unsigned& sizeinfo_count) { OP_DELETEA(sizeinfo_array); sizeinfo_array = OP_NEWA(SizeInfo, sizeinfo_count); if (!sizeinfo_array) { sizeinfo_count = 0; return OpStatus::ERR_NO_MEMORY; } return OpStatus::OK; } void GridLayouter::SetColumnSizes(unsigned col, unsigned minimum_size, unsigned preferred_size, unsigned margin) { OP_ASSERT(col < m_col_count); m_minimum_width += minimum_size + margin; SetSizes(m_column_info, col, minimum_size, preferred_size, margin); m_calculated_columns = FALSE; } void GridLayouter::SetRowSizes(unsigned row, unsigned minimum_size, unsigned preferred_size, unsigned margin) { OP_ASSERT(row < m_row_count); m_minimum_height += minimum_size + margin; SetSizes(m_row_info, row, minimum_size, preferred_size, margin); m_calculated_rows = FALSE; } /** Sets sizes in an element of a SizeInfo array to specified values * @param sizes Array to use * @param index Element to change * @param ... Sizes */ void GridLayouter::SetSizes(SizeInfo* sizes, unsigned index, unsigned minimum_size, unsigned preferred_size, unsigned margin) { sizes[index].minimum_size = minimum_size; sizes[index].preferred_size = max(minimum_size, preferred_size); sizes[index].dynamic_size = sizes[index].preferred_size - minimum_size; sizes[index].size = minimum_size; sizes[index].margin = margin; } unsigned GridLayouter::GetColumnWidth(unsigned col) { if (col >= m_col_count) return 0; CalculateColumns(); return m_column_info[col].size; } OpRect GridLayouter::GetLayoutRectForCell(unsigned col, unsigned row, unsigned colspan, unsigned rowspan) { if (col + colspan > m_col_count || row + rowspan > m_row_count) return OpRect(); CalculateColumns(); CalculateRows(); OpRect cell_rect; for (unsigned i = 0; i < colspan; i++) { cell_rect.width += m_column_info[col + i].size; if (i > 0) cell_rect.width += m_column_info[col + i - 1].margin; } for (unsigned i = 0; i < rowspan; i++) { cell_rect.height += m_row_info[row + i].size; if (i > 0) cell_rect.height += m_row_info[row + i - 1].margin; } cell_rect.x = m_column_info[col].position; cell_rect.y = m_row_info[row].position; // Why 2*m_grid_rect.x? Because the cells of a generic grid are not children of the grid(i.e via SetParentOpWidget etc) // Therefore, column positions are not calculated relative to the grid, a start_pos is given(look CalculatePositions // and CalculateSizes, where it is called). Hence, to even out the start_pos effect and actually give an offset, m_grid_rect.x // is added twice. if (UiDirection::Get() == UiDirection::RTL) cell_rect.x = m_grid_rect.width - m_column_info[col].position - cell_rect.width + 2*m_grid_rect.x ; return cell_rect; } void GridLayouter::CalculateColumns() { if (m_calculated_columns) return; unsigned column_fillroom = max(0, m_grid_rect.width - (int)m_minimum_width); GrowIfNecessary(m_column_info, m_col_count, column_fillroom); unsigned column_surplus = max(0, (int)m_minimum_width - max(0, m_grid_rect.width)); ShrinkIfNecessary(m_column_info, m_col_count, m_minimum_width, column_surplus); CalculatePositions(m_column_info, m_col_count, m_grid_rect.x); m_calculated_columns = TRUE; } void GridLayouter::CalculateRows() { if (m_calculated_rows) return; unsigned row_fillroom = max(0, m_grid_rect.height - (int)m_minimum_height); GrowIfNecessary(m_row_info, m_row_count, row_fillroom); unsigned row_surplus = max(0, (int)m_minimum_height - m_grid_rect.height); ShrinkIfNecessary(m_row_info, m_row_count, m_minimum_height, row_surplus); CalculatePositions(m_row_info, m_row_count, m_grid_rect.y); m_calculated_rows = TRUE; } /** Grows size in SizeInfo array if there is fill room * @param sizes Array of sizes to change * @param sizes_count Number of elements in sizes * @param fillroom How much room there is to fill */ void GridLayouter::GrowIfNecessary(SizeInfo* sizes, unsigned sizes_count, unsigned fillroom) { if (fillroom == 0) return; bool grow_fills = false; unsigned fill_count = 0; for (unsigned i = 0; i < sizes_count; i++) { if (sizes[i].preferred_size == WidgetSizes::Fill) fill_count++; } while (fillroom > 0) { // Find columns/rows that have potential to grow unsigned dynamic_count = 0; for (unsigned i = 0; i < sizes_count; i++) { if (sizes[i].preferred_size != WidgetSizes::Fill && sizes[i].dynamic_size > 0) dynamic_count++; } // If there is no more growing potential, return if (dynamic_count == 0) { if (fill_count > 0) grow_fills = true; else return; } // Determine how much a column/row can grow. If possible growth per // each is smaller than 1 pixel, make it 1 pixel(smallest discrete // possible size) unsigned fillroom_per_column = fillroom / (grow_fills ? fill_count : dynamic_count); if (fillroom_per_column == 0) break; for (unsigned i = 0; i < sizes_count && fillroom > 0; i++) { if ((grow_fills || sizes[i].preferred_size != WidgetSizes::Fill) && sizes[i].dynamic_size > 0) { unsigned grow = min(fillroom_per_column, sizes[i].dynamic_size); sizes[i].size += grow; sizes[i].dynamic_size -= grow; fillroom -= grow; } } if (fill_count > 0) grow_fills = true; } } /** Shrinks size in sizes array where necessary if there is a surplus * @param sizes Array of sizes to change * @param sizes_count Number of elements in sizes * @param minimum_size Total minimum size * @param surplus How much size should be reduced */ void GridLayouter::ShrinkIfNecessary(SizeInfo* sizes, unsigned sizes_count, unsigned minimum_size, unsigned surplus) { if (surplus == 0) return; unsigned shrinkage = 0; // Resize proportionally to minimum size for (unsigned i = 0; i < sizes_count; i++) { unsigned shrink = (surplus * sizes[i].minimum_size) / minimum_size; shrinkage += shrink; sizes[i].size -= shrink; } surplus -= shrinkage; // Divide the remainder while (surplus > 0) { unsigned remainder = surplus; for (unsigned i = 0; i < sizes_count && remainder > 0; i++) { if (sizes[i].size > 0) { sizes[i].size--; remainder--; } } if (surplus == remainder) break; surplus = remainder; } } /** Calculates 'position' property of elements in SizeInfo array using size * @param sizes Sizes array to change * @param sizes_count Number of elements in sizes * @param start_pos Position of the first element */ void GridLayouter::CalculatePositions(SizeInfo* sizes, unsigned sizes_count, int start_pos) { for (unsigned i = 0; i < sizes_count; i++) { sizes[i].position = start_pos; start_pos += sizes[i].size + sizes[i].margin; } }
#include "TransitionGenerator.h" #include "Situation.h" #include "Transition.h" #include <iostream> using std::unique_ptr; using std::make_unique; using std::shared_ptr; TransitionGenerator::TransitionGenerator() { } TransitionGenerator::~TransitionGenerator() { } unique_ptr<Transition> TransitionGenerator::generate(shared_ptr<Situation> const &oldSituation, shared_ptr<Situation> const &newSituation) { if((*oldSituation) == (*newSituation)) { return nullptr; } else { return move(make_unique<Transition>(oldSituation, newSituation)); } }
// Toboggan_Trajectory.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> #include <string> int main() { std::vector<std::string> trees; std::string tmp; while (std::cin >> tmp) { trees.push_back(tmp); } int rotatory_index = 3, number_of_trees = 0; std::vector<std::pair<int, int>> steps = { {1, 1}, {3, 1}, {5, 1}, {7, 1}, {1, 2} }; for (std::pair<int, int> step: steps) { rotatory_index = step.first; number_of_trees = 0; for (int i = step.second; i < trees.size(); i+=step.second) { //std::cout << trees[i][rotatory_index] << ":" << rotatory_index << ":" << trees[i] << "\n"; if (trees[i][rotatory_index] == '#') number_of_trees++; rotatory_index = (rotatory_index + step.first) % trees[i].size(); } std::cout << number_of_trees << "\n"; } }
#include <assert.h> #include <math.h> #include <algorithm> #include <climits> #include <functional> #include <iostream> #include <numeric> #include <queue> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define ll long long using namespace std; const int mod = 1e9 + 7; int n, k, x; vector<int> nums; struct Solution { void solve() { ll m = 1; while (k--) m *= x; // cout << m << endl; vector<ll> pre(n), suf(n + 1); for (int i = 0; i != n; ++i) { pre[i] = (i == 0 ? 0 : pre[i - 1]) | nums[i]; suf[n - i - 1] = suf[n - i] | nums[n - i - 1]; } // for(auto p:pre)cout<<p<<" ";cout<<endl; // for(auto p:suf)cout<<p<<" ";cout<<endl; ll res = 0; for (int i = 0; i != n; ++i) { res = max(res, m * nums[i] | (i == 0 ? 0 : pre[i - 1]) | suf[i + 1]); } cout << res << endl; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); int T = 1; while (T--) { cin >> n >> k >> x; nums.resize(n); for (int i = 0; i != n; ++i) cin >> nums[i]; Solution test; test.solve(); } }
/*==================================================================== Copyright(c) 2018 Adam Rankin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ====================================================================*/ #pragma once // STD includes #include <vector> // DirectX includes #include <DirectXMath.h> namespace DX { class DeviceResources; class StepTimer; } namespace HoloIntervention { namespace Spatial { struct ModelNormalConstantBuffer { DirectX::XMFLOAT4X4 modelToWorld; DirectX::XMFLOAT4X4 normalToWorld; DirectX::XMFLOAT4 colorFadeFactor; }; struct VertexBufferType { DirectX::XMFLOAT4 vertex; }; struct IndexBufferType { uint32 index; }; struct OutputBufferType { DirectX::XMFLOAT4 intersectionPoint; DirectX::XMFLOAT4 intersectionNormal; DirectX::XMFLOAT4 intersectionEdge; bool intersection; }; struct WorldConstantBuffer { DirectX::XMFLOAT4X4 meshToWorld; }; static_assert((sizeof(WorldConstantBuffer) % (sizeof(float) * 4)) == 0, "World constant buffer size must be 16-byte aligned (16 bytes is the length of four floats)."); struct SurfaceMeshProperties { unsigned int vertexStride = 0; unsigned int normalStride = 0; unsigned int indexCount = 0; DXGI_FORMAT indexFormat = DXGI_FORMAT_UNKNOWN; }; class SurfaceMesh { public: SurfaceMesh(const std::shared_ptr<DX::DeviceResources>& deviceResources); ~SurfaceMesh(); void UpdateSurface(Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ newMesh); Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ GetSurfaceMesh(); void Update(DX::StepTimer const& timer, Windows::Perception::Spatial::SpatialCoordinateSystem^ baseCoordinateSystem); void CreateVertexResources(); void CreateDeviceDependentResources(); void ReleaseVertexResources(); void ReleaseDeviceDependentResources(); bool TestRayOBBIntersection(Windows::Perception::Spatial::SpatialCoordinateSystem^ desiredCoordinateSystem, uint64_t frameNumber, const Windows::Foundation::Numerics::float3& rayOrigin, const Windows::Foundation::Numerics::float3& rayDirection); bool TestRayIntersection(ID3D11DeviceContext& context, uint64_t frameNumber, Windows::Foundation::Numerics::float3& outHitPosition, Windows::Foundation::Numerics::float3& outHitNormal, Windows::Foundation::Numerics::float3& outHitEdge); bool GetIsActive() const; float GetLastActiveTime() const; Windows::Foundation::DateTime GetLastUpdateTime() const; void Render(bool usingVprtShaders); Windows::Foundation::Numerics::float3 GetLastHitPosition() const; Windows::Foundation::Numerics::float3 GetLastHitNormal() const; Windows::Foundation::Numerics::float3 GetLastHitEdge() const; // this and normal define a coordinate system uint64_t GetLastHitFrameNumber() const; void SetIsActive(const bool& isActive); Windows::Foundation::Numerics::float4x4 GetMeshToWorldTransform(); void SetColorFadeTimer(float duration); protected: void SwapVertexBuffers(); void ComputeOBBInverseWorld(Windows::Perception::Spatial::SpatialCoordinateSystem^ baseCoordinateSystem); HRESULT CreateStructuredBuffer(uint32 uStructureSize, Windows::Perception::Spatial::Surfaces::SpatialSurfaceMeshBuffer^ buffer, ID3D11Buffer** target); HRESULT CreateStructuredBuffer(uint32 uElementSize, uint32 uCount, ID3D11Buffer** target); HRESULT CreateReadbackBuffer(uint32 uElementSize, uint32 uCount); HRESULT CreateConstantBuffer(); HRESULT CreateDirectXBuffer(ID3D11Device& device, D3D11_BIND_FLAG binding, Windows::Storage::Streams::IBuffer^ buffer, ID3D11Buffer** target); HRESULT CreateBufferSRV(Microsoft::WRL::ComPtr<ID3D11Buffer> computeShaderBuffer, ID3D11ShaderResourceView** ppSRVOut); HRESULT CreateBufferUAV(Microsoft::WRL::ComPtr<ID3D11Buffer> computeShaderBuffer, ID3D11UnorderedAccessView** ppUAVOut); void RunComputeShader(ID3D11DeviceContext& context, uint32 nNumViews, ID3D11ShaderResourceView** pShaderResourceViews, ID3D11UnorderedAccessView* pUnorderedAccessView, uint32 Xthreads, uint32 Ythreads, uint32 Zthreads); protected: std::shared_ptr<DX::DeviceResources> m_deviceResources; Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ m_surfaceMesh = nullptr; // D3D compute shader resources Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexPositions = nullptr; Microsoft::WRL::ComPtr<ID3D11Buffer> m_triangleIndices = nullptr; Microsoft::WRL::ComPtr<ID3D11Buffer> m_updatedVertexPositions = nullptr; Microsoft::WRL::ComPtr<ID3D11Buffer> m_updatedTriangleIndices = nullptr; Microsoft::WRL::ComPtr<ID3D11Buffer> m_outputBuffer = nullptr; Microsoft::WRL::ComPtr<ID3D11Buffer> m_readBackBuffer = nullptr; Microsoft::WRL::ComPtr<ID3D11Buffer> m_meshConstantBuffer = nullptr; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_vertexSRV = nullptr; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_indexSRV = nullptr; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_updatedVertexSRV = nullptr; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_updatedIndicesSRV = nullptr; Microsoft::WRL::ComPtr<ID3D11UnorderedAccessView> m_outputUAV = nullptr; // D3D rendering resources Microsoft::WRL::ComPtr<ID3D11Buffer> m_renderingVertexPositions; Microsoft::WRL::ComPtr<ID3D11Buffer> m_renderingVertexNormals; Microsoft::WRL::ComPtr<ID3D11Buffer> m_renderingTriangleIndices; Microsoft::WRL::ComPtr<ID3D11Buffer> m_renderingUpdatedVertexPositions; Microsoft::WRL::ComPtr<ID3D11Buffer> m_renderingUpdatedVertexNormals; Microsoft::WRL::ComPtr<ID3D11Buffer> m_renderingUpdatedTriangleIndices; Microsoft::WRL::ComPtr<ID3D11Buffer> m_modelTransformBuffer; SurfaceMeshProperties m_meshProperties; SurfaceMeshProperties m_updatedMeshProperties; ModelNormalConstantBuffer m_constantBufferData; // DateTime to allow returning cached ray hits Windows::Foundation::DateTime m_lastUpdateTime; // Behavior variables std::atomic_bool m_vertexLoadingComplete = false; std::atomic_bool m_loadingComplete = false; std::atomic_bool m_isActive = false; std::atomic_bool m_updateNeeded = false; std::atomic_bool m_updateReady = false; float m_lastActiveTime = -1.f; float m_colorFadeTimer = -1.f; float m_colorFadeTimeout = -1.f; // Bounding box inverse world matrix Windows::Foundation::Numerics::float4x4 m_worldToBoxCenterTransform = Windows::Foundation::Numerics::float4x4::identity(); Windows::Perception::Spatial::SpatialCoordinateSystem^ m_lastWorldToBoxComputedCoordSystem = nullptr; // Number of indices in the mesh data uint32 m_indexCount = 0; // Ray-triangle intersection related behavior variables std::atomic_bool m_hasLastComputedHit = false; Windows::Foundation::Numerics::float3 m_lastHitPosition; Windows::Foundation::Numerics::float3 m_lastHitNormal; Windows::Foundation::Numerics::float3 m_lastHitEdge; uint64 m_lastFrameNumberComputed = 0; static const uint32 NUMBER_OF_FRAMES_BEFORE_RECOMPUTE = 2; // This translates into FPS/NUMBER_OF_FRAMES_BEFORE_RECOMPUTE recomputations per sec Windows::Foundation::Numerics::float4x4 m_meshToWorldTransform; Windows::Foundation::Numerics::float4x4 m_normalToWorldTransform; std::mutex m_meshResourcesMutex; }; } }
#ifndef _METADATA_H_ #define _METADATA_H_ #include "mcprotocol_base.h" #include "slotdata.h" namespace MC { namespace Protocol { namespace Msg { class Metadata : public BaseMessage { public: Metadata(); Metadata(int8_t _item); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int8_t getItem() const; void setItem(int8_t _val); private: int8_t _pf_item; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG__METADATA__H_
/**************************************************************************** ** Copyright (C) 2017 Olaf Japp ** ** This file is part of FlatSiteBuilder. ** ** FlatSiteBuilder is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** FlatSiteBuilder is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #include "texteditor.h" #include "flatbutton.h" #include "xmlhighlighter.h" #include <QGridLayout> #include <QTabWidget> #include <QTextEdit> #include <QPushButton> #include <QLabel> #include <QXmlStreamWriter> #include <QXmlStreamReader> TextEditor::TextEditor() { m_changed = false; setAutoFillBackground(true); QFont font; font.setFamily("Courier"); font.setFixedPitch(true); font.setPointSize(13); QGridLayout *grid = new QGridLayout(); grid->setMargin(0); FlatButton *close = new FlatButton(":/images/close_normal.png", ":/images/close_hover.png"); close->setToolTip("Close Editor"); m_html = new QTextEdit(); m_html->setFont(font); m_html->setAcceptRichText(false); m_html->setLineWrapMode(QTextEdit::NoWrap); QFontMetrics metrics(font); m_html->setTabStopWidth(4 * metrics.width(' ')); new XmlHighlighter(m_html->document()); m_adminlabel = new QLineEdit(); m_adminlabel->setMaximumWidth(200); QLabel *titleLabel = new QLabel("Text Module"); QFont fnt = titleLabel->font(); fnt.setPointSize(16); fnt.setBold(true); titleLabel->setFont(fnt); grid->addWidget(titleLabel, 0, 0); grid->addWidget(close, 0, 1, 1, 1, Qt::AlignRight); grid->addWidget(m_html, 1, 0, 1, 2); grid->addWidget(new QLabel("Admin Label"), 2, 0); grid->addWidget(m_adminlabel, 3, 0, 1, 2); setLayout(grid); connect(close, SIGNAL(clicked()), this, SLOT(closeEditor())); connect(m_html, SIGNAL(textChanged()), this, SLOT(contentChanged())); connect(m_adminlabel, SIGNAL(textChanged(QString)), this, SLOT(contentChanged())); } void TextEditor::closeEditor() { if(m_changed) { m_content = ""; QXmlStreamWriter stream(&m_content); stream.writeStartElement("Text"); stream.writeAttribute("adminlabel", m_adminlabel->text()); stream.writeCDATA(m_html->toPlainText()); stream.writeEndElement(); } emit close(); } QString TextEditor::load(QXmlStreamReader *xml) { QString content = ""; QXmlStreamWriter stream(&content); stream.writeStartElement("Text"); stream.writeAttribute("adminlabel", xml->attributes().value("adminlabel").toString()); stream.writeCDATA(xml->readElementText()); stream.writeEndElement(); return content; } void TextEditor::setContent(QString content) { m_content = content; QXmlStreamReader stream(m_content); stream.readNextStartElement(); if(stream.name() == "Text") { m_adminlabel->setText(stream.attributes().value("adminlabel").toString()); m_html->setPlainText(stream.readElementText()); } else { m_html->setPlainText(m_content); m_adminlabel->setText(stream.attributes().value("adminlabel").toString()); } m_changed = false; } QString TextEditor::getHtml(QXmlStreamReader *xml) { return xml->readElementText(); }
#include"matrix03.h" #include<vector> #include<gtest/gtest.h> TEST(MulTest, meaningful) { std::vector<std::vector<int>> left = { {11, 12, 13, 14}, {21, 22, 23, 24}, {31, 32, 33, 34} }; std::vector<std::vector<int>> right; right.resize(4, std::vector<int>(3, 1.)); std::vector<std::vector<int>> expected = { {50, 50, 50}, {90, 90, 90}, {130, 130, 130} }; szeMatrix::Matrix<int> m1(left); szeMatrix::Matrix<int> m2(right); szeMatrix::Matrix<int> multiplied = m1.mul(m2); ASSERT_EQ(expected.size(), multiplied.getRowCount()) << "A sorok szama elter! Elvart: " << expected.size() << ", kapott: " << multiplied.getRowCount(); ASSERT_EQ(expected[0].size(), multiplied.getColCount()) << "Az oszlopok szama elter! Elvart: " << expected[0].size() << ", kapott: " << multiplied.getColCount(); for(unsigned row=0; row<expected.size(); row++) { for(unsigned col=0; col<expected[row].size(); col++) { EXPECT_EQ(expected[row][col], multiplied.get(row, col)) << "Nem egyezik az elemek erteke a [" << row << "][" << col << "] helyen!"; } } }
#include <Arduino.h> #include <EEPROM.h> #define EEPROM_SIZE 1 #define btn 15 unsigned char ledStatus = LOW; bool changeLedStatus = false; volatile bool interruptState = false; int totalInterruptCounter = 0; portMUX_TYPE gpioIntMux = portMUX_INITIALIZER_UNLOCKED; void IRAM_ATTR gpioISR() { portENTER_CRITICAL(&gpioIntMux); changeLedStatus = true; portEXIT_CRITICAL(&gpioIntMux); } void setup() { Serial.begin(9600); // put your setup code here, to run once: pinMode(BUILTIN_LED, OUTPUT); pinMode(btn, INPUT_PULLUP); attachInterrupt(btn, &gpioISR, FALLING); //rising akan menyala jika dilepas falling ketika dipencet akan hidup pinMode(5, OUTPUT); EEPROM.begin(EEPROM_SIZE); delay(500); ledStatus = EEPROM.read(0); digitalWrite(BUILTIN_LED, ledStatus); digitalWrite(5, ledStatus); Serial.print("LED Status "); Serial.println(ledStatus); } void loop() { // put your main code here, to run repeatedly: if (changeLedStatus) { portENTER_CRITICAL(&gpioIntMux); changeLedStatus = false; portEXIT_CRITICAL(&gpioIntMux); ledStatus = !ledStatus; EEPROM.write(0, ledStatus); EEPROM.commit(); digitalWrite(BUILTIN_LED, ledStatus); if (ledStatus) { digitalWrite(5, HIGH); } else { digitalWrite(5, LOW); } } }
/* * types.hpp * * Created on: Sep 24, 2019 * Author: jacoboffersen */ #ifndef TYPES_HPP_ #define TYPES_HPP_ typedef unsigned short int u8; #endif /* TYPES_HPP_ */
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; const int maxn = 1e6 + 10; int a[maxn]; int main() { int t,n; scanf("%d",&t); for (int ca = 1;ca <= t;ca++) { int p = 1,ans = 0,k; scanf("%d",&n); scanf("%d",&a[p]); for (int i = 2;i <= n; i++) { scanf("%d",&k); while (p > 0 && k < a[p]) {p--;ans++;} a[++p] = k; } printf("Case #%d: %d\n",ca ,ans); } return 0; }
#include <iostream> #include <algorithm> using namespace std; int main(){ int t{}, n{}; int max_speed{}, speed{}; cin >> t; for(int i = 1; i <= t; ++i){ cin >> n; max_speed = 0; for(int j = 0; j < n; ++j){ cin >> speed; max_speed = max(max_speed, speed); } cout << "Case " << i << ": " << max_speed << endl; } return 0; }
#ifndef UNIVERSE_H #define UNIVERSE_H #include "solarsystem.h" #include "SimConstants.h" #include "custom_sim_exceptions.h" namespace Simulation { class Universe { public: // Members Universe(int world_count); ~Universe(void); void Init(); void Update(float dt); void AddSolarSystem (SolarSystem* solarsystem); // Getters and setters SolarSystem** getSolarSystems() { return this->solar_systems; } SolarSystem* getIthSolarSystem(int i) { return this->solar_systems[i]; } SolarSystem* getSolarSystemByID(int id); World** getWorlds() { return this->worlds; } World* getIthWorld(int i) { return this->worlds[i]; } World* getWorldByID(int id); void setIthWorld(int i, World* world) { this->worlds[i] = world; } int getWorldCount() { return this->world_count; } int getSolarSystemCount() { return this->solar_system_count; } private: // Properties int world_count; int solar_system_count = 0; World* worlds[MAX_WORLDS] = {NULL}; SolarSystem* solar_systems[MAX_SOLARSYSTEMS] = {NULL}; }; } #endif
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMap> #include <QWindow> #include <QMutex> #include <xcb/xcb.h> #include <xcb/xcb_ewmh.h> #include <QtX11Extras/QX11Info> #include <QCloseEvent> class QSystemTrayIcon; class QThread; struct strucWindow { int wid = 0; QString name = ""; QWindow *window{nullptr}; double opacity{1.0}; }; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); void setAllWindows(); void setAllWindowsOpacity(double opacity = 0.99); void searchAllWindowType(); uint32_t searchWindowType(int wid); QList<unsigned long> searchWindowid(const QString &name); void initTray(); void initXcb(); void initNoopacity(); void closeEvent(QCloseEvent *event); private slots: void quitApp(); void on_opacitySlider_valueChanged(int); private: Ui::MainWindow *ui; QMap <int, strucWindow> m_windowVec; xcb_ewmh_connection_t m_ewmh_connection; xcb_intern_atom_cookie_t *m_cookie{nullptr}; QMutex m_mutex; bool m_bEvent = true; QThread *m_eventThread{nullptr}; unsigned long m_myId = 0; bool m_bFisrt = true; QSystemTrayIcon *m_trayIcon{nullptr}; QMenu *m_traymenu{nullptr}; QList <unsigned long> m_noOpacityId; }; #endif // MAINWINDOW_H
#include "connexion.h" using namespace std; int connexion(u_short port, SOCKET &sock, SOCKADDR_IN &sin) { WSADATA WSAData; WSAStartup(MAKEWORD(2, 0), &WSAData); sock = socket(AF_INET, SOCK_STREAM, 0); sin.sin_addr.s_addr = INADDR_ANY; sin.sin_family = AF_INET; sin.sin_port = htons(port); bind(sock, (SOCKADDR *)&sin, sizeof(sin)); listen(sock, 0); cout << "Ecoute du port: " << port << endl; return 0; }
#include "Director.h" #include"Builder.h" Director::Director(Builder * bld):_bld(bld) { } Director::~Director() { //if(_bld) // delete _bld; //_bld = nullptr; } void Director::Construct() { _bld->BuildPartA("one"); _bld->BuildPartB("one"); _bld->BuildPartC("one"); }
#include "SvrConfig_.h" #include <vector> #include "tinyxml.h" #include "Logger.h" using namespace std; static std::string GetAttribute(TiXmlElement * element,std::string name,std::string defaultValue) { const char * attribute = element->Attribute( name.c_str() ) ; if(attribute==NULL || std::string(attribute)=="") return defaultValue; else return std::string(attribute); } static int GetAttribute(TiXmlElement * element,std::string name, int defaultValue) { const char * attribute = element->Attribute( name.c_str() ) ; if(attribute==NULL || std::string(attribute)=="") return defaultValue; else return atoi(attribute); } SvrConfig_::SvrConfig_() { } SvrConfig_::~SvrConfig_() { } void SvrConfig_::init(const std::string& path) { size = 0; parseXML(path.c_str()); } int SvrConfig_::parseXML(const char* path) { TiXmlDocument *myDocument = NULL; try { myDocument = new TiXmlDocument(path); if (!myDocument->LoadFile()) { int i = myDocument->ErrorId(); std::string error; if (i==2) { error = "file not exist: " + std::string(path); } else { error = "file format error: " + std::string(path); } LOGGER(E_LOG_ERROR) << error; throw error ; } //back TiXmlElement *rootNode = myDocument->RootElement(); TiXmlElement *backElement= rootNode->FirstChildElement("back") ; if(backElement==NULL) { LOGGER(E_LOG_ERROR) << "cann't find back node"; throw "cann't find back node"; } for( TiXmlNode* child1 = backElement->FirstChild(); child1!=NULL; child1=child1->NextSibling()) { //nodes TiXmlElement * nodesElement = child1->ToElement(); int id = GetAttribute(nodesElement, "id",-1); Nodes* backnodes= new Nodes(id); for (TiXmlNode* child2 = nodesElement->FirstChild(); child2!=NULL; child2=child2->NextSibling()) { //server TiXmlElement * serverElement = child2->ToElement(); int id = GetAttribute(serverElement, "id",-1); string host = GetAttribute(serverElement, "host","NULL"); int port = GetAttribute(serverElement, "port",-1); std::string is_heart_str = GetAttribute(serverElement, "heart","false"); bool isheart = (is_heart_str=="true"); backnodes->add(new Node( id, host.c_str(), port, isheart)); LOGGER(E_LOG_INFO) << "Server: ID=" << id << " host=" << host << " port=" << port << " heart" << is_heart_str; } back_nodes[size++] = backnodes; } } catch (std::string& e) { delete myDocument ; LOGGER(E_LOG_ERROR) << "err :" << e; return -1; } return 0; }
// 全排列.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include<string> using namespace std; #include<vector> #include<algorithm> vector<string> res; void quanpai(string& a, int low, int high) { if (low >= high) res.push_back(a); for (int i = low; i < high; i++) { swap(a[low], a[i]); quanpai(a, low + 1, high); swap(a[low], a[i]); } } void printfvec(const vector<string> a) { for (auto it = a.begin(); it != a.end(); it++) { cout << *it << ' '; } cout << endl; } int main() { string a = "abcd"; quanpai(a, 0, a.size()); sort(res.begin(), res.end()); auto it = unique(res.begin(),res.end()); res.erase(it, res.end()); printfvec(res); return 0; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
#include <iostream> #include <string> class HashMap { private: struct Node { std::string name; int key; struct Node* next; }; int hash(int key) { return key % 5; } Node** arr = new Node*[5]; public: void get(int Key) { int index = hash(Key); if (NULL == arr[index]) { std::cout << "No such number!" << std::endl; return; } Node* temp = arr[index]; while (NULL != temp) { if (temp -> key == Key) { std::cout << Key << " phone number belongs to " << temp -> name << "." << std::endl; return; } temp = temp -> next; } std::cout << "No such phone number!" << std::endl; return; } void update(int key, std::string name) { int index = hash(key); if (NULL == arr[index]) { std::cout << "Nothing to update!" << std::endl; return; } Node* temp = arr[index]; while (NULL != temp) { if (temp -> key == key) { temp -> name = name; return; } temp = temp -> next; } std::cout << "No such key found!" << std::endl; } void add(std::string name, int key) { int index = hash(key); Node* newNode = new Node(); newNode -> key = key; newNode -> name = name; newNode -> next = NULL; if (NULL == arr[index]) { arr[index] = newNode; return; } Node* temp = arr[index]; while (NULL != temp -> next) { temp = temp -> next; } temp -> next = newNode; } void remove1(int key) { int index = hash(key); if (NULL == arr[index]) { std::cout << "No phone number to remove " << std::endl; return; } Node* temp = arr[index]; if (arr[index] -> key == key) { arr[index] = temp -> next; delete temp; return; } Node* previous = temp; temp = temp -> next; while (NULL != temp) { if (temp -> key == key) { previous -> next = temp -> next; delete temp; return; } previous = temp; temp = temp -> next; } } HashMap() { arr = new Node*[5]; } ~HashMap() { Node* temp = NULL; delete[] arr; } }; int main() { HashMap* hm = new HashMap; hm -> add("Lord Tywin Lannister", 55); hm -> add("Lord Petyr Baelish", 70); hm -> add("Vahan Hovhannisyan", 65); hm -> add("Aegon Targeryan", 80); hm -> add("Lord Varys", 56); hm -> add("Robb Stark", 71); hm -> add("Joffrey Baratheon", 61); hm -> remove1(55); hm -> remove1(80); hm -> get(55); hm -> get(70); hm -> get(65); hm -> get(80); hm -> get(56); hm -> get(71); hm -> get(61); hm -> update(61, "Renly Baratheon"); hm -> get(61); return 0; }
#include "interface.h" #include "machine.h" #include "util.h" #include <ncurses.h> #include <menu.h> #include <sstream> #include <fstream> #include <cmath> #include <vector> #include <json/json.h> #include <menu.h> #include <dirent.h> const int HEADER_MENU_LENGTH=4; //not really the best way to do things menu_option header_menus[] = { {"F1" , "- Select Machine"}, {"HOME","- Home Tool"}, {"ESC", "- Halt Tool"}, {"q", "- Quit Program"} }; void draw_header( WINDOW *header){ box( header, 0, 0 ); std::stringstream ss; ss << "Miller Runner" << " " << MillRunner_VERSION_MAJOR << "." << MillRunner_VERSION_MINOR; mvwprintw(header, 0,2, ss.str().c_str() ); int x =2; for( int i = 0; i < HEADER_MENU_LENGTH; i++){ wattron( header, A_BOLD | A_UNDERLINE ); mvwprintw(header, 1,x, header_menus[i].key.c_str() ); wattroff( header, A_BOLD | A_UNDERLINE ); x+=header_menus[i].key.size()+1; mvwprintw(header, 1,x, header_menus[i].text.c_str() ); x+=header_menus[i].text.size()+1; } } MENU *gen_select_machine( ){ /* go through the machine defs directory and each entry to the menu */ std::vector<std::string> files; DIR *dir; struct dirent *ent; if ((dir = opendir(MACHINE_DEFS)) != NULL ){ while (( ent = readdir( dir)) != NULL){ std::string name( ent->d_name ); if( name != "." && name != ".." ){ files.push_back( name ); } } } else{ // need error handling case } ITEM **items; ITEM *item; MENU *menu; items = new ITEM*[files.size()+2]; for( int i = 0; i < files.size(); i++ ){ items[i] = new_item( files[i].c_str(), "" ); } items[files.size()] = new_item( "Cancel", "" ); items[files.size()+1] = (ITEM *)NULL; menu = new_menu( (ITEM **)items ); return menu; } void draw_machine( Machine *machine, WINDOW *win ){ box(win, 0, 0 ); if( machine != NULL ){ mvwprintw( win, 0, 1, machine->get_name().c_str() ); Vector dim = machine->get_dimensions(); int mx,my; getmaxyx( win, mx, my ); float z = dim.z/mx; box( win, 1, 1 ); // draw ZX plane box // draw XY plane box } else{ mvwprintw( win, 0, 1, "Dummy" ); } } void draw_left( WINDOW *win){ box( win, 0, 0 ); }
#include<iostream> using namespace std; class shape { protected : float d1,d2,a; public : shape (float k,float l) { d1=k; d2=l;} virtual float calc_area ()=0; }; class rectangle : public shape { public : rectangle (float k,float l) : shape (k,l) {} float calc_area () { a=d1*d2; return a;} }; class triangle : public shape { public : triangle (float k,float l) : shape (k,l) {} float calc_area () { a=0.5*d1*d2; return a;} }; int main () { float a,b,c; int ch; shape *p; cout<<" ENTER THE CHOICE TO CALCUALTE AREA OF 1.RECTANGLE,2.TRAINGLE"<<endl; cin>>ch; if (ch==1) { cout<<"enter length and breadth"<<endl; cin>>a>>b; rectangle r(a,b); p=&r; c=p->calc_area (); cout<<" AREA IS"<<endl<<c<<endl; } else if (ch==2) { cout<<"enter base and height"<<endl; cin>>a>>b; triangle t(a,b); p=&t; c=p->calc_area (); cout<<" AREA IS"<<endl<<c<<endl; } else cout<<"INVALID CHOICE"<<endl; return 0; }
#pragma once #include "utils/ptts.hpp" #include "proto/config_league.pb.h" using namespace std; namespace pc = proto::config; namespace nora { namespace config { using league_ptts = ptts<pc::league>; league_ptts& league_ptts_instance(); void league_ptts_set_funcs(); using league_record_list_limit_ptts = ptts<pc::league_record_list_limit>; league_record_list_limit_ptts& league_record_list_limit_ptts_instance(); void league_record_list_limit_ptts_set_funcs(); using league_levelup_ptts = ptts<pc::league_levelup>; league_levelup_ptts& league_levelup_ptts_instance(); void league_levelup_ptts_set_funcs(); using league_resource_ptts = ptts<pc::league_resource>; league_resource_ptts& league_resource_ptts_instance(); void league_resource_ptts_set_funcs(); using league_campaign_ptts = ptts<pc::league_campaign>; league_campaign_ptts& league_campaign_ptts_instance(); void league_campaign_ptts_set_funcs(); using league_drop_ptts = ptts<pc::league_drop>; league_drop_ptts& league_drop_ptts_instance(); void league_drop_ptts_set_funcs(); using league_apply_item_ptts = ptts<pc::league_apply_item>; league_apply_item_ptts& league_apply_item_ptts_instance(); void league_apply_item_ptts_set_funcs(); using league_creating_ptts = ptts<pc::league_creating>; league_creating_ptts& league_creating_ptts_instance(); void league_creating_ptts_set_funcs(); using league_building_ptts = ptts<pc::league_building>; league_building_ptts& league_building_ptts_instance(); void league_building_ptts_set_funcs(); using league_urban_management_level_ptts = ptts<pc::league_urban_management_level>; league_urban_management_level_ptts& league_urban_management_level_ptts_instance(); void league_urban_management_level_ptts_set_funcs(); using league_daily_quest_level_ptts = ptts<pc::league_daily_quest_level>; league_daily_quest_level_ptts& league_daily_quest_level_ptts_instance(); void league_daily_quest_level_ptts_set_funcs(); using league_government_level_ptts = ptts<pc::league_government_level>; league_government_level_ptts& league_government_level_ptts_instance(); void league_government_level_ptts_set_funcs(); using city_ptts = ptts<pc::city>; city_ptts& city_ptts_instance(); void city_ptts_set_funcs(); using system_league_ptts = ptts<pc::system_league>; system_league_ptts& system_league_ptts_instance(); void system_league_ptts_set_funcs(); using city_battle_logic_ptts = ptts<pc::city_battle_logic>; city_battle_logic_ptts& city_battle_logic_ptts_instance(); void city_battle_logic_ptts_set_funcs(); using city_battle_treasure_box_defender_ptts = ptts<pc::city_battle_treasure_box>; city_battle_treasure_box_defender_ptts& city_battle_treasure_box_defender_ptts_instance(); void city_battle_treasure_box_defender_ptts_set_funcs(); using city_battle_treasure_box_offensive_ptts = ptts<pc::city_battle_treasure_box>; city_battle_treasure_box_offensive_ptts& city_battle_treasure_box_offensive_ptts_instance(); void city_battle_treasure_box_offensive_ptts_set_funcs(); using city_battle_ptts = ptts<pc::city_battle>; city_battle_ptts& city_battle_ptts_instance(); void city_battle_ptts_set_funcs(); using league_war_logic_ptts = ptts<pc::league_war_logic>; league_war_logic_ptts& league_war_logic_ptts_instance(); void league_war_logic_ptts_set_funcs(); using league_permission_ptts = ptts<pc::league_permission>; league_permission_ptts& league_permission_ptts_instance(); void league_permission_ptts_set_funcs(); using league_permission_function_ptts = ptts<pc::league_permission_function>; league_permission_function_ptts& league_permission_function_ptts_instance(); void league_permission_function_ptts_set_funcs(); } }
#include <iostream> #include <string> #include <algorithm> #include <utility> #include <map> bool isEven(int number) { bool isEven = false; if (number % 2 == 0) { isEven = true; } return isEven; } int main() { int anumber = 0; std::cin >> anumber; std::string oddevenWord[] = {"ODD", "EVEN"}; std::map<int, std::string> a; for ( int i = 0; i < anumber; ++i ) { if (isEven(i)) { std::string str = oddevenWord[1]; a.insert(std::pair<int, std::string>(i, str)); } else { std::string str = oddevenWord[0]; a.insert(std::pair<int, std::string>(i, str)); } } for ( auto &j : a ) { std::cout << "KEY: " << j.first << " VALUE: " << j.second << std::endl; } return 0; }
#include "citygen.hpp" #include "city.hpp" #include "components/room.hpp" #include "entities/citizen.hpp" #include "entities/workroom.hpp" #include "entities/entity.hpp" #include "entities/filestorage.hpp" #include "hydroponics/hydroponics.hpp" #include "hydroponics/hydroponics_table.hpp" #include "storage/storageroom.hpp" enum RoomTypes { Regular, FoodSupply, FoodStorage, FileStorage, Infirmary, Engineering, RoomTypesCount }; struct RoomProperties { int height, width, seed, top, left, bottom, right; RoomTypes roomType; bool isCompound, floorOnly; bool doorN, doorE, doorW, doorS; RoomProperties(int iTop, int iLeft, int iHeight, int iWidth) { top = iTop; left = iLeft; bottom = iTop + iHeight - 1; right = iLeft + iWidth - 1; height = iHeight; width = iWidth; // randomly determine the room type roomType = (RoomTypes)(rand() % RoomTypes::RoomTypesCount); // 2/3 chance that the room has smaller rooms inside it isCompound = ((rand() % 3) != 0); // is the room purely floor floorOnly = false; if ((height < 3) || (width < 3)) { floorOnly = true; } // assume you can put doors on all sides doorN = true; doorS = true; doorE = true; doorW = true; // if the wall size is too small then don't put // the door on that wall if (height < 3) { doorE = false; doorW = false; } // if the wall size is too small then don't put // the door on that wall if (width < 3) { doorN = false; doorS = false; } } }; class MathHelper { public: static int GetFactor(int p) { int factor = (p / 2); for (; factor > 2; factor--) { if ((p % factor) == 0) return factor; } return p; } }; #define CITY_GENERATION_DEPTH 2 #define ROOM_MIN_SEGMENTS 2 #define ROOM_MAX_SEGMENTS 6 CityProperties::CityProperties() {} CityProperties::CityProperties(int iHeight, int iWidth) : height(iHeight), width(iWidth), seed((int)time(0)), top(0), left(0), bottom(height-1), right(width-1) {} CityProperties::CityProperties(int iHeight, int iWidth, int iSeed) : height(iHeight), width(iWidth), seed(iSeed), top(0), left(0), bottom(height-1), right(width-1) {} struct CityGenerator { CityGenerator(City& city, CityProperties const& props) : city(city), props(props) { // set seed for the city generator srand(props.seed); // assume the entire city area is just ground for (int i = 0; i < city.getYSize(); ++i) { for (int j = 0; j < city.getXSize(); ++j) { city.tile(j, i) = { Tile::TileKind::ground }; } } // recursively generate city // TODO: may be we can move this to initialize() generate(CITY_GENERATION_DEPTH); } // generates random int value bound by min and max // TODO: move to a helper file int randNext() { return rand(); } int randNext(int max) { if (max == 0) return 0; return rand() % max; } int randNext(int min, int max) { if (min >= max) return min; return min + (rand() % (max - min)); } // Recursive city generator. Accepts 'depth' to determine // the segmentation granularity. void generate(int depth) { // determine the number of segments to cut vertically and horizontally int vRooms = randNext(ROOM_MIN_SEGMENTS, ROOM_MAX_SEGMENTS); int hRooms = randNext(ROOM_MIN_SEGMENTS, ROOM_MAX_SEGMENTS); // determine the size of each segment int vSize = city.getYSize() / vRooms; int hSize = city.getXSize() / hRooms; // often the factorization might not be clean // so determine where the vertical oversized segment should go. int *vSegments = new int[vRooms]; for (int i = 0; i < vRooms; i++) vSegments[i] = vSize; int vIndex = randNext(0, vRooms); vSegments[vIndex] = vSize + city.getYSize() - (vSize * vRooms); // often the factorization might not be clean // so determine where the horizontal oversized segment should go. int *hSegments = new int[hRooms]; for (int i = 0; i < hRooms; i++) hSegments[i] = hSize; int hIndex = randNext(0, hRooms); hSegments[hIndex] = hSize + city.getXSize() - (hSize * hRooms); // Start placing rooms recursively for (int i = 0, top = 0; i < vRooms; i++) { for (int j = 0, left = 0; j < hRooms; j++) { // determine the coordinates of the room int height = vSegments[i], width = hSegments[j]; int actualTop = top, actualLeft = left; // this is to avoid double walling each room // if removed each room will sit inside a previous bound // hence adding a wall for each level of depth if (i != 0) { actualTop = top - 1; height += 1; } if (j != 0) { actualLeft = left - 1; width += 1; } // create room properties, this determines what kind of room, if it has doors // where the doors are, orientation, etc RoomProperties rp(actualTop, actualLeft, height, width); // determine if the room is a boundry for smaller rooms if (rp.isCompound) { // build more rooms inside the boundary generate(rp, depth - 1); } else { // construct the room using the room properties build_room(rp); } left += hSegments[j]; } top += vSegments[i]; } // construct the perimeter wall build_perimeter_wall(); // add RED entities at a random position add_entities(Security::Mask::RED, 2, 4); // add ORANGE entities at a random position add_entities(Security::Mask::ORANGE, 1, 1); // change doors to ground finalize_doors(); // find room locations // TODO: this can be removed( see comment on method) find_rooms(); delete[] vSegments; delete[] hSegments; } // Recursive city generator. Accepts 'depth' to determine // the segmentation granularity. This version uses room properties to // perform segmentation. void generate(const RoomProperties& roomProperties, int depth) { // if the depth is reached draw floor if (depth <= 0) { build_floor(roomProperties); return; } // determine the number of segments to cut vertically and horizontally int vRooms = randNext(ROOM_MIN_SEGMENTS, ROOM_MAX_SEGMENTS); int hRooms = randNext(ROOM_MIN_SEGMENTS, ROOM_MAX_SEGMENTS); // determine the size of each segment int vSize = roomProperties.height / vRooms; int hSize = roomProperties.width / hRooms; // if the size is too small return if ((vSize <= 0) || (hSize <= 0)) { return; } // often the factorization might not be clean // so determine where the vertical oversized segment should go. int *vSegments = new int[vRooms]; for (int i = 0; i < vRooms; i++) vSegments[i] = vSize; int vIndex = randNext(0, vRooms); vSegments[vIndex] = vSize + roomProperties.height - (vSize * vRooms); // often the factorization might not be clean // so determine where the horizontal oversized segment should go. int *hSegments = new int[hRooms]; for (int i = 0; i < hRooms; i++) hSegments[i] = hSize; int hIndex = randNext(0, hRooms); hSegments[hIndex] = hSize + roomProperties.width - (hSize * hRooms); // Start placing rooms recursively for (int i = 0, top = roomProperties.top; i < vRooms; i++) { for (int j = 0, left = roomProperties.left; j < hRooms; j++) { // determine the coordinates of the room int height = vSegments[i], width = hSegments[j]; int actualTop = top, actualLeft = left; // this is to avoid double walling each room // if removed each room will sit inside a previous bound // hence adding a wall for each level of depth if (i != 0) { actualTop = top - 1; height += 1; } if (j != 0) { actualLeft = left - 1; width += 1; } // create room properties, this determines what kind of room, if it has doors // where the doors are, orientation, etc RoomProperties rp(actualTop, actualLeft, height, width); // determine if the room is a boundry for smaller rooms if (rp.isCompound) { // build more rooms inside the boundary generate(rp, depth - 1); } else { // construct the room using the room properties build_room(rp); } left += hSegments[j]; } top += vSegments[i]; } delete[] vSegments; delete[] hSegments; } // adds a random number of entities of a specified type void add_entities(Security::Mask entity, int min, int max) { int count = randNext(min, max); for (int i = 0; i<count;) { int r = randNext(0, city.getYSize()); int c = randNext(0, city.getXSize()); if (city.tile(c, r).type == Tile::TileKind::ground) { new_citizen({ &city, c, r }, entity); i++; } } } // construct a room void build_room(const RoomProperties& rp) { // if the room is just a floor build it if (rp.floorOnly) { build_floor(rp); return; } // construct a specific room. switch (rp.roomType) { case RoomTypes::Regular: build_regular(rp); build_doors(rp); break; case RoomTypes::FileStorage: build_file_storage(rp); build_doors(rp); break; case RoomTypes::Engineering: build_engineering(rp); build_doors(rp); break; case RoomTypes::FoodSupply: build_food_supply(rp); build_doors(rp); break; case RoomTypes::FoodStorage: build_food_storage(rp); build_doors(rp); break; case RoomTypes::Infirmary: build_infirmary(rp); build_doors(rp); break; default: break; } } void build_regular(const RoomProperties& rp) { for (int i = rp.top; i <= rp.bottom; i++) { for (int j = rp.left; j <= rp.right; j++) { if (city.tile(j, i).type != Tile::TileKind::door) { if ((i == rp.top) || (i == rp.bottom) || (j == rp.left) || (j == rp.right)) { city.tile(j, i).type = Tile::TileKind::wall; } else { city.tile(j, i).type = Tile::TileKind::ground; } } } } } void build_food_storage(const RoomProperties& rp) { for (int i = rp.top; i <= rp.bottom; i++) { for (int j = rp.left; j <= rp.right; j++) { if (city.tile(j, i).type != Tile::TileKind::door) { if ((i == rp.top) || (i == rp.bottom) || (j == rp.left) || (j == rp.right)) { city.tile(j, i).type = Tile::TileKind::wall; } else { city.tile(j, i).type = Tile::TileKind::ground; } } } } storage::make_storageroom({ &city, rp.left + 1, rp.top + 1, rp.width - 2, rp.height - 2 }); } void build_file_storage(const RoomProperties& rp) { build_regular(rp); if ((rp.width >= 5) || (rp.height >= 5)) { int top = rp.top + 2; int bottom = rp.bottom - 2; int left = rp.left + 2; int right = rp.right - 2; if (rp.height > rp.width) { int factor = MathHelper::GetFactor(rp.height - 4); if ((rp.height - 4) <= 8) { factor = rp.height; } for (int i = top; i <= bottom; i++) { for (int j = left; j <= right; j += 2) { if ((city.tile(j, i).type == Tile::TileKind::ground) && ((i % factor) != 0)) { make_filingcabinet({ &city, j, i }); } } } } else { int factor = MathHelper::GetFactor(rp.width - 4); if ((rp.width - 4) <= 8) { factor = rp.width; } for (int i = top; i <= bottom; i += 2) { for (int j = left; j <= right; j++) { if ((city.tile(j, i).type == Tile::TileKind::ground) && ((j % factor) != 0)) { make_filingcabinet({ &city, j, i }); } } } } make_filestorage({ &city, rp.left + 1, rp.top + 1, rp.width - 2, rp.height - 2 }); } } void build_engineering(const RoomProperties& rp) { build_regular(rp); if (((rp.width >= 5) && (rp.height >= 8)) || ((rp.width >= 8) && (rp.height >= 5))) { int top = rp.top + 2; int bottom = rp.bottom - 2; int left = rp.left + 2; int right = rp.right - 2; if (rp.height > rp.width) { if ((rp.height % 2) == 0) { for (int i = top; i <= (top + 1); i++) { for (int j = left; j <= right; j++) { if (city.tile(j, i).type == Tile::TileKind::ground) { city.tile(j, i).type = Tile::TileKind::engineering; } } } } else { for (int i = (bottom - 1); i <= bottom; i++) { for (int j = left; j <= right; j++) { if (city.tile(j, i).type == Tile::TileKind::ground) { city.tile(j, i).type = Tile::TileKind::engineering; } } } } } else { if ((rp.width % 2) == 0) { for (int i = top; i <= bottom; i++) { for (int j = left; j <= (left + 1); j++) { if (city.tile(j, i).type == Tile::TileKind::ground) { city.tile(j, i).type = Tile::TileKind::engineering; } } } } else { for (int i = top; i <= bottom; i++) { for (int j = (right - 1); j <= right; j++) { if (city.tile(j, i).type == Tile::TileKind::ground) { city.tile(j, i).type = Tile::TileKind::engineering; } } } } } } } void build_food_supply(const RoomProperties& rp) { for (int i = rp.top; i <= rp.bottom; i++) { for (int j = rp.left; j <= rp.right; j++) { if (city.tile(j, i).type != Tile::TileKind::door) { if ((i == rp.top) || (i == rp.bottom) || (j == rp.left) || (j == rp.right)) { city.tile(j, i).type = Tile::TileKind::wall; } else { //city.tile(j, i).type = Tile::TileKind::foodsupply; if (rand() % 3 == 0) hydroponics::make_hydroponics_table({ &city, j, i }); } } } } hydroponics::make_hydroponics_room({ &city, rp.left + 1, rp.top + 1, rp.width - 2, rp.height - 2 }); } void build_infirmary(const RoomProperties& rp) { for (int i = rp.top; i <= rp.bottom; i++) { for (int j = rp.left; j <= rp.right; j++) { if (city.tile(j, i).type != Tile::TileKind::door) { if ((i == rp.top) || (i == rp.bottom) || (j == rp.left) || (j == rp.right)) { city.tile(j, i).type = Tile::TileKind::wall; } else { city.tile(j, i).type = Tile::TileKind::infirmary; } } } } } // mark anything that is not already a wall or door as floor void build_floor(const RoomProperties& rp) { for (int i = rp.top; i <= rp.bottom; i++) { for (int j = rp.left; j <= rp.right; j++) { if ((city.tile(j, i).type != Tile::TileKind::door) && (city.tile(j, i).type != Tile::TileKind::wall)) { city.tile(j, i).type = Tile::TileKind::ground; } } } } // Determines where the door has to be placed void build_doors(const RoomProperties& rp) { if (rp.doorN) { int i = (rp.width % 2 == 0) ? rp.width / 2 : rp.width / 2 + 1; city.tile(rp.left + i, rp.top).type = Tile::TileKind::door; } if (rp.doorS) { int i = (rp.width % 2 == 0) ? rp.width / 2 : rp.width / 2 + 1; city.tile(rp.left + i, rp.bottom).type = Tile::TileKind::door; } if (rp.doorE) { int i = (rp.height % 2 == 0) ? rp.height / 2 : rp.height / 2 + 1; city.tile(rp.right, rp.top + i).type = Tile::TileKind::door; } if (rp.doorW) { int i = (rp.height % 2 == 0) ? rp.height / 2 : rp.height / 2 + 1; city.tile(rp.left, rp.top + i).type = Tile::TileKind::door; } } // Generates a perimeter wall for the entire city // TODO: this can be optimized to speed up city generation void build_perimeter_wall() { for (int i = props.top; i < props.height; i++) { for (int j = props.left; j < props.width; j++) { if ((i == 0) || (i == props.bottom) || (j == 0) || (j == props.right)) { city.tile(j, i).type = Tile::TileKind::wall; } } } } // While generating rooms the doors are represented by // TileKind::door this method replaces them with TileKind::ground void finalize_doors() { for (int j = props.top; j < props.height; j++) { for (int i = props.left; i < props.width; i++) { if (city.tile(i, j).type == Tile::TileKind::door) { city.tile(i, j).type = Tile::TileKind::ground; } } } } // Finds the rooms in the generated city // TODO: this can be removed since rooms are // procedurally generated we don't have to find them void find_rooms() { for (int j = props.top; j < props.height; j++) { for (int i = props.left; i < props.width; i++) { char ch = city.tile(i, j).type; if ((ch == Tile::TileKind::wall) || (ch == Tile::TileKind::ground)) continue; int kx, ky, w, h; for (kx = i; kx < city.getXSize(); ++kx) { if (city.tile(kx, j).type != ch) break; } for (ky = j; ky < city.getYSize(); ++ky) { for (int x = i; x < kx; ++x) { if (city.tile(x, ky).type != ch) goto finish_loop; } } finish_loop: w = kx - i; h = ky - j; for (int y = j; y < ky; ++y) { for (int x = i; x < kx; ++x) { city.tile(x, y).type = Tile::ground; } } // room's top-left is i,j and dimensions are w x h city.rooms.push_back(make_workroom({ &city, i, j, w, h })->assert_get<Room>()); } } } City& city; CityProperties const& props; CityGenerator& operator=(CityGenerator const&) = delete; }; void randomgen(City& city, CityProperties const& props) { CityGenerator cg(city, props); }
// Copyright 2012 Yandex #ifndef LTR_INTERFACES_PRINTABLE_H_ #define LTR_INTERFACES_PRINTABLE_H_ #include <ostream> #include <string> using std::string; namespace ltr { class Printable { public: virtual string toString() const = 0; virtual ~Printable() {} }; std::ostream& operator<<(std::ostream& stream, const Printable& printable); } #endif // LTR_INTERFACES_PRINTABLE_H_
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace OpenGLES3Renderer { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Abstract OpenGL ES 3 extensions base interface * * @note * - Extensions are only optional, so do always take into account that an extension may not be available */ class IExtensions { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Destructor */ virtual ~IExtensions(); //[-------------------------------------------------------] //[ Public virtual OpenGLES3Renderer::IExtensions methods ] //[-------------------------------------------------------] public: /////////////////////////////////////////////////////////// // Returns whether an extension is supported or not /////////////////////////////////////////////////////////// // EXT virtual bool isGL_EXT_texture_compression_s3tc() const = 0; virtual bool isGL_EXT_texture_compression_dxt1() const = 0; virtual bool isGL_EXT_texture_compression_latc() const = 0; virtual bool isGL_EXT_texture_buffer() const = 0; virtual bool isGL_EXT_draw_elements_base_vertex() const = 0; virtual bool isGL_EXT_base_instance() const = 0; virtual bool isGL_EXT_clip_control() const = 0; // AMD virtual bool isGL_AMD_compressed_3DC_texture() const = 0; // NV virtual bool isGL_NV_fbo_color_attachments() const = 0; // OES virtual bool isGL_OES_element_index_uint() const = 0; virtual bool isGL_OES_packed_depth_stencil() const = 0; virtual bool isGL_OES_depth24() const = 0; virtual bool isGL_OES_depth32() const = 0; // KHR virtual bool isGL_KHR_debug() const = 0; //[-------------------------------------------------------] //[ Protected methods ] //[-------------------------------------------------------] protected: /** * @brief * Default constructor */ IExtensions(); explicit IExtensions(const IExtensions& source) = delete; IExtensions& operator =(const IExtensions& source) = delete; }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // OpenGLES3Renderer //[-------------------------------------------------------] //[ Implementation includes ] //[-------------------------------------------------------] #include "OpenGLES3Renderer/ExtensionsRuntimeLinking.h" // Required in here because we define the OpenGL ES 3 extension functions for dynamic runtime linking
#ifndef LIBLAS_CHIPPER_H #define LIBLAS_CHIPPER_H #include <liblas/liblas.hpp> #include <liblas/export.hpp> #include <liblas/detail/opt_allocator.hpp> #include <vector> namespace liblas { namespace chipper { enum Direction { DIR_X, DIR_Y, DIR_NONE }; class LAS_DLL PtRef { public: double m_pos; uint32_t m_ptindex; uint32_t m_oindex; bool operator < (const PtRef& pt) const { return m_pos < pt.m_pos; } }; typedef std::vector<PtRef, detail::opt_allocator<PtRef> > PtRefVec; struct LAS_DLL RefList { public: PtRefVec *m_vec_p; Direction m_dir; RefList(Direction dir = DIR_NONE) : m_vec_p(NULL), m_dir(dir) {} ~RefList() { delete m_vec_p; } PtRefVec::size_type size() const { return m_vec_p->size(); } void reserve(PtRefVec::size_type n) { m_vec_p->reserve(n); } void resize(PtRefVec::size_type n) { m_vec_p->resize(n); } void push_back(const PtRef& ref) { m_vec_p->push_back(ref); } PtRefVec::iterator begin() { return m_vec_p->begin(); } PtRefVec::iterator end() { return m_vec_p->end(); } PtRef& operator[](uint32_t pos) { return (*m_vec_p)[pos]; } std::string Dir() { if (m_dir == DIR_X) return "X"; else if (m_dir == DIR_Y) return "Y"; else return "NONE"; } void SortByOIndex(uint32_t left, uint32_t center, uint32_t right); void SetAllocator(detail::opt_allocator<PtRef> *alloc_p ) { m_vec_p = new PtRefVec( *alloc_p ); } }; class LAS_DLL Chipper; class LAS_DLL Block { friend class Chipper; private: RefList *m_list_p; uint32_t m_left; uint32_t m_right; liblas::Bounds<double> m_bounds; public: std::vector<uint32_t> GetIDs() const; Bounds<double> const& GetBounds() const {return m_bounds;} void SetBounds(liblas::Bounds<double> const& bounds) {m_bounds = bounds;} }; // Options that can be used to modify the behavior of the chipper. class LAS_DLL Options { public: Options() : m_threshold( 1000 ), m_use_sort( false ), m_use_maps( false ) {} // Maximum number of pointer per output block. uint32_t m_threshold; // If true, use sorting instead of copying to reduce memory. bool m_use_sort; // If true, use memory mapped files instead of main memory bool m_use_maps; // Map file to use if m_use_maps is true. std::string m_map_file; }; class LAS_DLL Chipper { public: Chipper(Reader *reader, Options *options ); Chipper(Reader *reader, uint32_t max_partition_size) : m_reader(reader), m_xvec(DIR_X), m_yvec(DIR_Y), m_spare(DIR_NONE) { m_options.m_threshold = max_partition_size; } void Chip(); std::vector<Block>::size_type GetBlockCount() { return m_blocks.size(); } const Block& GetBlock(std::vector<Block>::size_type i) { return m_blocks[i]; } private: int Allocate(); int Load(); void Partition(uint32_t size); void Split(RefList& xvec, RefList& yvec, RefList& spare); void DecideSplit(RefList& v1, RefList& v2, RefList& spare, uint32_t left, uint32_t right); void RearrangeNarrow(RefList& wide, RefList& narrow, RefList& spare, uint32_t left, uint32_t center, uint32_t right); void Split(RefList& wide, RefList& narrow, RefList& spare, uint32_t left, uint32_t right); void FinalSplit(RefList& wide, RefList& narrow, uint32_t pleft, uint32_t pcenter); void Emit(RefList& wide, uint32_t widemin, uint32_t widemax, RefList& narrow, uint32_t narrowmin, uint32_t narrowmax); Reader *m_reader; std::vector<Block> m_blocks; std::vector<uint32_t> m_partitions; // Note, order is important here, as the allocator must be destroyed // after the RefLists. boost::shared_ptr<detail::opt_allocator<PtRef> > m_allocator; RefList m_xvec; RefList m_yvec; RefList m_spare; Options m_options; }; } // namespace chipper } // namespace liblas #endif
#include <iostream> #include <string> #include <memory> #include <algorithm> #include <vector> #include <functional> #include "stdafx.h" #include "..\Dependencies\jni.h" #include "ConfigReader.h" using namespace std; #pragma region "Interop class" namespace JNIBridge { namespace Core { class JNIBRIDGE_API Interop { private: /// <summary> /// Runs the java env checks. /// </summary> void RunJavaEnvChecks(); /// <summary> /// Gets the jar files. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <param name="extension">The extension.</param> /// <returns></returns> std::vector<std::wstring> GetJarFiles(std::wstring directoryPath, std::wstring extension); protected: /// <summary> /// The m java vm /// </summary> JavaVM* m_JavaVm; /// <summary> /// Checks for java env variables. /// </summary> /// <returns></returns> bool CheckForJavaEnvVariables(); /// <summary> /// The m configuration reader /// </summary> mutable JNIBridge::Config::ConfigReader m_configReader; /// <summary> /// The m jar files /// </summary> mutable std::vector<std::wstring> m_jarFiles; /// <summary> /// Checks the required jre sym links. /// </summary> /// <param name="deleteAndCreateIfExist">if set to <c>true</c> [delete and create if exist].</param> /// <returns></returns> bool CheckRequiredJreSymLinks(bool deleteAndCreateIfExist); /// <summary> /// The m java home /// </summary> std::wstring m_javaHome; /// <summary> /// The m jre home /// </summary> std::wstring m_jreHome; public: /// <summary> /// Initializes a new instance of the <see cref="Interop" /> class. /// </summary> Interop(); /// <summary> /// Finalizes an instance of the <see cref="Interop" /> class. /// </summary> ~Interop(); /// <summary> /// Javas the env get. /// </summary> /// <returns></returns> JNIEnv* JavaEnv_get() const; /// <summary> /// Javas the vm get. /// </summary> /// <returns></returns> JavaVM* JavaVM_get() const; /// <summary> /// Jnis the version get. /// </summary> /// <returns></returns> jint JniVersion_get() const; /// <summary> /// Initializes the JVM. /// </summary> /// <param name="configFile">The configuration file.</param> /// <returns></returns> bool InitializeJvm(const char* configFile); /// <summary> /// Configurations the get. /// </summary> /// <returns></returns> JNIBridge::Config::ConfigReader& Config_get() const; /// <summary> /// Loadeds the jars get. /// </summary> /// <returns></returns> std::vector<std::wstring>& LoadedJars_get() const; /// <summary> /// Javas the home get. /// </summary> /// <returns></returns> std::wstring JavaHome_get() const; /// <summary> /// Jres the home get. /// </summary> /// <returns></returns> std::wstring JreHome_get() const; /// <summary> /// Gets the jni expection details. /// </summary> /// <param name="e">The e.</param> /// <returns></returns> static std::string GetJniExpectionDetails(const jthrowable& e, JNIEnv** env); /// <summary> /// Checks for exceptions in JVM. /// </summary> /// <param name="env">The env.</param> /// <param name="exceptionsThrown">The exceptions thrown.</param> static void CheckForExceptionsInJvm(JNIEnv* env, std::vector<std::string>& exceptionsThrown); /// <summary> /// Prepares the arguments. /// </summary> /// <param name="params">The parameters.</param> /// <param name="paramType">Type of the parameter.</param> /// <param name="args">The arguments.</param> static void PrepareArgs(SAFEARRAY& params, SAFEARRAY& paramType, std::vector<jvalue>& args); }; } } #pragma endregion #pragma region "Exported functions" extern "C" { JNIBRIDGE_API void ForceGC(); JNIBRIDGE_API void ShutdownJvm(); JNIBRIDGE_API HRESULT LoadJVMAndJar(const char* configFile); JNIBRIDGE_API HRESULT AddPath(const char* jarFile, char* result, char* exceptions); JNIBRIDGE_API HRESULT SerializeMethodsInJar(const char* jarFile, const char* xmlPath, char* exceptions); JNIBRIDGE_API HRESULT RunMethodInJar(const char* className, const char* methodName, BOOL isStatic, const char* methodProto, SAFEARRAY params, SAFEARRAY paramType, int arrayLength, const void* returnValue, char* exceptions, char* returnType); } #pragma endregion
#include <iostream> #include <fstream> using namespace std; int WriteToText() { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; } int ReadFromText() { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); } else cout << "Unable to open file"; return 0; } int Binary() { streampos begin,end; ifstream myfile ("example.txt", ios::binary); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; } int main() { cout<<"Please Enter Your Selection"<<endl; cout<<"1: WriteToFile()"<<endl; cout<<"2: ReadFromFile()"<<endl; cout<<"3: Binary() //Read Size of File"<<endl; cout<<"4: Exit"<<endl; cout<<"\nSelection: "; int selection; cin>>selection; switch(selection) { case 1: WriteToText(); break; case 2: ReadFromText() ; break; case 3: Binary(); break; } }
// // Created by Alan de Freitas on 12/04/2018. // #include "parameter_control_EA.h" template<typename problem, typename solution> std::default_random_engine parameter_control_EA<problem, solution>::_generator = std::default_random_engine( std::chrono::system_clock::now().time_since_epoch().count()); template<typename problem, typename solution> parameter_control_EA<problem, solution>::parameter_control_EA(problem &p) : _problem(p), _mutation_strength(1.0 / p.size()), _fitness_sharing_niche_size(0.05 * p.size()) { this->algorithm(algorithm::DEFAULT); if (this->_problem.is_minimization()) { this->_comp = [](individual_ptr &a, individual_ptr &b) { return a->fx < b->fx; }; this->_not_comp = [](individual_ptr &a, individual_ptr &b) { return a->fx > b->fx; }; } else { this->_comp = [](individual_ptr &a, individual_ptr &b) { return a->fx > b->fx; }; this->_not_comp = [](individual_ptr &a, individual_ptr &b) { return a->fx < b->fx; }; } this->_comp_fitness = [](individual_ptr &a, individual_ptr &b) { return a->fitness > b->fitness; }; this->_not_comp_fitness = [](individual_ptr &a, individual_ptr &b) { return a->fitness < b->fitness; }; } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::algorithm(enum algorithm alg){ switch (alg){ case algorithm::DEFAULT : { this->_population_size = 300; this->_number_of_islands = 5; this->_fitness_sharing_niche_size = 3.0; this->_children_proportion = 7.0; this->_crossover_probability = 0.9; this->_mutation_strength = 1/this->_problem.size(); this->_competition_between_parents_and_children = false; this->_elitism_proportion = 0.01; this->_reproduction_scaling_strategy = scaling_strategy::window; this->_reproduction_selection_strategy = selection_strategy::tournament; this->_survival_scaling_strategy = scaling_strategy::window; this->_survival_selection_strategy = selection_strategy::truncate; break; } case algorithm::GA : { this->_population_size = 100; this->_number_of_islands = 1; this->_fitness_sharing_niche_size = 0.0; this->_children_proportion = 1.0; this->_crossover_probability = 0.8; this->_mutation_strength = 1/this->_problem.size(); this->_competition_between_parents_and_children = false; this->_elitism_proportion = 1.0; this->_reproduction_scaling_strategy = scaling_strategy::window; this->_reproduction_selection_strategy = selection_strategy::roulette; this->_survival_scaling_strategy = scaling_strategy::window; this->_survival_selection_strategy = selection_strategy::truncate; break; } case algorithm::EE : { this->_population_size = 40; this->_number_of_islands = 1; this->_fitness_sharing_niche_size = 0.0; this->_children_proportion = 7.0; this->_crossover_probability = 0.1; this->_mutation_strength = 1/this->_problem.size(); this->_competition_between_parents_and_children = false; this->_elitism_proportion = 1.0; this->_reproduction_scaling_strategy = scaling_strategy::window; this->_reproduction_selection_strategy = selection_strategy::uniform; this->_survival_scaling_strategy = scaling_strategy::window; this->_survival_selection_strategy = selection_strategy::truncate; break; } } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::initialize_population() { this->_population.resize(0); this->_population.reserve(this->_population_size); for (int i = this->_population.size(); i < this->_population_size; ++i) { this->_population.emplace_back(std::make_shared<individual>(this->_problem)); } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::run() { initialize_population(); for (int i = 0; i < this->_max_generations; ++i) { evolutionary_cycle(); } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::run(size_t iterations) { initialize_population(); for (int i = 0; i < iterations; ++i) { evolutionary_cycle(); } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::evolutionary_cycle() { display_status(); evaluate(this->_population); scaling(this->_population, this->_reproduction_scaling_strategy); fitness_sharing(this->_population); population_type parents = selection(this->_population, n_of_selection_candidates(), this->_reproduction_selection_strategy); population_type children = reproduction(parents); evaluate(children); const size_t size_of_elite_set = this->size_of_elite_set(); population_type parents_and_children = this->merge(this->_population,children); population_type next_population_candidates = (this->_competition_between_parents_and_children || this->_children_proportion < 1.0) ? parents_and_children : children; scaling(next_population_candidates, this->_survival_scaling_strategy); population_type survivors = selection(next_population_candidates, this->_population_size - size_of_elite_set, this->_survival_selection_strategy); this->_population = insert_elite_set(survivors,parents_and_children,size_of_elite_set); migration_step(); } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::merge(population_type &parents,population_type &children){ population_type result = parents; result.insert(result.end(),children.begin(),children.end()); return result; }; template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::insert_elite_set(population_type& individuals, population_type& elite_source, size_t size_of_elite_set) { std::partial_sort(elite_source.begin(), elite_source.begin() + size_of_elite_set, elite_source.end(), this->_comp_fitness); individuals.insert( individuals.end(), elite_source.begin(), elite_source.begin() + size_of_elite_set ); return individuals; } template<typename problem, typename solution> double parameter_control_EA<problem, solution>::best_fx() { if (!this->_best_solutions.empty()) { return this->_best_solutions[0]->fx; } else { return this->_problem.is_minimization() ? std::numeric_limits<double>::max() : -std::numeric_limits<double>::max(); } } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::individual_ptr parameter_control_EA<problem, solution>::best_solution() { if (!this->_best_solutions.empty()) { return this->_best_solutions[0]; } else { return nullptr; } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::evaluate(population_type &population) { for (individual_ptr &item : population) { item->fx = item->evaluate(this->_problem); this->try_to_update_best(item); } }; template<typename problem, typename solution> size_t parameter_control_EA<problem, solution>::n_of_selection_candidates() { return this->_population_size * this->_parents_per_children * this->_children_proportion; }; template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::selection(population_type &population, size_t n_of_candidates, selection_strategy s) { population_type result; for (int i = 0; i < this->_number_of_islands; ++i) { population_type island = get_island(population, i); population_type island_result; size_t n_of_candidates_per_island = n_of_candidates / this->_number_of_islands; switch (s) { case selection_strategy::uniform: island_result = uniform_selection(island, n_of_candidates_per_island); break; case selection_strategy::truncate: island_result = truncate_selection(island, n_of_candidates_per_island); break; case selection_strategy::tournament: island_result = tournament_selection(island, n_of_candidates_per_island); break; case selection_strategy::roulette: island_result = roulette_selection(island, n_of_candidates_per_island); break; case selection_strategy::sus: island_result = sus_selection(island, n_of_candidates_per_island); break; case selection_strategy::overselection: island_result = overselection_selection(island, n_of_candidates_per_island); break; case selection_strategy::roundrobin_tournament: island_result = roundrobin_selection(island, n_of_candidates_per_island); break; } result.insert(result.end(), island_result.begin(), island_result.end()); } return result; }; template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::reproduction(population_type &parents) { std::uniform_real_distribution<double> r(0.0, 1.0); population_type children; children.reserve(parents.size() / this->_parents_per_children); for (int j = 0; j < parents.size(); j += this->_parents_per_children) { if (r(parameter_control_EA::_generator) < this->_crossover_probability) { children.emplace_back( std::make_shared<individual>( parents[j]->crossover( this->_problem, *parents[j + 1] ) ) ); } else { children.emplace_back(std::make_shared<individual>(*parents[j])); children.back()->mutation(this->_problem, this->_mutation_strength); } } return children; } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::display_status() { std::cout << "Generation #" << ++_current_generation; if (this->_current_generation > 1) { std::cout << " Best_fx: " << this->best_fx() << std::endl; double min_fx = std::numeric_limits<double>::max(); double avg_fx = 0.0; double max_fx = -std::numeric_limits<double>::max(); for (individual_ptr &ind : this->_population) { min_fx = std::min(min_fx, ind->fx); max_fx = std::max(max_fx, ind->fx); avg_fx += ind->fx; } avg_fx /= this->_population.size(); std::cout << "| Min: " << min_fx << " | Avg: " << avg_fx << " | Max: " << max_fx << " | " << ((min_fx == max_fx) ? ("(Population Converged)") : ("")) << std::endl; } else { std::cout << std::endl; } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::scaling(population_type &population, scaling_strategy s) { switch (s) { case scaling_strategy::window: { window_scaling(population); break; } case scaling_strategy::sigma: { sigma_scaling(population); break; } case scaling_strategy::linear_rank: { linear_rank_scaling(population); break; } case scaling_strategy::exponential_rank: { exponential_rank_scaling(population); break; } } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::attribute_fitness_from_rank(parameter_control_EA::population_type &population) { std::sort(population.begin(), population.end(),this->_comp); for (int i = 0; i < population.size(); ++i) { population[i]->fitness = this->_problem.is_minimization() ? population.size() - i : i + 1; } } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::uniform_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { population_type parents(n_of_candidates); std::uniform_int_distribution<size_t> pos_d(0, population.size() - 1); for (individual_ptr &parent : parents) { parent = population[pos_d(parameter_control_EA::_generator)]; } return parents; } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::tournament_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { population_type parents; std::uniform_int_distribution<size_t> pos_d(0, population.size() - 1); for (int i = 0; i < n_of_candidates; ++i) { size_t position = pos_d(parameter_control_EA::_generator); for (int j = 1; j < this->_tournament_size; ++j) { size_t position2 = pos_d(parameter_control_EA::_generator); if (population[position2]->fitness > population[position]->fitness) { position = position2; } } parents.push_back(population[position]); } return parents; } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::roulette_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { population_type parents; parents.reserve(n_of_candidates); std::discrete_distribution<size_t> pos_d(population.size(), 0, population.size() - 1, [&population](size_t pos) { return population[pos]->fitness; }); for (int i = 0; i < n_of_candidates; ++i) { parents.push_back(population[pos_d(parameter_control_EA::_generator)]); } return parents; } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::truncate_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { population_type parents; parents.reserve(n_of_candidates); std::partial_sort(population.begin(), population.begin() + std::min(n_of_candidates, population.size()), population.end(), this->_comp_fitness); std::copy(population.begin(), population.begin() + std::min(n_of_candidates, population.size()), std::back_inserter(parents)); int i = 0; while (parents.size() < n_of_candidates) { parents.push_back(parents[i % population.size()]); i++; } std::shuffle(parents.begin(), parents.end(), parameter_control_EA::_generator); return parents; } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::sus_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { population_type parents; parents.reserve(n_of_candidates); double total_fit = 0.0; for (individual_ptr &ind : population) { total_fit += ind->fitness; } double gap = total_fit / n_of_candidates; std::uniform_real_distribution<double> dist_r(0.0, gap); double r = dist_r(parameter_control_EA::_generator); size_t current_ind = 0; double sum = population[current_ind]->fitness; for (int i = 0; i < n_of_candidates; ++i) { while (r > sum) { ++current_ind; sum += population[current_ind]->fitness; } parents.push_back(population[current_ind]); r += gap; } std::shuffle(parents.begin(), parents.end(), parameter_control_EA::_generator); return parents; } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::overselection_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { population_type parents; parents.reserve(n_of_candidates); std::partial_sort(population.begin(), population.begin() + population.size() * this->_overselection_proportion, population.end(), this->_comp_fitness); std::uniform_int_distribution<size_t> pos_best(0, population.size() * this->_overselection_proportion - 1); for (int i = 0; i < n_of_candidates * 0.8; ++i) { parents.push_back(population[pos_best(parameter_control_EA::_generator)]); } std::uniform_int_distribution<size_t> pos_worst(population.size() * this->_overselection_proportion, population.size() - 1); for (int i = 0; i < n_of_candidates - (n_of_candidates * 0.8); ++i) { parents.push_back(population[pos_worst(parameter_control_EA::_generator)]); } return parents; } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::roundrobin_selection(parameter_control_EA::population_type &population, size_t n_of_candidates) { struct solution_with_score { individual_ptr s; size_t score = 0; }; std::vector<solution_with_score> scores(population.size()); for (int i = 0; i < population.size(); ++i) { scores[i].s = population[i]; } std::uniform_int_distribution<size_t> pos_d(0, scores.size() - 1); for (int i = 0; i < population.size(); ++i) { solution_with_score &player1 = scores[i]; for (int j = 1; j < this->_roundrobin_tournament_size; ++j) { solution_with_score &player2 = scores[pos_d(parameter_control_EA::_generator)]; if (player1.s->fitness > player2.s->fitness) { player1.score++; } else { player2.score++; } } } std::sort(scores.begin(), scores.end(), [](solution_with_score &a, solution_with_score &b) { return a.score > b.score; } ); population_type parents; parents.reserve(n_of_candidates); for (int i = 0; i < std::min(n_of_candidates, population.size()); ++i) { parents.push_back(scores[i].s); } int i = 0; while (parents.size() < n_of_candidates) { parents.push_back(parents[i % population.size()]); i++; } return parents; } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::window_scaling(parameter_control_EA::population_type &population) { for (individual_ptr &ind : population) { ind->fitness = this->_problem.is_minimization() ? -ind->fx : ind->fx; } const auto iter_to_min_fitness = std::min_element(population.begin(), population.end(), this->_not_comp_fitness); double min_fitness = (*iter_to_min_fitness)->fitness; for (individual_ptr &ind : population) { ind->fitness -= min_fitness + 1; } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::sigma_scaling(parameter_control_EA::population_type &population) { for (individual_ptr &ind : population) { ind->fitness = this->_problem.is_minimization() ? -ind->fx : ind->fx; } double avg_fitness = 0.0; for (individual_ptr &ind : population) { avg_fitness += ind->fitness; } double std_fitness = 0.0; for (individual_ptr &ind : population) { std_fitness += pow(ind->fitness - avg_fitness, 2.0); } std_fitness /= population.size() - 1; std_fitness = sqrt(std_fitness); for (individual_ptr &ind : population) { ind->fitness = std::max( this->_sigma_bias + (ind->fitness - avg_fitness) / (this->_sigma_constant * std_fitness), 0.0); } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::linear_rank_scaling(parameter_control_EA::population_type &population) { attribute_fitness_from_rank(population); const double bias = ((2 - _linear_rank_selective_pressure) / population.size()); const double denominator = population.size() * (population.size() - 1); for (individual_ptr &ind : population) { ind->fitness = bias + (2 * ind->fitness * (_linear_rank_selective_pressure - 1)) / denominator; } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::exponential_rank_scaling(parameter_control_EA::population_type &population) { attribute_fitness_from_rank(population); for (individual_ptr &ind : population) { ind->fitness = (1 - exp(-ind->fitness)) / population.size(); } } template<typename problem, typename solution> size_t parameter_control_EA<problem, solution>::size_of_elite_set(){ return size_t(ceil(this->_elitism_proportion * this->_population.size())); }; template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type parameter_control_EA<problem, solution>::get_island(population_type &population, int idx) { population_type island; const size_t island_size = population.size() / this->_number_of_islands; island.insert(island.end(), population.begin() + idx * island_size, population.begin() + (idx + 1) * island_size); return island; } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::try_to_update_best(parameter_control_EA::individual_ptr &candidate) { const bool solution_is_new = std::find_if(this->_best_solutions.begin(), this->_best_solutions.end(), [this, &candidate](individual_ptr &a) { return (a->distance(this->_problem, *candidate, 0.0) == 0.0); }) == this->_best_solutions.end(); if (solution_is_new) { if (this->_best_solutions.size() < this->_number_of_best_solutions) { this->_best_solutions.push_back(candidate); } else { if (this->_comp(candidate, this->_best_solutions.back())) { this->_best_solutions.pop_back(); this->_best_solutions.push_back(candidate); } } std::sort(this->_best_solutions.begin(), this->_best_solutions.end(), this->_comp); } } template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type::iterator parameter_control_EA<problem, solution>::best_solutions_begin() { return this->_best_solutions.begin(); }; template<typename problem, typename solution> typename parameter_control_EA<problem, solution>::population_type::iterator parameter_control_EA<problem, solution>::best_solutions_end() { return this->_best_solutions.end(); } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::migration_step() { if (this->_current_generation % this->_migration_epoch == 0) { for (int i = 0; i < this->_number_of_islands; ++i) { population_type island1 = get_island(this->_population, i); population_type island2; switch (this->_island_structure) { case island_structure::random: { std::uniform_int_distribution<int> island_idx(0, this->_number_of_islands - 1); island2 = get_island(this->_population, island_idx(parameter_control_EA::_generator)); break; } case island_structure::ring: { island2 = get_island(this->_population, (i + 1) % this->_number_of_islands); break; } } population_type individuals_emigrating; switch (this->_island_migration_policy) { case island_migration_policy::random: { std::uniform_int_distribution<int> island_idx(0, island1.size() - 1); for (int j = 0; j < this->_migration_size; ++j) { individuals_emigrating.push_back(island1[island_idx(parameter_control_EA::_generator)]); } break; } case island_migration_policy::best: { std::partial_sort(island1.begin(), island1.begin() + _migration_size, island1.end(), this->_comp); individuals_emigrating.insert(individuals_emigrating.end(),island1.begin(), island1.begin() + _migration_size); break; } case island_migration_policy::fittest_half: { std::partial_sort(island1.begin(), island1.begin() + island1.size() / 2, island1.end(), this->_comp); std::uniform_int_distribution<int> island_idx(0, island1.size() / 2); for (int j = 0; j < this->_migration_size; ++j) { individuals_emigrating.push_back(island1[island_idx(parameter_control_EA::_generator)]); } break; } } population_type individuals_immigrating; switch (this->_island_replacement_policy) { case island_replacement_policy::worst_swap : { std::partial_sort(island2.begin(), island2.begin() + _migration_size, island2.end(),this->_not_comp); individuals_immigrating.insert(individuals_immigrating.end(),island2.begin(), island2.begin() + _migration_size); for (int j = 0; j < this->_migration_size; ++j) { std::swap(*individuals_immigrating[j], *individuals_emigrating[j]); } break; } case island_replacement_policy::worst_overwrite: { std::partial_sort(island2.begin(), island2.begin() + _migration_size, island2.end(), [this](individual_ptr &a, individual_ptr &b) { return !this->_comp(a, b); }); individuals_immigrating.insert(individuals_immigrating.end(),island2.begin(), island2.begin() + _migration_size); for (int j = 0; j < this->_migration_size; ++j) { *individuals_immigrating[j] = *individuals_emigrating[j]; } break; } case island_replacement_policy::random_swap: { std::uniform_int_distribution<int> island_idx(0, island2.size() - 1); for (int j = 0; j < this->_migration_size; ++j) { individuals_immigrating.push_back(island2[island_idx(parameter_control_EA::_generator)]); } for (int j = 0; j < this->_migration_size; ++j) { std::swap(*individuals_immigrating[j], *individuals_emigrating[j]); } break; } case island_replacement_policy::random_overwrite: { std::uniform_int_distribution<int> island_idx(0, island2.size() - 1); for (int j = 0; j < this->_migration_size; ++j) { individuals_immigrating.push_back(island2[island_idx(parameter_control_EA::_generator)]); } for (int j = 0; j < this->_migration_size; ++j) { *individuals_immigrating[j] = *individuals_emigrating[j]; } break; } } } } } template<typename problem, typename solution> void parameter_control_EA<problem, solution>::fitness_sharing(parameter_control_EA::population_type &population) { for (int i = 0; i < population.size(); ++i) { double sum = 0.0; for (int j = 0; j < population.size(); ++j) { const double d = population[i]->distance(this->_problem,*population[j],this->_fitness_sharing_niche_size); const double sh = (d <= this->_fitness_sharing_niche_size) ? (1 - d/this->_fitness_sharing_niche_size) : 0.0; sum += sh; } population[i]->fitness /= sum + 1.0; } } // Setters and getters // Population management template <typename problem, typename solution> size_t parameter_control_EA<problem,solution>::population_size() { return this->_population_size; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::population_size(size_t value){this->_population_size = value;} template <typename problem, typename solution> size_t parameter_control_EA<problem,solution>::number_of_islands() { return this->_number_of_islands; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::number_of_islands(size_t value){this->_number_of_islands = value;} template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::island_structure parameter_control_EA<problem,solution>::island_structure() { return this->_island_structure; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::island_structure(enum island_structure value){this->_island_structure = value;} template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::island_migration_policy parameter_control_EA<problem,solution>::island_migration_policy() { return this->_island_migration_policy; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::island_migration_policy(enum island_migration_policy value){ this->_island_migration_policy = value; } template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::island_replacement_policy parameter_control_EA<problem,solution>::island_replacement_policy() { return this->_island_replacement_policy; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::island_replacement_policy(enum island_replacement_policy value){ this->_island_replacement_policy = value; } template <typename problem, typename solution> size_t parameter_control_EA<problem,solution>::migration_epoch() { return this->_migration_epoch; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::migration_epoch(size_t value){this->_migration_epoch = value;} template <typename problem, typename solution> size_t parameter_control_EA<problem,solution>::migration_size() { return this->_migration_size; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::migration_size(size_t value){this->_migration_size = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::fitness_sharing_niche_size() { return this->_fitness_sharing_niche_size; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::fitness_sharing_niche_size(double value){this->_fitness_sharing_niche_size = value;} // Stopping criteria template <typename problem, typename solution> size_t parameter_control_EA<problem,solution>::max_generations() { return this->_max_generations; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::max_generations(size_t value){this->_max_generations = value;} // Reproduction template <typename problem, typename solution> double parameter_control_EA<problem,solution>::children_proportion() { return this->_children_proportion; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::children_proportion(double value){this->_children_proportion = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::crossover_probability() { return this->_crossover_probability; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::crossover_probability(double value){this->_crossover_probability = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::mutation_strength() { return this->_mutation_strength; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::mutation_strength(double value){this->_mutation_strength = value;} // Selection template <typename problem, typename solution> bool parameter_control_EA<problem,solution>::competition_between_parents_and_children() { return this->_competition_between_parents_and_children; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::competition_between_parents_and_children(bool value){this->_competition_between_parents_and_children = value;} template <typename problem, typename solution> unsigned int parameter_control_EA<problem,solution>::tournament_size() { return this->_tournament_size; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::tournament_size(unsigned int value){this->_tournament_size = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::overselection_proportion() { return this->_overselection_proportion; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::overselection_proportion(double value){this->_overselection_proportion = value;} template <typename problem, typename solution> size_t parameter_control_EA<problem,solution>::roundrobin_tournament_size() { return this->_roundrobin_tournament_size; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::roundrobin_tournament_size(size_t value){this->_roundrobin_tournament_size = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::elitism_proportion() { return this->_elitism_proportion; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::elitism_proportion(double value){this->_elitism_proportion = value;} // scaling template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::scaling_strategy parameter_control_EA<problem,solution>::reproduction_scaling_strategy() { return this->_reproduction_scaling_strategy; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::reproduction_scaling_strategy(enum scaling_strategy value) { this->_reproduction_scaling_strategy = value; } template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::selection_strategy parameter_control_EA<problem,solution>::reproduction_selection_strategy() { return this->_reproduction_selection_strategy; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::reproduction_selection_strategy(enum selection_strategy value) { this->_reproduction_selection_strategy = value; } template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::scaling_strategy parameter_control_EA<problem,solution>::survival_scaling_strategy() { return this->_survival_scaling_strategy; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::survival_scaling_strategy(enum scaling_strategy value) { this->_survival_scaling_strategy = value; } template <typename problem, typename solution> enum parameter_control_EA<problem,solution>::selection_strategy parameter_control_EA<problem,solution>::survival_selection_strategy() { return this->_survival_selection_strategy; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::survival_selection_strategy(enum selection_strategy value) { this->_survival_selection_strategy = value; } template <typename problem, typename solution> double parameter_control_EA<problem,solution>::sigma_bias() { return this->_sigma_bias; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::sigma_bias(double value){this->_sigma_bias = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::sigma_constant() { return this->_sigma_constant; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::sigma_constant(double value){this->_sigma_constant = value;} template <typename problem, typename solution> double parameter_control_EA<problem,solution>::linear_rank_selective_pressure() { return this->_linear_rank_selective_pressure; } template <typename problem, typename solution> void parameter_control_EA<problem,solution>::linear_rank_selective_pressure(double value){this->_linear_rank_selective_pressure = value;}
#include<iostream> //time complexity for array rotation using temp O(n) //auxillary space O(d) using namespace std; int main(){ int n,arr[100],temp[100],d; cout<<"Enter the size of the array"<<endl; cin>>n; cout<<"Enter the array elements"<<endl; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<"Enter the number of rotations"<<endl; cin>>d; cout<<"\nStoring in temp array"<<endl; for(int i=0;i<d;i++){ temp[i]=arr[i]; cout<<temp[i]<<" "; } cout<<"\nShifting the rest of the array"<<endl; for(int i=0;i<n;i++){ if(i==(n-d)){ break; } arr[i]=arr[d+i]; cout<<arr[i]<<" "; } cout<<"\nStoring elements from temp"<<endl; for(int i=0;i<d;i++){ arr[n-d+i]=temp[i]; cout<<arr[n-d+i]<<" "; } cout<<endl; for(int i=0;i<n;i++){ cout<<arr[i]<<endl; } return 0; }
/**************************************************************** File Name: contree.C Author: Tian Zhang, CS Dept., Univ. of Wisconsin-Madison, 1995 Copyright(c) 1995 by Tian Zhang All Rights Reserved Permission to use, copy and modify this software must be granted by the author and provided that the above copyright notice appear in all relevant copies and that both that copyright notice and this permission notice appear in all relevant supporting documentations. Comments and additions may be sent the author at zhang@cs.wisc.edu. ******************************************************************/ #include "global.h" #include "util.h" #include "vector.h" #include "rectangle.h" #include "cfentry.h" #include "cutil.h" #include "status.h" #include "cftree.h" #include "contree.h" #include "components.h" ConNode::ConNode(int size, Stat* Stats) { actsize=size; entry=new Entry[size]; child=new ConNode*[size]; for (int i=0; i<size; i++) { entry[i].Init(Stats->Dimension); child[i]=NULL; } } ConNode::~ConNode() { delete [] entry; delete [] child; } void ConNode::Free() { for (int i=0; i<actsize; i++) if (child[i]!=NULL) child[i]->Free(); delete [] entry; delete [] child; } int ConNode::N() const { int tmp = 0; for (int i=0; i<actsize; i++) tmp+=entry[i].n; return tmp; } void ConNode::SX(Vector& tmpsx) const { tmpsx.Reset(); for (int i=0; i<actsize; i++) tmpsx+=entry[i].sx; } double ConNode::SXX() const { double tmp=0; for (int i=0; i<actsize; i++) tmp+=entry[i].sxx; return tmp; } void ConNode::CF(Entry& tmpcf) const { tmpcf.Reset(); for (int i=0; i<actsize; i++) tmpcf+=entry[i]; } double ConNode::Radius() const { Entry tmpent; tmpent.Init(entry[0].sx.dim); this->CF(tmpent); return tmpent.Radius(); } double ConNode::Diameter() const { Entry tmpent; tmpent.Init(entry[0].sx.dim); this->CF(tmpent); return tmpent.Diameter(); } double ConNode::Fitness(short ftype) const { Entry tmpent; tmpent.Init(entry[0].sx.dim); this->CF(tmpent); return tmpent.Fitness(ftype); } #ifdef RECTANGLE void ConNode::Rect(Rectangle& tmprect) const { tmprect.Reset(); for (int i=0; i<actsize; i++) tmprect+=entry[i].rect; } #endif RECTANGLE int ConNode::Size() const { int size=1; if (child[0]==NULL) return size; else { for (int i=0; i<actsize; i++) size+=child[i]->Size(); return size; } } int ConNode::Depth() const { if (child[0]==NULL) return 1; else return 1+child[0]->Depth(); } int ConNode::LeafNum() const { int num=0; if (child[0]==NULL) return 1; else { for (int i=0; i<actsize; i++) num+=child[i]->LeafNum(); return num; } } int ConNode::NonleafNum() const { int num=1; if (child[0]==NULL) return 0; else { for (int i=0; i<actsize; i++) num+=child[i]->NonleafNum(); return num; } } int ConNode::NumLeafEntry() const { int num=0; if (child[0]==NULL) return actsize; else { for (int i=0; i<actsize; i++) num+=child[i]->NumLeafEntry(); return num; } } int ConNode::NumNonleafEntry() const { int num=actsize; if (child[0]==NULL) return 0; else { for (int i=0; i<actsize; i++) num+=child[i]->NumNonleafEntry(); return num; } } int ConNode::NumEntry() const { int num=actsize; if (child[0]==NULL) return actsize; else { for (int i=0; i<actsize; i++) num+=child[i]->NumEntry(); return num; } } void ConNode::Print_Tree(short ind, std::ostream &fo) const { int i; if (child[0]==NULL) { // leaf for (i=0; i<actsize; i++) { indent(ind,fo); fo<<entry[i]<< std::endl; } } else { // nonleaf for (i=0; i<actsize; i++) { indent(ind,fo); fo<<entry[i]<<std::endl; child[i]->Print_Tree(ind+5,fo); } } } void ConNode::Print_Tree(short ind, std::ofstream &fo) const { int i; if (child[0]==NULL) { // leaf for (i=0; i<actsize; i++) { indent(ind,fo); fo<<entry[i]<<std::endl; } } else { // nonleaf for (i=0; i<actsize; i++) { indent(ind,fo); fo<<entry[i]<<std::endl; child[i]->Print_Tree(ind+5,fo); } } } void ConNode::Print_Summary(std::ostream &fo) const { Entry tmpent; tmpent.Init(entry[0].sx.dim); CF(tmpent); fo<<"Root CF\t"<<tmpent<<std::endl; fo<<"FootPrint\t"<<sqrt(tmpent.Radius())<<"\t"<<sqrt(tmpent.Diameter())<<std::endl; #ifdef RECTANGLE Rectangle tmprect; tmprect.Init(entry[0].sx.dim); Rect(tmprect); fo<<"Root Rectangle\t"<<tmprect<<std::endl; #endif RECTANGLE fo<<"Leaf Nodes\t"<<LeafNum()<<std::endl; fo<<"Nonleaf Nodes\t"<<NonleafNum()<<std::endl; fo<<"Tree Size\t"<<Size()<<std::endl; fo<<"Tree Depth\t"<<Depth()<<std::endl; fo<<"Leaf Entries\t"<<NumLeafEntry()<<std::endl; fo<<"Nonleaf Entries\t"<<NumNonleafEntry()<<std::endl; fo<<"Entries\t"<<NumEntry()<<std::endl; } void ConNode::Print_Summary(std::ofstream &fo) const { Entry tmpent; tmpent.Init(entry[0].sx.dim); CF(tmpent); fo<<"Root CF\t"<<tmpent<<std::endl; fo<<"FootPrint\t"<<sqrt(tmpent.Radius())<<"\t"<<sqrt(tmpent.Diameter())<<std::endl; #ifdef RECTANGLE Rectangle tmprect; tmprect.Init(entry[0].sx.dim); Rect(tmprect); fo<<"Root Rectangle\t"<<tmprect<<std::endl; #endif RECTANGLE fo<<"Leaf Nodes\t"<<LeafNum()<<std::endl; fo<<"Nonleaf Nodes\t"<<NonleafNum()<<std::endl; fo<<"Tree Size\t"<<Size()<<std::endl; fo<<"Tree Depth\t"<<Depth()<<std::endl; fo<<"Leaf Entries\t"<<NumLeafEntry()<<std::endl; fo<<"Nonleaf Entries\t"<<NumNonleafEntry()<<std::endl; fo<<"Entries\t"<<NumEntry()<<std::endl; } void ConNode::Connect(Stat* Stats) { int i,j; double density; Graph *graph; Components *Compos; Component *Compo; int newsize,allsize; Entry *newentry; ConNode **newchild; if (child[0]==NULL) { // leaf density=Stats->NoiseRate*Stats->NewRoot->N()/Stats->CurrEntryCnt; // connect graph based on density and connectivity graph=new Graph(actsize,entry,Stats->Ftype,Stats->CurFt,density); Compos=graph->Connected_Components(); Compos->ResetComponent(); newsize=allsize=Compos->Size(); for (i=0;i<allsize;i++) { Compo=Compos->CurComponent(); if (Compo->Size()==1 && Compo->TupleCnt(entry)<density) { newsize--; Stats->OutlierEntryCnt++; Stats->OutlierTupleCnt+=Compo->TupleCnt(entry); } } if (newsize<actsize) { newentry=new Entry[newsize]; newchild=new ConNode*[newsize]; for (i=0;i<newsize;i++) { newentry[i].Init(entry[i].sx.dim); newchild[i]=NULL; } Compos->ResetComponent(); j=0; for (i=0;i<allsize;i++) { Compo=Compos->CurComponent(); if (!(Compo->Size()==1&&Compo->TupleCnt(entry)<density)) { Compo->EntryChild(Stats,entry,child, newentry[j],newchild[j]); j++; } } actsize=newsize; delete [] entry; entry=newentry; delete [] child; child=newchild; } } else { // nonleaf graph=new Graph(actsize,entry); Compos=graph->Connected_Components(); newsize=Compos->Size(); if (newsize<actsize) { newentry=new Entry[newsize]; newchild=new ConNode*[newsize]; for (i=0;i<newsize;i++) { newentry[i].Init(entry[i].sx.dim); newchild[i]=NULL; Compo=Compos->CurComponent(); Compo->EntryChild(Stats,entry,child, newentry[i],newchild[i]); } actsize=newsize; delete [] entry; entry=newentry; delete [] child; child=newchild; } for (i=0;i<actsize;i++) child[i]->Connect(Stats); } }
//realwindow.cpp //Handles real windows - creation, etc. //Created by Lewis Hosie //14-07-07 //Dependencies: SDL. #include "realwindow.hpp" #include "entry.hpp" #include "inputpasser.hpp" void realwindow::takesdlevents(inputpasser &theinputpasser){ SDL_Event event; while ( SDL_PollEvent( &event ) ){ switch( event.type ){ case SDL_KEYDOWN: //FIXME: Remove this when menus etc are added if(event.key.keysym.sym==SDLK_ESCAPE) killprogram(); theinputpasser.on_keydown(event.key.keysym); break; case SDL_KEYUP: theinputpasser.on_keyup(event.key.keysym); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: //LButtonDown=SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1); break; case SDL_QUIT: killprogram(); break; default: break; } } } realwindow::realwindow(){ thevars.loadlistfromfile("config/window.ini"); if(SDL_Init(SDL_INIT_VIDEO)!= 0) throw("SDL_Init failed."); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER , 1 ); SDL_WM_SetCaption("Eclipse", NULL); thesurface = SDL_SetVideoMode( thevars.getintvec2("windowsize",640,480).x, thevars.getintvec2("windowsize",640,480).y, thevars.getint("bitdepth",16), SDL_OPENGL | SDL_HWSURFACE | SDL_HWACCEL | (thevars.getbool("fullscreen",false) ? SDL_FULLSCREEN : 0)); } void realwindow::swapbuffers(){ SDL_GL_SwapBuffers(); }
#ifndef CONDITION_H_MYIDENTIFY_1985 #define CONDITION_H_MYIDENTIFY_1985 #include <pthread.h> #include "lock.hpp" namespace core { namespace common { class condition { private: pthread_cond_t cond; public: condition() { pthread_cond_init(&cond,NULL); } ~condition() { pthread_cond_destroy(&cond); } int notify_one() { return pthread_cond_signal(&cond); } int notify_all() { return pthread_cond_broadcast(&cond); } int wait(locker& lk) { return pthread_cond_wait(&cond,&(lk.getmutex())); } int waittime(locker& lk,const struct timespec *abstime) { return pthread_cond_timedwait(&cond,&(lk.getmutex()),abstime); } }; } // namespace common } // namespace core #endif
#pragma once #include "GamePiece.h" #include "Coin.h" #include "Race.h" #include "PowerBadge.h" using namespace std; class GameDeck { private: vector<PowerBadge*>* powers; vector<Race*>* races; vector<OneCoin*> oneCoins; vector<ThreeCoin*> threeCoins; vector<FiveCoin*> fiveCoin; vector<TenCoin*> tenCoin; vector<GamePiece*> gamePiece; vector<Race*>* sixRaces; public: GameDeck(); vector<Race*>* getSixRandomRaces(); OneCoin* getOneCoin(); ThreeCoin* getThreeCoin(); FiveCoin* getFiveCoin(); TenCoin* getTenCoin(); GamePiece* getGamePiece(string type); ~GameDeck(); };
#include <stdio.h> int main(){ int N; int a[80]; scanf("%d",&N); int count; while(1){ count=0; int i; for(int i=0;i<N;i++) scanf("%d",&a[i]); for(i=0;i<N-1;i++){ if((a[i]%2==1 && a[++i]%2==0) || (a[i]%2==0 && a[++i]%2==1)){ count++; } } printf("%d\n",count); } return 0; }
// Calvin Costa // 7/8/19 // Lab 10 Task A // The first function should return the number of minutes from 0:00AM until time. The second function should receive two Time arguments earlier and later and report how many minutes separate the two moments. For example, when passing 10:30AM and 1:40PM: #include <iostream> using namespace std; enum Genre {ACTION, COMEDY, DRAMA, ROMANCE, THRILLER}; class Time { //creates class that allows for two variables public: int h; int m; }; class Movie { public: string title; Genre genre; // only one genre per movie int duration; // in minutes }; class TimeSlot { public: Movie movie; // what movie Time startTime; // when it starts }; int minutesSinceMidnight(Time time); //procreates function int minutesUntil(Time earlier, Time later); //procreates function Time addMinutes(Time time0, int min); void printTime(Time time); void printMovie(Movie mv); void printTimeSlot(TimeSlot ts); TimeSlot scheduleAfter(TimeSlot ts, Movie nextMovie); bool timeOverlap(TimeSlot ts1, TimeSlot ts2); int main(){ Movie one = {"The Dark Knight" , ACTION, 152}; Movie two = {"SuperBad" , COMEDY, 113}; Movie three = {"Taxi Driver" , DRAMA, 112}; Movie four = {"Titanic" , ROMANCE, 194}; Movie five = {"Psycho" , THRILLER, 109}; TimeSlot morning = {one, {9,15}}; TimeSlot daytime = {two, {12,15}}; TimeSlot evening = {three, {16, 45}}; TimeSlot night = {four, {20, 00}}; TimeSlot latenight = {five, {21, 45}}; cout << timeOverlap(night, latenight); return 0; } int minutesSinceMidnight(Time time){ // gives the time in minutes int minutes = 0; minutes = (time.h * 60); minutes += time.m; return minutes; } int minutesUntil(Time earlier, Time later){ // returns time difference in minutes int minutes = minutesSinceMidnight(later) - minutesSinceMidnight(earlier); return minutes; } Time addMinutes(Time time0, int min){ // adds minutes to a time and returns as hour/minutes int newtime; newtime = minutesSinceMidnight(time0) + min; time0.m = (newtime % 60); // remainder is the minutes time0.h = (newtime - time0.m)/60; return time0; } void printTime(Time time) { cout << time.h << ":" << time.m; } void printMovie(Movie mv){ string g; switch (mv.genre) { case ACTION : g = "ACTION"; break; case COMEDY : g = "COMEDY"; break; case DRAMA : g = "DRAMA"; break; case ROMANCE : g = "ROMANCE"; break; case THRILLER : g = "THRILLER"; break; } cout << mv.title << " " << g << " (" << mv.duration << " min)"; } void printTimeSlot(TimeSlot ts){ Time Endtime; printMovie(ts.movie); cout << "[starts at "; printTime(ts.startTime); cout << ", ends by "; Endtime = addMinutes(ts.startTime, ts.movie.duration); printTime(Endtime); cout << " ]\n"; } TimeSlot scheduleAfter(TimeSlot ts, Movie nextMovie){ TimeSlot bs = ts; bs.movie = nextMovie; bs.startTime = addMinutes(ts.startTime, ts.movie.duration); return bs; } bool timeOverlap(TimeSlot ts1, TimeSlot ts2){ if (minutesSinceMidnight(ts1.startTime) == minutesSinceMidnight(ts2.startTime)) { //if start time are equal, overlap is true return true; } if (minutesSinceMidnight(ts1.startTime) < minutesSinceMidnight(ts2.startTime)){ Time Endtime1 = addMinutes(ts1.startTime, ts1.movie.duration); if ( Endtime1.h > ts2.startTime.h) { //if endtime hour is higher than starttime hour, then overlap is true return true; } if (Endtime1.h == ts2.startTime.h) { if (Endtime1.m > ts2.startTime.m) { //if Endtime hour is = to starttime hour but minutes is more return true return true; } } } if (minutesSinceMidnight(ts2.startTime) < minutesSinceMidnight(ts1.startTime)){ Time Endtime2 = addMinutes(ts2.startTime, ts2.movie.duration); if ( Endtime2.h > ts1.startTime.h) { return true; } if (Endtime2.h == ts1.startTime.h) { if (Endtime2.m > ts1.startTime.m) { return true; } } } return false; }
#include <iostream> #include <fstream> #include <cstring> #include <cstdlib> #include <vector> #include <map>; #define limit 10000 using namespace std; typedef long long number; typedef pair<int, int> coord; ifstream fin("input.txt"); number s[limit], p[limit], i, base; vector<vector<char>> camera; map<coord, bool> ship; bool part1 = 1; char dump; coord pos, rotations[4] = { {-1,0}, //^ {0,1}, //> {1,0}, //V {0,-1} //< }; int rotation; coord& operator+=(coord& lhs, int rhs) { lhs.first += rotations[rhs].first; lhs.second += rotations[rhs].second; return lhs; } coord operator+(coord& lhs, int rhs) { return { lhs.first + rotations[rhs].first, lhs.second + rotations[rhs].second }; } int getRotation(int c) { switch (c) { case '^': return 0; case '>': return 1; case 'v': return 2; case '<': return 3; } return -1; } inline bool isScaffold(char c) { switch (c) { case '#': case '^': case '<': case '>': case 'v': return 1; default: return 0; } } //first parameter(excluding the opcode) is 1 number& getval(int parameter) { switch (s[i] / (number)pow(10ll, parameter + 1ll) % 10) { case 2: return s[base + s[i + parameter]]; case 1: return s[i + parameter]; case 0: return s[s[i + parameter]]; } cout << "Argh!"; return s[0]; } bool cycle() { switch (s[i] % 100) { case 1: { getval(3) = getval(1) + getval(2); i += 4; break; } case 2: { getval(3) = getval(1) * getval(2); i += 4; break; } case 3: { fin.get(dump); cout << dump; getval(1) = dump; i += 2; break; } case 4: { int output = getval(1); if (output > 255) { cout << output; } else cout << (char)output; if (part1) { if (output == '\n') { camera.emplace_back(); } else { if (isScaffold(output)) { coord loc = { camera.size() - 1,camera.back().size() }; ship[loc] = 1; if (getRotation(output) >= 0) { rotation = getRotation(output); pos = loc; } } camera.back().push_back(output); } } i += 2; break; } case 5: { if (getval(1) != 0) { i = getval(2); } else { i += 3; } break; } case 6: { if (getval(1) == 0) { i = getval(2); } else { i += 3; } break; } case 7: { getval(3) = getval(1) < getval(2); i += 4; break; } case 8: { getval(3) = getval(1) == getval(2); i += 4; break; } case 9: { base += getval(1); i += 2; break; } case 99: return 0; default: cout << "Oh no!"; } return 1; } int getRight(int rot) { return (rot + 1) % 4; } int getLeft(int rot) { rot--; if (rot == -1) { rot = 3; } return rot; } bool isIntersection(int i, int j) { return isScaffold(camera[i][j]) && isScaffold(camera[i - 1][j]) && isScaffold(camera[i + 1][j]) && isScaffold(camera[i][j - 1]) && isScaffold(camera[i][j + 1]); } int main() { for (i = 0; fin >> s[i]; i++) { fin.get(dump); } i = 0; memcpy(p, s, sizeof(number) * limit); camera.emplace_back(); while (cycle()); while (!camera.back().size()) { camera.pop_back(); } size_t sum = 0, iLim = camera.size() - 1, jLim = camera.front().size() - 1; for (size_t i = 1; i < iLim; i++) { for (size_t j = 1; j < jLim; j++) { if (isIntersection(i, j)) { sum += i * j; } } } cout << sum << "\n\n"; memcpy(s, p, sizeof(number) * limit); s[0] = 2LL; while (true) { for (i = 0; ship[pos + rotation]; i++) { pos += rotation; } if (i) { cout << i << ','; } if (ship[pos + getRight(rotation)]) { cout << "R,"; rotation = getRight(rotation); } else if (ship[pos + getLeft(rotation)]) { cout << "L,"; rotation = getLeft(rotation); } else { break; } } fin.close(); part1 = 0; cout << "\n\nSince this year I've been focused on solving ASAP, this is not automatic." << "\nYou need to find the patterns by yourself(which is faster than me coding an automation)" << "\nand load them into an input2.txt file which is going to be parsed character by character," << "\nincluding new lines. See input2.ex which is made after the example\nPress RETURN when ready..."; cin.get(); fin = ifstream("input2.txt"); i = 0; while (cycle()); }
/* * File: main.cpp * Author: Elijah De Vera * Created on January 21, 2021 * Purpose: MPG problem */ //System Libraries #include <iostream> //Input/Output Library #include <iomanip> using namespace std; //User Libraries //Global Constants, no Global Variables are allowed const float CVLITER = 0.264179f; // constant of liters to gallon //Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc... //Function Prototypes float mpg ( float, float ); //miles per gallon function //Execution Begins Here! int main(int argc, char** argv) { //Set the random number seed //Declare Variables float liter1, miles1, liter2, miles2; string answer; //Initialize or input i.e. set variable values //Map inputs -> outputs do { cout<<"Car 1"<<endl; cout<<"Enter number of liters of gasoline:"<<endl; cout<<"Enter number of miles traveled:"<<endl; cin>>liter1; cin>>miles1; cout<<"miles per gallon: "<<setprecision(2)<<fixed<<mpg(liter1,miles1)<<endl<<endl; cout<<"Car 2"<<endl; cout<<"Enter number of liters of gasoline:"<<endl; cout<<"Enter number of miles traveled:"<<endl; cin>>liter2; cin>>miles2; cout<<"miles per gallon: "<<setprecision(2)<<fixed<<mpg(liter2,miles2)<<endl<<endl; if ( mpg(liter1,miles1) > mpg(liter2,miles2) ) { cout<<"Car 1 is more fuel efficient"<<endl<<endl; } else { cout<<"Car 2 is more fuel efficient"<<endl<<endl; } cout<<"Again:"<<endl; cin>>answer; if (answer=="y") { cout<<endl; } } while ( answer == "y" ); //Exit stage right or left! return 0; } float mpg ( float liter, float miles ) { float gallons, mpg; gallons = liter * CVLITER; mpg = miles/gallons; return mpg; }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <stack> using namespace std; int findMax(int ar[], int n){ stack <int> s; int top,max_area=-1,area = 0; // s.push(0); top = 0; int i; for(i =0;i<n;) { if(s.empty()||ar[s.top()]<=ar[i]){ s.push(i++); } else{ top = s.top(); s.pop(); if(s.empty()){ area = ar[top]*i; } else{ area = ar[top]*(i - s.top()-1); } max_area = max(area, max_area); } } while(!s.empty()){ top = s.top(); s.pop(); if(s.empty()){ area = ar[top]*i; } else{ area = ar[top]*(i - s.top()-1); } max_area = max(area, max_area); } return max_area; } int main(){ int A[3][3] = {{1,1,1},{0,1,1},{1,0,0}}; int n = 3; int max_area = -1; int temp[n]; memset(temp,0,sizeof(temp)); for(int i =0;i<3;i++){ for(int j = 0;j<3;j++){ if(A[i][j]==0){ temp[j] = 0; } else{ temp[j]+=A[i][j]; } } max_area = max(max_area,findMax(temp,3)); } cout<<max_area; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined ENCODINGS_HAVE_TABLE_DRIVEN && (defined ENCODINGS_HAVE_CHINESE || defined ENCODINGS_HAVE_KOREAN) #include "modules/encodings/tablemanager/optablemanager.h" #include "modules/encodings/decoders/iso-2022-cn-decoder.h" #define ISO2022_LF 0x0A /* LF: Line break */ #define ISO2022_SBCS 0x0F /* SI: Switch to ASCII mode */ #define ISO2022_DBCS 0x0E /* SO: Switch to DBCS mode */ #define ISO2022_ESC 0x1B /* ESC: Start escape sequence */ #define ISO2022_SS2 0x4E /* SS2: G2 for next character only */ ISO2022toUTF16Converter::ISO2022toUTF16Converter(enum encoding inputencoding) : #ifdef ENCODINGS_HAVE_CHINESE m_gbk_table(NULL), m_cns_11643_table(NULL), m_gbk_length(0), m_cns_11643_length(0), #endif #ifdef ENCODINGS_HAVE_KOREAN m_ksc_5601_table(NULL), m_ksc_5601_length(0), #endif m_prev_byte(0), m_current_so_charset(NONE), #ifdef ENCODINGS_HAVE_CHINESE m_current_ss2_charset(NONE), #endif m_state(ascii), m_last_known_state(ascii), m_my_encoding(inputencoding) { } OP_STATUS ISO2022toUTF16Converter::Construct() { if (OpStatus::IsError(this->InputConverter::Construct())) return OpStatus::ERR; BOOL success = TRUE; switch (m_my_encoding) { default: #ifdef ENCODINGS_HAVE_CHINESE case ISO2022CN: m_gbk_table = reinterpret_cast<const UINT16 *>(g_table_manager->Get("gbk-table", m_gbk_length)); m_cns_11643_table = reinterpret_cast<const UINT16 *>(g_table_manager->Get("cns11643-table", m_cns_11643_length)); m_gbk_length /= 2; // Adjust from byte count to UINT16 count m_cns_11643_length /= 2; // Size was in bytes, we need it in uni_chars success = success && m_gbk_table && m_cns_11643_table; break; #endif #ifdef ENCODINGS_HAVE_KOREAN case ISO2022KR: m_ksc_5601_table = reinterpret_cast<const UINT16 *>(g_table_manager->Get("ksc5601-table", m_ksc_5601_length)); m_ksc_5601_length /= 2; // Adjust from byte count to UINT16 count success = success && m_ksc_5601_table; break; #endif } return success ? OpStatus::OK : OpStatus::ERR; } ISO2022toUTF16Converter::~ISO2022toUTF16Converter() { if (g_table_manager) { #ifdef ENCODINGS_HAVE_CHINESE g_table_manager->Release(m_gbk_table); g_table_manager->Release(m_cns_11643_table); #endif #ifdef ENCODINGS_HAVE_KOREAN g_table_manager->Release(m_ksc_5601_table); #endif } } BOOL ISO2022toUTF16Converter::identify_charset(char esc1, char esc2) { if (esc1 == ')') { switch (esc2) { #ifdef ENCODINGS_HAVE_CHINESE case 'A': m_current_so_charset = GB2312; break; case 'G': m_current_so_charset = CNS_11643_1; break; #endif #ifdef ENCODINGS_HAVE_KOREAN case 'C': m_current_so_charset = KSC_5601; break; #endif default: return FALSE; } return TRUE; } #ifdef ENCODINGS_HAVE_CHINESE else if (esc1 == '*') { if (esc2 == 'H') { m_current_ss2_charset = CNS_11643_2; return TRUE; } } #endif return FALSE; } enum { NO_VALID_DATA_YET = -1, /**< No valid output character yet */ INVALID_INPUT = -2, /**< Invalid or unrecognized input */ INVALID_INPUT_REDO = -3 /**< Invalid input, try again with new state */ }; int ISO2022toUTF16Converter::Convert(const void *src, int len, void *dest, int maxlen, int *read_ext) { int read = 0, written = 0; const unsigned char *input = reinterpret_cast<const unsigned char *>(src); uni_char *output = reinterpret_cast<uni_char *>(dest); maxlen &= ~1; // Make sure destination size is always even while (read < len && written < maxlen) { long decoded = NO_VALID_DATA_YET; switch (m_state) { case ascii: switch (*input) { case ISO2022_ESC: m_state = esc; break; // <ESC> case ISO2022_SBCS: m_state = ascii; break; // <SI> case ISO2022_DBCS: m_last_known_state = m_state = lead; break; // <SO> default: decoded = *input; break; } break; case esc: switch (*input) { case '$': m_state = escplus1; break; // <ESC>$ #ifdef ENCODINGS_HAVE_CHINESE case ISO2022_SS2: // SS2 if (ISO2022CN == m_my_encoding) { m_state = ss2_lead; break; } #endif default: // Invalid or unrecognized input decoded = INVALID_INPUT_REDO; m_state = ascii; break; } break; case escplus1: switch (*input) { #ifdef ENCODINGS_HAVE_CHINESE case '*': #endif case ')': m_prev_byte = *input; m_state = escplus2; break; default: // Invalid or unrecognized input decoded = INVALID_INPUT_REDO; m_state = ascii; break; } break; case escplus2: if (!identify_charset(m_prev_byte, *input)) { decoded = INVALID_INPUT_REDO; } // Charset switch has been recognized, now return to // previous state m_state = m_last_known_state; break; case lead: // Double-byte mode; lead expected if (*input < 0x20) { // C0 control character. switch (*input) { case ISO2022_ESC: m_state = esc; break; // <ESC> case ISO2022_SBCS: m_last_known_state = m_state = ascii; break; // <SI> case ISO2022_DBCS: m_state = lead; break; // <SO> default: // Anything else is an error. m_last_known_state = m_state = ascii; decoded = *input; HandleInvalidChar(written); break; } } else { m_prev_byte = *input; m_state = trail; } break; case trail: // Decode character decoded = INVALID_INPUT; // start off with invalid state m_state = lead; if (m_prev_byte >= 0x21 && m_prev_byte <= 0x7E && *input >= 0x21 && *input <= 0x7E) { int codepoint; switch (m_current_so_charset) { #ifdef ENCODINGS_HAVE_CHINESE case GB2312: codepoint = (m_prev_byte - 1) * 191 + (*input + 0x40); if (codepoint < m_gbk_length) { decoded = ENCDATA16(m_gbk_table[codepoint]); } break; case CNS_11643_1: codepoint = (m_prev_byte - 0x21) * 94 + (*input - 0x21); if (codepoint < m_cns_11643_length) { decoded = ENCDATA16(m_cns_11643_table[codepoint]); } break; #endif #ifdef ENCODINGS_HAVE_KOREAN case KSC_5601: // The KSC 5601 table contains all the extra codepoints from // the extended EUC-KR table, so we need to index into it a // bit. This is partly borrowed from the EUC-KR decoder. if (m_prev_byte < 0x47) { // In EUC-KR, lead bytes below 0xC7 (0x47 in ISO-2022) // allow more trail bytes than ISO-2022. codepoint = (26 + 26 + 126) * (m_prev_byte - 1) + 26 + 26 + *input - 1; } else { // The rest of the lead bytes only allow the standard // trail bytes. codepoint = (26 + 26 + 126) * (0xC7 - 0x81) + (m_prev_byte - 0x47) * 94 + (*input - 0x21); } if (codepoint >= 0 && codepoint < m_ksc_5601_length) { decoded = ENCDATA16(m_ksc_5601_table[codepoint]); } break; #endif } } else { /* Unknown character where trail byte was expected: * flag a decoding error and switch to ASCII. */ m_state = ascii; switch (*input) { case ISO2022_ESC: // Error condition: Escape sequence when expecting trail byte m_state = esc; break; case ISO2022_DBCS: // Error condition: SO when expecting trail byte m_state = lead; break; } m_last_known_state = ascii; } break; #ifdef ENCODINGS_HAVE_CHINESE case ss2_lead: decoded = INVALID_INPUT; if (*input >= 0x21 && *input <= 0x7E) { m_prev_byte = *input; m_state = ss2_trail; decoded = NO_VALID_DATA_YET; } else { switch (*input) { case ISO2022_LF: // Error condition: Line break in stream. // Output it and switch back to singlebyte mode. m_last_known_state = m_state = ascii; decoded = ISO2022_LF; HandleInvalidChar(written); break; case ISO2022_ESC: // Error condition: Escape sequence when expecting trail byte m_state = esc; break; case ISO2022_SBCS: // Error condition: SI when expecting trail byte m_last_known_state = m_state = ascii; break; case ISO2022_DBCS: // Error condition: SO when expecting trail byte m_state = lead; } } break; #endif #ifdef ENCODINGS_HAVE_CHINESE case ss2_trail: decoded = INVALID_INPUT; // start off with invalid state if (m_prev_byte >= 0x21 && m_prev_byte <= 0x7E && *input >= 0x21 && *input <= 0x7E) { int codepoint; switch (m_current_ss2_charset) { case CNS_11643_2: codepoint = (m_prev_byte - 0x21) * 94 + (*input - 0x21) + 8742; if (codepoint < m_cns_11643_length) { decoded = ENCDATA16(m_cns_11643_table[codepoint]); } } } else { // Invalid character in trail byte. switch (*input) { case ISO2022_ESC: // Error condition: Escape sequence when expecting trail byte m_state = esc; break; case ISO2022_SBCS: // Error condition: SI when expecting trail byte m_last_known_state = m_state = ascii; break; case ISO2022_DBCS: // Error condition: SO when expecting trail byte m_state = lead; break; } } // Return to state before SS2 character m_state = m_last_known_state; break; #endif } // Output if something was decoded switch (decoded) { case INVALID_INPUT: written += HandleInvalidChar(written, &output); // Consume read ++; input ++; break; case INVALID_INPUT_REDO: // Do not consume written += HandleInvalidChar(written, &output); break; default: // Consume and output regular character *(output ++) = static_cast<UINT16>(decoded); written += sizeof (UINT16); /* fall through */ case NO_VALID_DATA_YET: // Consume read ++; input ++; break; } } *read_ext = read; m_num_converted += written / sizeof (uni_char); return written; } const char *ISO2022toUTF16Converter::GetCharacterSet() { switch (m_my_encoding) { default: #ifdef ENCODINGS_HAVE_CHINESE case ISO2022CN: return "iso-2022-cn"; #endif #ifdef ENCODINGS_HAVE_KOREAN case ISO2022KR: return "iso-2022-kr"; #endif } } void ISO2022toUTF16Converter::Reset() { this->InputConverter::Reset(); m_prev_byte = 0; m_current_so_charset = NONE; #ifdef ENCODINGS_HAVE_CHINESE m_current_ss2_charset = NONE; #endif m_last_known_state = m_state = ascii; } #endif // ENCODINGS_HAVE_TABLE_DRIVEN && (ENCODINGS_HAVE_CHINESE || ENCODINGS_HAVE_KOREAN)
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 5555 int n, l, r; char s[N]; int f[N], pr[N]; int main() { freopen("language.in", "r", stdin); freopen("language.out", "w", stdout); cin >> n >> l >> r >> s; memset(f, 127 + 63, sizeof(f)); f[0] = 0; for (int i = 1; i <= n; i++) { int ma = 'a' - 1, mi = 'z' + 1; for (int j = i; j > 0; j--) { if (s[j - 1] > ma) ma = s[j - 1]; if (s[j - 1] < mi) mi = s[j - 1]; if (i - j + 1 >= l && i - j + 1 <= r && f[j - 1] + ma - mi > f[i]) { f[i] = f[j - 1] + ma - mi; pr[i] = j - 1; } } } if (f[n] < 0) { cout << "NO SOLUTION" << endl; } else { cout << f[n] << endl; vector<string> ans; int k = n; while (k > 0) { s[k] = 0; ans.push_back(s + pr[k]); k = pr[k]; } cout << ans.size() << endl; for (int i = ans.size() - 1; i>=0; i--) cout << ans[i] << endl; } return 0; }
// This example code is in the public domain. // I2C slave Nano #include <Wire.h> #include <SPI.h> #include <SD.h> #define I2C_ADDR 4 #define SPEED 1000000 #define SPEED 3200000 #define SD_CS 4 #define BUFSIZE 8 byte buffer[BUFSIZE]; int idx = 0; File dataFile; void setup() { Wire.begin(I2C_ADDR); Wire.setClock(SPEED); Wire.onRequest(requestEvent); Serial.begin(9600); if (!SD.begin(SD_CS)) { Serial.println("Card failed, or not present"); return; } Serial.println("card initialized."); dataFile = SD.open("song.raw"); if (dataFile) Serial.println("Song opened OK"); else Serial.println("Song open fail"); } void loop() { } void requestEvent() { bool ok = dataFile.available(); if (ok) { dataFile.read(buffer, sizeof(buffer)); } else { memset(buffer, 0, sizeof(buffer)); } Wire.write(buffer, sizeof(buffer)); if (!ok) { dataFile.seek(0); // rewind back to start of the file } }
#include "Sort.h" bool compareStrings(const std::string &s1, const std::string &s2) { int maxLen = (s1.length() > s2.length()) ? (int)s2.length() : (int)s1.length(); for (int i = 0; i < maxLen; i++) { if (s1[i] != s2[i]) return (s1[i] < s2[i]); } return s1.length() < s2.length(); } std::string Sort::execute(std::string & text) { std::string temp = ""; std::list<std::string> lines; std::list<std::string>::iterator it = lines.end(); for (unsigned i = 0; i < text.length(); i++) { if (text[i] == '\n') { it = lines.end(); lines.insert(it, temp); temp = ""; } else { temp += text[i]; } } lines.sort(compareStrings); std::string result = *lines.begin(); for (it = ++lines.begin(); it != lines.end(); it++) { result += "\n"; result += *it; } return result; }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMPATIENTDBWRITERMANAGER_HPP_ #define _GDCMIO_DICOMPATIENTDBWRITERMANAGER_HPP_ #include <fwTools/ProgressAdviser.hpp> #include <fwDataIO/writer/GenericObjectWriter.hpp> #include <fwData/PatientDB.hpp> #include <fwData/location/Folder.hpp> #include "gdcmIO/config.hpp" namespace gdcmIO { namespace writer { /** * @brief This class manages patient writing, in DICOM file format. * * @class DicomPatientDBWriterManager * @author IRCAD (Research and Development Team). * @date 2011. */ class DicomPatientDBWriterManager : public ::fwDataIO::writer::GenericObjectWriter< ::fwData::PatientDB >, public ::fwData::location::enableFolder< ::fwDataIO::writer::IObjectWriter >, public ::fwTools::ProgressAdviser { public : fwCoreClassDefinitionsWithFactoryMacro( (DicomPatientDBWriterManager)( ::fwDataIO::writer::GenericObjectWriter< ::fwData::PatientDB >), (()), new DicomPatientDBWriterManager ); /** * @brief Manage writing tools to save all patients. * * It launches DicomGlobalWriterManager for each patient. */ GDCMIO_API void write(); /** * Overriding * @brief Do nothing */ GDCMIO_API std::string extension(); protected : GDCMIO_API DicomPatientDBWriterManager(); GDCMIO_API ~DicomPatientDBWriterManager(); }; } // namespace writer } // namespace gdcmIO #endif // _GDCMIO_DICOMPATIENTDBWRITERMANAGER_HPP_
#include <GL/glfw.h> #include <iostream> #include <cmath> #include <cassert> using namespace std; //feel free to mess with these constants. const GLfloat BALL_RADIUS = 0.07f; const GLfloat MAJOR_AXIS = 0.07f; const GLfloat MINOR_AXIS = 0.36f; const GLuint THING_COLORS[] = { 0xFFFFFFFF, 0x550000FF, 0x55FF0000 }; struct Vtx { GLfloat x, y; GLuint color; }; struct Thing{ GLfloat x, y, vx, vy, minAx, majAx; }; const GLsizei N_VERTICES_BALL = 20; const GLsizei N_VERTICES_BAR = 6; Vtx vertices[(N_VERTICES_BALL+N_VERTICES_BAR)*2]; const GLfloat PIE = 3.14159265f; double conv(double mint){ return (mint/180)*PIE; } //minorAxis == majorAxis if the shape is circle void generatePolygon(GLfloat minorAxis, GLfloat majorAxis, GLfloat angularOffset, GLfloat x, GLfloat y, GLvoid *pointer, GLsizei nVertices, GLuint stride) { assert(nVertices >= 3); GLfloat *vtx = (GLfloat*)pointer; vtx[0] = x; vtx[1] = y; const GLfloat n = nVertices - 2; const GLfloat factor = 2.0f * PIE/n; for ( GLsizei i = 1; i <= n + 1; ++i ) { GLfloat theta = i * factor; GLfloat *vtx = (GLfloat*)(((GLubyte*)pointer) + stride * i); vtx[0] = minorAxis * cos(angularOffset + theta) + x; vtx[1] = majorAxis * sin(angularOffset + theta) + y; } } void drawThings(const Thing &ball, const Thing &p1, const Thing &p2) { generatePolygon(ball.minAx, ball.majAx, 0, ball.x, ball.y, vertices, N_VERTICES_BALL, sizeof(Vtx)); generatePolygon(p1.minAx, p1.majAx, 150.01, p1.x, p1.y, vertices + N_VERTICES_BALL, N_VERTICES_BAR, sizeof(Vtx)); generatePolygon(p2.minAx, p2.majAx, 150.01, p2.x, p2.y, vertices + N_VERTICES_BALL + N_VERTICES_BAR, N_VERTICES_BAR, sizeof(Vtx)); glDrawArrays(GL_TRIANGLE_FAN, 0, N_VERTICES_BALL); glDrawArrays(GL_TRIANGLE_FAN, N_VERTICES_BALL, N_VERTICES_BAR); glDrawArrays(GL_TRIANGLE_FAN, N_VERTICES_BALL+N_VERTICES_BAR, N_VERTICES_BAR); } int main() { if ( !glfwInit() ) { std::cerr << "Unable to initialize OpenGL!\n"; return -1; } if ( !glfwOpenWindow(640,640, //width and height of the screen 8,8,8,8, //Red, Green, Blue and Alpha bits 0,0, //Depth and Stencil bits GLFW_WINDOW)) { std::cerr << "Unable to create OpenGL window.\n"; glfwTerminate(); return -1; } glfwSetWindowTitle("GLFW Simple Example"); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); // Enable vertical sync (on cards that support it) glfwSwapInterval( 1 ); glClearColor(0,0,0,0); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); //sets up the color of the vertices for ( size_t i = 0; i < N_VERTICES_BALL; ++i ) { vertices[i].color = THING_COLORS[0]; } for ( size_t i = N_VERTICES_BALL; i < 2 * N_VERTICES_BALL; ++i ) { vertices[i].color = THING_COLORS[1]; } glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); Thing ball = {-0.05, 0, 1, 1, BALL_RADIUS, BALL_RADIUS}, p1 = {0.93, 0, 0, 0, MAJOR_AXIS, MINOR_AXIS}, p2 = {-0.93, 0, 0, 0, MAJOR_AXIS, MINOR_AXIS}; double t = 0, rad = MAJOR_AXIS*4.5; const double dt = 0.02; do { int width, height; // Get window size (may be different than the requested size) //we do this every frame to accommodate window resizing. glfwGetWindowSize( &width, &height ); glViewport( 0, 0, width, height ); glClear(GL_COLOR_BUFFER_BIT); //Right bar controlled by 'W' and 'S' or UP and DOWN arrow keys /*if(p1.y <= 1.00f && p1.y >= -1.00f){ if(glfwGetKey('W') == GLFW_PRESS || glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS){ p1.y += 0.05f; } else if(glfwGetKey('S') == GLFW_PRESS || glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS){ p1.y -= 0.05f; } } else if(p1.y + rad >= 1.00f){ p1.y = 1.00f - rad; } else if(p1.y - rad <= -1.00f){ p1.y = -1.00f + rad; }*/ int bounds; if(p1.y + rad <= 1.0f && p1.y + rad <= 1.0f ) bounds = 1; else bounds = 0; if( bounds ) { if(glfwGetKey('W') == GLFW_PRESS || glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS){ p1.y += 0.05f; } else if(glfwGetKey('S') == GLFW_PRESS || glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS){ p1.y -= 0.05f; } } else { bounds = 1; } //else //{ // if( p1.y + rad >= 1.00f ) // p1.y = 1.00f - rad; // else if ( p1.y - rad <= -1.00f ) // p1.y = //} //Ball AI here t += dt; ball.x += ball.vx * dt; ball.y += ball.vy * dt; if ( ball.x > 1 - BALL_RADIUS ) { ball.vx *= -1; ball.x = 1 - BALL_RADIUS; } else if ( ball.x < -1 + BALL_RADIUS ) { ball.vx *= -1; ball.x = -1 + BALL_RADIUS; } if ( ball.y > 1 - BALL_RADIUS ) { ball.vy *= -1; ball.y = 1 - BALL_RADIUS; } else if ( ball.y < -1 + BALL_RADIUS ) { ball.vy *= -1; ball.y = -1 + BALL_RADIUS; } //Opponent AI here if(p2.y <= 1.00f && p2.y >= -1.00f){ if(ball.y >= p2.y){ p2.y += 0.02f; } else { p2.y -= 0.02f; } } else if(p2.y + rad >= 1.00f){ p2.y = 1.00f - rad; } else if(p1.y - rad <= -1.00f){ p2.y = -1.00f + rad; } //Bar and ball collisions const float dx = ball.x - p1.x, dy = ball.y - p1.y; const float mag1 = dx * dx + dy * dy; const float minD = ball.majAx + p1.minAx*2; if ( mag1 <= minD * minD ) { const float mag = sqrt(mag1); const float ndx = dx/mag, ndy = dy/mag; ball.x = (minD + 0.00000) * ndx + p1.x; ball.y = (minD + 0.00000) * ndy + p1.y; const float proj = -2 * (ndx * ball.vx + ndy * ball.vy); ball.vx += proj * ndx; ball.vy += proj * ndy; } const float ddx = ball.x - p2.x, ddy = ball.y - p2.y; const float mag2 = ddx * ddx + ddy * ddy; const float minDD = ball.majAx + p2.minAx*2; if ( mag2 <= minDD * minDD ) { const float mag = sqrt(mag2); const float ndx = ddx/mag, ndy = ddy/mag; ball.x = (minDD + 0.00000) * ndx + p2.x; ball.y = (minDD + 0.00000) * ndy + p2.y; const float proj = -2 * (ndx * ball.vx + ndy * ball.vy); ball.vx += proj * ndx; ball.vy += proj * ndy; } glVertexPointer(2, GL_FLOAT, sizeof(Vtx), vertices); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vtx), &(vertices[0].color)); drawThings(ball, p1, p2); //VERY IMPORTANT: displays the buffer to the screen glfwSwapBuffers(); } while ( glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS && glfwGetWindowParam(GLFW_OPENED) ); glfwTerminate(); return 0; }
#pragma once #include "afxcmn.h" #include "afxwin.h" // CModallessDlg 对话框 class CModallessDlg : public CDialog { DECLARE_DYNAMIC(CModallessDlg) public: CModallessDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CModallessDlg(); // 对话框数据 enum { IDD = IDD_MODALLESS_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CWnd* m_pParent; CWnd* m_pModallessDlg; void PostNcDestroy(); CSliderCtrl m_ctlSLRed; CSliderCtrl m_ctlSLGreen; CSliderCtrl m_ctlSLBlue; CSpinButtonCtrl m_ctlSpinRed; CSpinButtonCtrl m_ctlSpinGreen; CSpinButtonCtrl m_ctlSpinBlue; CEdit m_ctlERed; CString m_strRed; CEdit m_ctlEGreen; CString m_strGreen; CString m_strBlue; CEdit m_ctlEBlue; BOOL OnInitDialog(); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); // afx_msg void OnBuddyUpdate(); // afx_msg void OnBuddyupdate(); afx_msg void OnEnUpdateEred(); afx_msg void OnEnUpdateEgreen(); afx_msg void OnEnUpdateEblue(); void OnBuddyUpdate(); int StringToInt(CString* psInt); afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); };
#include <stdio.h> #include <stdlib.h> #include <algorithm> #include <Game/GameUtil.h> #include "Table.h" #include "Logger.h" #include "IProcess.h" #include "Configure.h" #include "AllocSvrConnect.h" #include "CoinConf.h" #include "HallManager.h" #include "Util.h" #include "Protocol.h" #include "GameApp.h" #include "StrFunc.h" #include "RedisLogic.h" //区域倍率 BYTE Multiple[AREA_MAX] = { 0 , MULTIPLE_XIAN_PING , MULTIPLE_PING , MULTIPLE_ZHUANG_PING , MULTIPLE_XIAN , MULTIPLE_ZHUANG }; // 庄赢 ,庄赢庄对,庄赢闲对, 庄赢庄对闲对,闲赢,闲赢闲对, 闲赢庄对,闲赢庄对闲对,平,平庄对,平闲对,平庄对闲对 BYTE AllWinArea[12][AREA_MAX] = { { FALSE , FALSE , FALSE , FALSE , FALSE , TRUE } , // 庄赢 { FALSE , FALSE , FALSE , TRUE , FALSE , TRUE } , // 庄赢庄对 { FALSE , TRUE , FALSE , FALSE , FALSE , TRUE } , // 庄赢闲对 { FALSE , TRUE , FALSE , TRUE , FALSE , TRUE } , // 庄赢庄对闲对 { FALSE , FALSE , FALSE , FALSE , TRUE , FALSE } , // 闲赢 { FALSE , TRUE , FALSE , FALSE , TRUE , FALSE } , // 闲赢闲对 { FALSE , FALSE , FALSE , TRUE , TRUE , FALSE } , // 闲赢庄对 { FALSE , TRUE , FALSE , TRUE , TRUE , FALSE } , // 闲赢庄对闲对 { FALSE , FALSE , TRUE , FALSE , FALSE , FALSE } , // 平 { FALSE , FALSE , TRUE , TRUE , FALSE , FALSE } , // 平庄对 { FALSE , TRUE , TRUE , FALSE , FALSE , FALSE } , // 平闲对 { FALSE , TRUE , TRUE , TRUE , FALSE , FALSE } // 平庄对闲对 }; bool compare_nocase (Player* first,Player* second) { return (first)->m_lMoney > (second)->m_lMoney; } Cfg Table::coincfg; static std::string game_name = "Baccarat"; Table::Table(): m_nStatus(-1), receivePhpPush(false), zhuangDui(0), xianDui(0), m_nZhuangWinRate(458597) , m_nXianWinRate(446247) , m_nPingRate(95156) , m_nZhuangDuiRate(50400) , m_nXianDuiRate(50400) { reloadCfg(); } Table::~Table() { } void Table::init() { timer.init(this); id = Configure::getInstance()->m_nServerId << 16; this->m_nStatus = STATUS_TABLE_IDLE; memset(player_array, 0, sizeof(player_array)); m_nType = Configure::getInstance()->m_nLevel; PlayerList.clear(); BankerList.clear(); memset(m_lTabBetArray, 0, sizeof(m_lTabBetArray)); memset(m_lRealBetArray, 0, sizeof(m_lRealBetArray)); memset(betAreaLimit, 0, sizeof(betAreaLimit)); memset(m_nChipArray, 0, sizeof(m_nChipArray)); m_bHasBet = false; maxwinner = NULL; m_lBankerWinScoreCount = 0; this->startIdleTimer(Configure::getInstance()->idletime); this->setStatusTime(time(NULL)); m_nRecordLast=0; memset(m_GameRecordArrary, 0, sizeof(m_GameRecordArrary)); bankeruid = 0; bankernum = 0; m_nLimitCoin = 0; this->m_nPersonLimitCoin = 100000; bankersid = -1; betVector.clear(); reloadCfg(); m_nDespatchNum = 0; for (int i = 0; i < MAX_SEAT_NUM; ++i) { m_SeatidArray[i] = NULL; } memset(m_cbCardCount, 0, sizeof(m_cbCardCount)); memset(m_cbTableCardArray, 0, sizeof(m_cbTableCardArray)); m_cbBankerPoint = 0; m_cbPlayerPoint = 0; m_cbBankerPair = 0; m_cbPlayerPair = 0; m_historyCount = 0; receivePhpPush = false; } void Table::reset() { memset(m_lTabBetArray, 0, sizeof(m_lTabBetArray)); memset(m_lRealBetArray, 0, sizeof(m_lRealBetArray)); m_bHasBet = false; m_lBankerWinScoreCount = 0; for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player) player->reset(); } betVector.clear(); maxwinner = NULL; Player* banker = NULL; if(bankersid >=0) banker = this->player_array[bankersid]; if(banker) { calculateBetAreaLimit(banker); } m_nDespatchNum = 0; m_cbBankerPoint = 0; m_cbPlayerPoint = 0; m_cbBankerPair = 0; m_cbPlayerPair = 0; memset(m_cbCardCount, 0, sizeof(m_cbCardCount)); memset(m_cbTableCardArray, 0, sizeof(m_cbTableCardArray)); receivePhpPush = false; } void Table::setStartTime(time_t t) { StartTime = t; bool bRet = Server()->HSETi(StrFormatA("%s:%d", game_name.c_str(), Configure::getInstance()->m_nServerId).c_str(), "starttime", t); if (!bRet) { LOGGER(E_LOG_ERROR) << "save time to redis failed!"; } } Player* Table::isUserInTab(int uid) { for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->id == uid) return player; } return NULL; } bool Table::isAllRobot() { for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] && player_array[i]->source != 30 && player_array[i]->m_lBetArray[0] > 0) { return false; } } return true; } Player* Table::getPlayer(int uid) { for(int i = 0; i < GAME_PLAYER; ++i) { Player* player = player_array[i]; if(player && player->id == uid) return player; } return NULL; } void Table::setToPlayerList(Player* player) { if(player == NULL) return ; if (PlayerList.size() <= 0) { PlayerList.push_back(player); return; } list<Player*>::iterator it; it = PlayerList.begin(); while(it != PlayerList.end()) { Player* other = *it; if(other) { if(other->m_lMoney <= player->m_lMoney) { PlayerList.insert(it, player); return ; } } it++; } PlayerList.push_back(player); } void Table::setToBankerList(Player* player) { if(player == NULL) return ; //if (BankerList.size() <= 0) //{ // BankerList.push_back(player); // return; //} //list<Player*>::iterator it; //it = BankerList.begin(); //while(it != BankerList.end()) //{ // Player* other = *it; // if(other) // { // if(other->m_lMoney <= player->m_lMoney) // { // BankerList.insert(it, player); // return ; // } // } // it++; //} BankerList.push_back(player); } void Table::CancleBanker(Player* player) { if(player == NULL) return ; Player* noer = NULL; if(player->isbankerlist) { list<Player*>::iterator it; it = BankerList.begin(); while(it != BankerList.end()) { noer = *it; if(noer->id == player->id) { BankerList.erase(it); break; } it++; } } player->isbankerlist = false; } void Table::HandleBankeList() { list<Player*>::iterator it; it = BankerList.begin(); while(it != BankerList.end()) { Player* other = *it; if(other) { if(other->m_lMoney < m_nBankerlimit) { other->isbankerlist = false; IProcess::NoteBankerLeave(this, other); BankerList.erase(it++); } else it++; } else BankerList.erase(it++); } //上庄列表排序 //BankerList.sort(compare_nocase); } void Table::rotateBanker() { Player* prebanker = NULL; if(this->bankersid >=0) prebanker = this->player_array[this->bankersid]; if(prebanker) { prebanker->isbankerlist = false; prebanker->m_nLastBetTime = time(NULL); } bankersid = -1; bankeruid = 0;//做庄的uid bankernum = 0;//连续做庄的次数 list<Player*>::iterator it; it = BankerList.begin(); //_LOG_DEBUG_("bankersize:%d\n", BankerList.size()); it = BankerList.begin(); while (it != BankerList.end()) { Player* banker = *it; if(banker && prebanker) { if(!banker->isonline) { BankerList.erase(it++); continue; } if(banker->id == prebanker->id) { _LOG_ERROR_("bankerlist id[%d] m_nSeatID[%d] is prebanker id[%d] m_nSeatID[%d] \n", banker->id, banker->m_nSeatID, prebanker->id, prebanker->m_nSeatID); BankerList.erase(it++); continue; } } if(banker) { bankersid = banker->m_nSeatID; bankeruid = banker->id;//做庄的uid bankernum = 0;//连续做庄的次数 setBetLimit(); time_t t; time(&t); char time_str[32]={0}; struct tm* tp= localtime(&t); strftime(time_str,32,"%Y%m%d%H%M%S",tp); char gameId[64] ={0}; //Player* banker = NULL; //if(this->bankersid >=0) // banker = this->player_array[this->bankersid]; sprintf(gameId, "%s|%d|%02d", time_str, banker ? banker->id: 0, this->bankernum + 1); this->setGameID(gameId); BankerList.erase(it++); IProcess::rotateBankerInfo(this, banker, prebanker); if (banker->m_seatid != 0) { this->LeaveSeat(banker->m_seatid); this->NotifyPlayerSeatInfo(); } return; } BankerList.erase(it++); } if(BankerList.size() == 0) { IProcess::rotateBankerInfo(this, NULL, prebanker); return ; } } int Table::playerComming(Player* player) { if(player == NULL) return -1; for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] == NULL) { player_array[i] = player; player->m_nStatus = STATUS_PLAYER_INGAME; setToPlayerList(player); break; } } player->tid = this->id; player->enter(); ++this->m_nCountPlayer; AllocSvrConnect::getInstance()->updateTableUserCount(this); return 0; } void Table::setSeatNULL(Player* player) { for(int i = 0; i < GAME_PLAYER; ++i) { if(player_array[i] == player) player_array[i] = NULL; } list<Player*>::iterator it; it = PlayerList.begin(); while(it != PlayerList.end()) { Player* other = *it; if(other) { if(other->id == player->id) { PlayerList.erase(it); break ; } } it++; } if(player->isbankerlist) { it = BankerList.begin(); while(it != BankerList.end()) { Player* other = *it; if(other) { if(other->id == player->id) { BankerList.erase(it); break ; } } it++; } } } void Table::playerLeave(int uid) { Player* player = this->getPlayer(uid); if(player) { this->playerLeave(player); } } void Table::playerLeave(Player* player) { if(player == NULL) return; //_LOG_WARN_("Player[%d] Leave\n", player->id); ULOGGER(E_LOG_INFO, player->id) << "leave"; this->setSeatNULL(player); if (player->m_seatid != 0) { this->LeaveSeat(player->m_seatid); this->NotifyPlayerSeatInfo(); } player->leave(); player->init(); //当前用户减一 --this->m_nCountPlayer; AllocSvrConnect::getInstance()->updateTableUserCount(this); } int Table::playerBetCoin(Player* player, short bettype, int64_t betmoney) { if(player == NULL) return -3; if(bettype <= 0 || bettype > 5) return -3; if(player->m_lBetArray[bettype] > this->betAreaLimit[bettype]) { _LOG_ERROR_("You[%d] is large limit[%ld] bet type[%d] coin[%ld]\n", player->id, this->betAreaLimit[bettype], bettype, betmoney); return -15; } int64_t total_bet = 0; for (int i = 1; i < BETNUM; i++) { total_bet += player->m_lBetArray[i]; } if ((total_bet + betmoney) > m_nMaxBetNum) { _LOG_ERROR_("You[%d] is large sum limit[%ld] bet type[%d] coin[%ld]\n", player->id, m_nMaxBetNum, bettype, player->m_lBetArray[bettype] + betmoney); return -8; } if(player->m_lMoney < betmoney) { _LOG_ERROR_("You[%d] not Not enough money[%ld] bet type[%d] coin[%ld]\n", player->id, player->m_lMoney, bettype, betmoney); return -13; } player->m_lMoney -= betmoney; player->m_lBetArray[bettype] += betmoney; player->m_lBetArray[0] += betmoney; ULOGGER(E_LOG_INFO, player->id) << "bet array[0] = " << player->m_lBetArray[0]; this->m_lTabBetArray[bettype] += betmoney; this->m_lTabBetArray[0] += betmoney; //if (bettype == AREA_XIAN || bettype == AREA_ZHUANG) //{ player->m_lReturnScore += betmoney; //} player->m_nLastBetTime = time(NULL); if(player->source != E_MSG_SOURCE_ROBOT) { this->m_lRealBetArray[bettype] += betmoney; SaveBetInfoToRedis(player, bettype); m_bHasBet = true; } setBetLimit(); return 0; } void Table::calculateBetAreaLimit(Player* banker) { betAreaLimit[AREA_XIAN_DUI] = (banker->m_lMoney + m_lTabBetArray[AREA_PING] + m_lTabBetArray[AREA_ZHUANG] + m_lTabBetArray[AREA_ZHUANG_DUI] - m_lTabBetArray[AREA_XIAN]) / 11; betAreaLimit[AREA_PING] = (banker->m_lMoney + m_lTabBetArray[AREA_XIAN_DUI] + m_lTabBetArray[AREA_XIAN] + m_lTabBetArray[AREA_ZHUANG] + m_lTabBetArray[AREA_ZHUANG_DUI]) / 9; betAreaLimit[AREA_ZHUANG_DUI] = (banker->m_lMoney + m_lTabBetArray[AREA_PING] + m_lTabBetArray[AREA_XIAN_DUI] + m_lTabBetArray[AREA_XIAN] - m_lTabBetArray[AREA_ZHUANG]) / 11; betAreaLimit[AREA_XIAN] = banker->m_lMoney + m_lTabBetArray[AREA_PING] + m_lTabBetArray[AREA_ZHUANG] + m_lTabBetArray[AREA_ZHUANG_DUI] - m_lTabBetArray[AREA_XIAN_DUI] * 11; betAreaLimit[AREA_ZHUANG] = banker->m_lMoney + m_lTabBetArray[AREA_PING] + m_lTabBetArray[AREA_XIAN] + m_lTabBetArray[AREA_XIAN_DUI] - m_lTabBetArray[AREA_ZHUANG_DUI] * 11; LOGGER(E_LOG_INFO) << "xian dui limit = " << betAreaLimit[AREA_XIAN_DUI] << "he limit = " << betAreaLimit[AREA_PING] << "zhuang dui limit = " << betAreaLimit[AREA_ZHUANG_DUI] << "xian limit = " << betAreaLimit[AREA_XIAN] << "xian dui limit = " << betAreaLimit[AREA_ZHUANG]; } BYTE Table::getWinType(BYTE cbWinArea[AREA_MAX]) { if (cbWinArea[AREA_ZHUANG] == TRUE /*|| cbWinArea[AREA_ZHUANG_DUI] == TRUE*/) { return WIN_TYPE_ZHUANG; } if (cbWinArea[AREA_XIAN] == TRUE /*|| cbWinArea[AREA_XIAN_DUI] == TRUE*/) { return WIN_TYPE_XIAN; } if (cbWinArea[AREA_PING] == TRUE) { return WIN_TYPE_HE; } LOGGER(E_LOG_ERROR) << "win type error!"; return WIN_TYPE_NONE; } void Table::receivePush(int winarea, BYTE zhuangdui, BYTE xiandui) { receivePhpPush = true; winType = winarea; zhuangDui = zhuangdui; xianDui = xiandui; } BYTE find_dui_card(BYTE* cards, size_t count, BYTE card, CGameLogic* logic) { for (size_t i = 0; i < count; i++) { if (logic->GetCardValue(card) == logic->GetCardValue(cards[i])) { return cards[i]; break; } } return 0; } BYTE find_not_dui_card(BYTE* cards, size_t count, BYTE card, CGameLogic* logic) { for (size_t i = 0; i < count; i++) { if (logic->GetCardValue(card) != logic->GetCardValue(cards[i])) { return cards[i]; break; } } return 0; } BYTE find_card(BYTE* cards, size_t count, CGameLogic* logic, int randSeed) { //srand(randSeed); size_t index = rand() % count; return cards[index]; } // pip 点数, card_count 玩家最终手牌数量 void find_card(BYTE* cards, size_t all_count, CGameLogic* logic, BYTE* playerCards, BYTE dui, BYTE& pip, BYTE& card_count, int randSeed) { //抽取第一张 logic->RandCardList(playerCards, 1); //第二张 if (dui == 1) //有对 { playerCards[1] = find_dui_card(cards, all_count, playerCards[0], logic); if (playerCards[1] == 0) //如果实在找不到,直接使用第一张牌,不应该走到这里 { playerCards[1] = playerCards[0]; } } else { playerCards[1] = find_not_dui_card(cards, all_count, playerCards[0], logic); } pip = logic->GetCardListPip(playerCards, 2); card_count = 2; if (pip < 8) //补第三张 { playerCards[2] = find_card(cards, all_count, logic, randSeed); pip = logic->GetCardListPip(playerCards, 3); //重新计算庄点 card_count++; } } void Table::phpRandCard(int randSeed) { srand(randSeed); if (!receivePhpPush) { LOGGER(E_LOG_WARNING) << "dont receive php push!"; return; } static const int limitCount = 1000; BYTE card_array[2][3]; size_t count = 0; BYTE* cards = m_GameLogic.Shuffle(count,rand()); BYTE bankerPip, bankerCount; find_card(cards, count, &m_GameLogic, card_array[0], zhuangDui, bankerPip, bankerCount, rand()); BYTE playerPip, playerCount; find_card(cards, count, &m_GameLogic, card_array[1], xianDui, playerPip, playerCount, rand()); int index = 0; if (winType == WIN_TYPE_HE) //和赢 { while (playerPip != bankerPip) { find_card(cards, count, &m_GameLogic, card_array[1], xianDui, playerPip, playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0], sizeof(m_cbTableCardArray) / sizeof(BYTE)); return; } index++; } } else { if (winType == WIN_TYPE_ZHUANG) //庄赢 { while (bankerPip <= 3) //点数太小,庄重新抽取 { find_card(cards, count, &m_GameLogic, card_array[0], zhuangDui, bankerPip, bankerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; break; } index++; } index = 0; // reset index while (playerPip >= 4) //点数太大,闲重新抽取 { find_card(cards, count, &m_GameLogic, card_array[1], xianDui, playerPip, playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0], sizeof(m_cbTableCardArray) / sizeof(BYTE)); return; } index++; } index = 0; // reset index while (playerPip >= bankerPip) { find_card(cards, count, &m_GameLogic, card_array[1], xianDui, playerPip, playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0], sizeof(m_cbTableCardArray) / sizeof(BYTE)); return; } index++; } } else //闲赢 { while (playerPip <= 3) //点数太小,闲重新抽取 { find_card(cards, count, &m_GameLogic, card_array[1], xianDui, playerPip, playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0], sizeof(m_cbTableCardArray) / sizeof(BYTE)); break; } index++; } index = 0; // reset index while (bankerPip >= 4) //点数太大,庄重新抽取 { find_card(cards, count, &m_GameLogic, card_array[0], zhuangDui, bankerPip, bankerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0], sizeof(m_cbTableCardArray) / sizeof(BYTE)); return; } index++; } index = 0; // reset index while (bankerPip >= playerPip) { find_card(cards, count, &m_GameLogic, card_array[1], xianDui, playerPip, playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0], sizeof(m_cbTableCardArray) / sizeof(BYTE)); return; } index++; } } } CopyMemory(m_cbTableCardArray[INDEX_BANKER], card_array[0], sizeof(card_array[0])); CopyMemory(m_cbTableCardArray[INDEX_PLAYER], card_array[1], sizeof(card_array[1])); } bool Table::hasSameCards(BYTE cards1[], BYTE count1, BYTE cards2[], BYTE count2) { // 庄闲的前两张牌不能牌面重复 if ((cards1[1] == cards2[1] && cards1[2] == cards2[2]) || (cards1[1] == cards2[2] && cards1[2] == cards2[1])) { return true; } return false; } BYTE Table::RandCardByWinType(int randSeed) { srand(randSeed); int32_t win_rate = rand() % 1000000; _LOG_ERROR_("the rand win_rate is :%d", win_rate); BYTE type = 0; if (win_rate < m_nZhuangWinRate ) { type = WIN_TYPE_ZHUANG; } else if (win_rate < m_nZhuangWinRate + m_nXianWinRate) { type = WIN_TYPE_XIAN; } else { type = WIN_TYPE_HE; } int32_t bank_dui_rate = rand() % 1000000; BYTE bank_dui = bank_dui_rate < m_nZhuangDuiRate? 1 : 0; _LOG_ERROR_("the rand bank_dui_rate is :%d", bank_dui_rate); int32_t xian_dui_rate = rand() % 1000000; BYTE xian_dui = xian_dui_rate < m_nXianDuiRate ? 1 : 0; _LOG_ERROR_("the rand xian_dui_rate is :%d", xian_dui_rate); static const int limitCount = 1000; BYTE card_array[2][3]; size_t count = 0; BYTE* cards = m_GameLogic.Shuffle(count, rand()); BYTE bankerPip , bankerCount; find_card(cards , count , &m_GameLogic , card_array[0] , bank_dui , bankerPip , bankerCount, rand()); BYTE playerPip , playerCount; find_card(cards , count , &m_GameLogic , card_array[1] , xian_dui , playerPip , playerCount, rand()); int index = 0; if (type == WIN_TYPE_HE) //和赢 { while (playerPip != bankerPip || hasSameCards(card_array[0], bankerCount, card_array[1], playerCount)) { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } } else { if (type == WIN_TYPE_ZHUANG) //庄赢 { while (bankerPip <= 3) //点数太小,庄重新抽取 { find_card(cards , count , &m_GameLogic , card_array[0] , zhuangDui , bankerPip , bankerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; break; } index++; } index = 0; // reset index while (playerPip >= 4) //点数太大,闲重新抽取 { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } index = 0; // reset index while (playerPip >= bankerPip || hasSameCards(card_array[0], bankerCount, card_array[1], playerCount)) { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } } else //闲赢 { while (playerPip <= 3) //点数太小,闲重新抽取 { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); break; } index++; } index = 0; // reset index while (bankerPip >= 4) //点数太大,庄重新抽取 { find_card(cards , count , &m_GameLogic , card_array[0] , zhuangDui , bankerPip , bankerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } index = 0; // reset index while (bankerPip >= playerPip || hasSameCards(card_array[0], bankerCount, card_array[1], playerCount)) { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } } } CopyMemory(m_cbTableCardArray[INDEX_BANKER] , card_array[0] , sizeof(card_array[0])); CopyMemory(m_cbTableCardArray[INDEX_PLAYER] , card_array[1] , sizeof(card_array[1])); return type; } BYTE Table::RandCardByAssignedType(int randSeed, BYTE type) { srand(randSeed); _LOG_ERROR_("the assigned type is :%d" , type); int32_t bank_dui_rate = rand() % 1000000; BYTE bank_dui = bank_dui_rate < m_nZhuangDuiRate ? 1 : 0; _LOG_ERROR_("the rand bank_dui_rate is :%d" , bank_dui_rate); int32_t xian_dui_rate = rand() % 1000000; BYTE xian_dui = xian_dui_rate < m_nXianDuiRate ? 1 : 0; _LOG_ERROR_("the rand xian_dui_rate is :%d" , xian_dui_rate); static const int limitCount = 1000; BYTE card_array[2][3]; size_t count = 0; BYTE* cards = m_GameLogic.Shuffle(count, rand()); BYTE bankerPip , bankerCount; find_card(cards , count , &m_GameLogic , card_array[0] , bank_dui , bankerPip , bankerCount, rand()); BYTE playerPip , playerCount; find_card(cards , count , &m_GameLogic , card_array[1] , xian_dui , playerPip , playerCount, rand()); int index = 0; if (type == WIN_TYPE_HE) //和赢 { while (playerPip != bankerPip && hasSameCards(card_array[0], bankerCount, card_array[1], playerCount)) { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } } else { if (type == WIN_TYPE_ZHUANG) //庄赢 { while (bankerPip <= 3) //点数太小,庄重新抽取 { find_card(cards , count , &m_GameLogic , card_array[0] , zhuangDui , bankerPip , bankerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; break; } index++; } index = 0; // reset index while (playerPip >= 4) //点数太大,闲重新抽取 { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } index = 0; // reset index while (playerPip >= bankerPip && hasSameCards(card_array[0], bankerCount, card_array[1], playerCount)) { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } } else //闲赢 { while (playerPip <= 3) //点数太小,闲重新抽取 { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); break; } index++; } index = 0; // reset index while (bankerPip >= 4) //点数太大,庄重新抽取 { find_card(cards , count , &m_GameLogic , card_array[0] , zhuangDui , bankerPip , bankerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } index = 0; // reset index while (bankerPip >= playerPip && hasSameCards(card_array[0], bankerCount, card_array[1], playerCount)) { find_card(cards , count , &m_GameLogic , card_array[1] , xianDui , playerPip , playerCount, rand()); if (index >= limitCount) { LOGGER(E_LOG_WARNING) << "rand special card failed, user normal rand now"; m_GameLogic.RandCardList(m_cbTableCardArray[0] , sizeof(m_cbTableCardArray) / sizeof(BYTE)); return WIN_TYPE_NONE; } index++; } } } CopyMemory(m_cbTableCardArray[INDEX_BANKER] , card_array[0] , sizeof(card_array[0])); CopyMemory(m_cbTableCardArray[INDEX_PLAYER] , card_array[1] , sizeof(card_array[1])); return type; } void Table::SaveBetInfoToRedis(Player * player, int bettype) { bool bRet = Server()->HSETi(StrFormatA("%s:%d:%d", game_name.c_str(), Configure::getInstance()->m_nServerId, bettype).c_str(), StrFormatA("%d", player->id).c_str(), player->m_lBetArray[bettype]); if (!bRet) { LOGGER(E_LOG_ERROR) << "save to redis failed!bettype = " << bettype << " betmoney = " << player->m_lBetArray[bettype]; } } void Table::ClearBetInfo() { for (int i = 1; i < BETNUM; i++) { bool bRet = Server()->DEL(StrFormatA("%s:%d:%d", game_name.c_str(), Configure::getInstance()->m_nServerId, i).c_str()); if (!bRet) { LOGGER(E_LOG_ERROR) << "save to redis failed!bettype = " << i; } } } void Table::setBetLimit() { Player* banker = NULL; if(bankersid >=0) banker = this->player_array[bankersid]; if(banker) { calculateBetAreaLimit(banker); } else { LOGGER(E_LOG_ERROR) << "banker is INVALID! banker sid = " << bankersid; } } bool Table::SetResult(int64_t bankerwincount, int64_t userbankerwincount) { //计算牌点 BYTE cbPlayerCount = m_GameLogic.GetCardListPip( m_cbTableCardArray[INDEX_PLAYER],m_cbCardCount[INDEX_PLAYER] ); BYTE cbBankerCount = m_GameLogic.GetCardListPip( m_cbTableCardArray[INDEX_BANKER],m_cbCardCount[INDEX_BANKER] ); //系统输赢 int64_t lSystemScoreCount = 0; int64_t systemWinCount = 0; //推断玩家 BYTE cbWinArea[AREA_MAX] = {FALSE}; DeduceWinner(cbWinArea); Player* banker = NULL; if(bankersid >=0) banker = this->player_array[bankersid]; if(banker == NULL) { //_LOG_ERROR_("CalculateScore: banker is NULL bankersid:%d bankeruid:%d\n", bankersid, bankeruid); return false; } for (int i = 0; i < GAME_PLAYER; i++) { Player* player = this->player_array[i]; if (player) { player->m_lTempScore = 0; } } bool isBankerRobot = banker->source == E_MSG_SOURCE_ROBOT; for(int j = 0; j < GAME_PLAYER; ++j) { Player *player = this->player_array[j]; if (player==NULL) continue; if (player->id == this->bankeruid) continue; bool isRobot = player->source == E_MSG_SOURCE_ROBOT; for (BYTE wAreaIndex = 1; wAreaIndex < AREA_MAX; wAreaIndex++) { if (cbWinArea[wAreaIndex] == TRUE) { player->m_lTempScore += player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; banker->m_lTempScore -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; if (banker->source == E_MSG_SOURCE_ROBOT && player->source != E_MSG_SOURCE_ROBOT) //机器人坐庄,真人玩家下注 { systemWinCount -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; } if (banker->source != E_MSG_SOURCE_ROBOT && player->source == E_MSG_SOURCE_ROBOT) //真人坐庄,机器人下注 { systemWinCount += player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; } } else if (cbWinArea[AREA_PING] == TRUE && (wAreaIndex == AREA_XIAN || wAreaIndex == AREA_ZHUANG)) { } else { player->m_lTempScore -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; banker->m_lTempScore += player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; if (banker->source == E_MSG_SOURCE_ROBOT && player->source != E_MSG_SOURCE_ROBOT) //机器人坐庄,真人玩家下注 { systemWinCount += player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; } if (banker->source != E_MSG_SOURCE_ROBOT && player->source == E_MSG_SOURCE_ROBOT) //真人坐庄,机器人下注 { systemWinCount -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; } } } } int64_t lUserWin = 0; for (int i = 0; i < GAME_PLAYER; i++) { Player* player = this->player_array[i]; if (player && player->source == E_MSG_SOURCE_ROBOT) { lSystemScoreCount += player->m_lTempScore; } if (player && player->source != E_MSG_SOURCE_ROBOT) { lUserWin += player->m_lTempScore; } } { int64_t tempScore = lSystemScoreCount + bankerwincount; _LOG_ERROR_( "systemWinCount is :%ld, tempScore:%ld, lSystemScoreCount:%ld, lowerlimit:%ld, upperlimit:%ld " , systemWinCount , lSystemScoreCount , tempScore, this->coincfg.lowerlimit , this->coincfg.upperlimit ); if (tempScore > this->coincfg.lowerlimit && tempScore <= this->coincfg.upperlimit) { // 系统输钱,库存在安全范围,但库存单次降低超过 70%, 不予开奖 if (lSystemScoreCount<0 && tempScore > 0 && bankerwincount > 0 && (tempScore * 100) / bankerwincount <= 40) { return false; } if (bankerwincount - lUserWin<=0) { return false; } // if (lUserWin >= (bankerwincount*0.6)) // { // return false; // } return true; } if ( tempScore <= this->coincfg.lowerlimit ) { if (bankerwincount - lUserWin <= 0) { return false; } //系统赢 if (lSystemScoreCount > 0) { return true; } else { return false; } } if ( tempScore > this->coincfg.upperlimit ) { if (bankerwincount - lUserWin <= 0) { return false; } //系统输 if (lSystemScoreCount <= 0) { return true; } else { return false; } } return true; } } void Table::DisplayCards() { BYTE cbPlayerCount = m_GameLogic.GetCardListPip(m_cbTableCardArray[INDEX_PLAYER] , m_cbCardCount[INDEX_PLAYER]); BYTE cbBankerCount = m_GameLogic.GetCardListPip(m_cbTableCardArray[INDEX_BANKER] , m_cbCardCount[INDEX_BANKER]); std::string card_more; std::string cardInfo1; std::string cardInfo2; char msg[32] = { 0 }; if (m_cbCardCount[INDEX_PLAYER] == 3) { card_more = m_GameLogic.getCardInfo(m_cbTableCardArray[INDEX_PLAYER][2]); sprintf(msg , "补牌: %s, 总点数:%d" , card_more.c_str(), cbPlayerCount); } else { sprintf(msg , "总点数:%d" , cbPlayerCount); } cardInfo1 = m_GameLogic.getCardInfo(m_cbTableCardArray[INDEX_PLAYER][0]); cardInfo2 = m_GameLogic.getCardInfo(m_cbTableCardArray[INDEX_PLAYER][1]); _LOG_DEBUG_("闲[%s, %s], %s", cardInfo1.c_str(), cardInfo2.c_str(), msg); char msg2[32] = { 0 }; if (m_cbCardCount[INDEX_BANKER] == 3) { card_more = m_GameLogic.getCardInfo(m_cbTableCardArray[INDEX_BANKER][2]); sprintf(msg2 , "补牌: %s, 总点数:%d" , card_more.c_str() , cbBankerCount); } else { sprintf(msg2 , "总点数:%d" , cbBankerCount); } cardInfo1 = m_GameLogic.getCardInfo(m_cbTableCardArray[INDEX_BANKER][0]); cardInfo2 = m_GameLogic.getCardInfo(m_cbTableCardArray[INDEX_BANKER][1]); _LOG_DEBUG_("庄[%s, %s], %s" , cardInfo1.c_str() , cardInfo2.c_str() , msg2); } void Table::GameOver() { m_nDespatchNum = 0; int64_t bankerwincount = 0; int64_t playerwincount = 0; int64_t userbankerwincount = 0; CoinConf::getInstance()->getWinCount(bankerwincount, playerwincount, userbankerwincount); SortedScordIndex.clear(); DisplayPlayerBetInfo(); // 根据下注情况,确定所有开奖情况的赔付,选择一个较优的开奖区域 CalcualAllResult(); srand(time(NULL)); //_LOG_INFO_("========= bankerwincount == %ld\n", bankerwincount); //short resultret = CoinConf::getInstance()->getSwtichTypeResult(); //int printresult = 0; while(true) { /* if(resultret > 0 && resultret < 4) { if(SysSetResult(resultret)) { printresult = 1; break; } } else if (Loser && Configure::getInstance().randlose > 0 && ((Loser->id != bankeruid && Loser->m_lBetArray[0] >= Configure::getInstance().switchbetmoney) || Loser->id == bankeruid)) { if(SetLoserResult(Loser)) { printresult = 2; break; } } else */ //{ //if(SetResult(bankerwincount, userbankerwincount)) // break; //} DispatchTableCard(rand()); //if (SetResult(bankerwincount, userbankerwincount)) if (SetResult(bankerwincount , userbankerwincount)) { DisplayCards(); break; } m_nDespatchNum++; if (m_nDespatchNum > 100) { BYTE winType = 0; BYTE zhuang_dui = 0; BYTE xian_dui = 0; OpenType2WinAreasInfo(GetSafeOpenType(), winType, zhuang_dui, xian_dui); DispatchTableCard(rand(), winType, zhuang_dui, xian_dui); DisplayCards(); break; } } //_LOG_INFO_("GameOver: GameID[%s] dispatch num[%d] bet1:%ld bet2:%ld bet3:%ld Loser:%d printresult:%d resultret:%d bankeruid:%d\n", // this->getGameID(), m_nDespatchNum, this->m_lTabBetArray[1], this->m_lTabBetArray[2], this->m_lTabBetArray[3], Loser ? Loser->id : 0, printresult, resultret, bankeruid); //_LOG_INFO_("========= WinType == %d\n", m_bWinType); //_LOG_INFO_("GameOver: GameID[%s] dispatch num[%d] bet1:%ld bet2:%ld bet3:%ld bankeruid:%d\n", // this->getGameID(), m_nDespatchNum, this->m_lTabBetArray[1], this->m_lTabBetArray[2], this->m_lTabBetArray[3], bankeruid); CalculateScore(0); IProcess::GameOver(this); ClearBetInfo(); } int64_t Table::RobotBankerGetSystemWin(BYTE openType) { int64_t system_win = 0; for (int j = 0; j < GAME_PLAYER; ++j) { Player *player = this->player_array[j]; if (player == NULL) continue; if (player->id == this->bankeruid) continue; if (player->source == E_MSG_SOURCE_ROBOT) // 只考虑真人闲家跟系统之间的输赢 continue; for (BYTE wAreaIndex = 1; wAreaIndex < AREA_MAX; wAreaIndex++) { if (AllWinArea[openType][wAreaIndex] == TRUE) { system_win -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; // 玩家压中, 按倍率和玩家下注 进行赔付 } else { system_win += player->m_lBetArray[wAreaIndex]; // 玩家未压中,下注被系统吃掉 } } } return system_win; } int64_t Table::PlayerBankerGetSystemWin(BYTE openType) { int64_t system_win = 0; for (int j = 0; j < GAME_PLAYER; ++j) { Player *player = this->player_array[j]; if (player == NULL) continue; if (player->id == this->bankeruid) continue; if (player->source != E_MSG_SOURCE_ROBOT) // 只考虑机器人闲家跟真人庄家之间的输赢 continue; for (BYTE wAreaIndex = 1; wAreaIndex < AREA_MAX; wAreaIndex++) { if (AllWinArea[openType][wAreaIndex] == TRUE) { system_win += player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; // 机器人压中, 按倍率和下注 交给系统 } else { system_win -= player->m_lBetArray[wAreaIndex]; // 机器人未压中,下注被玩家吃掉 } } } return system_win; } void Table::SortOpenTypes() { for (BYTE i = 0; i < 12; ++i) { ScoreIndexRecord item; item.index = i; item.score = AllOpenResult[i]; SortedScordIndex.push_back(item); } sort(SortedScordIndex.begin() , SortedScordIndex.end()); _LOG_ERROR_("-------------------- round all open result ---------------------------------------"); std::vector<ScoreIndexRecord>::iterator it = SortedScordIndex.begin(); for (; it != SortedScordIndex.end(); ++ it) { _LOG_ERROR_("index: %d, system win :%d", it->index, it->score); } _LOG_ERROR_("-------------------- --------------------- ---------------------------------------"); } BYTE Table::GetSafeOpenType() { BYTE openTypeIndex[12] = {0}; BYTE count = 0; std::vector<ScoreIndexRecord>::iterator it = SortedScordIndex.begin(); for (; it != SortedScordIndex.end(); ++it) { if (it->score >= 0) { openTypeIndex[count++] = (it->index); } } if (count == 0) { return 8; } return openTypeIndex[rand() % count]; } void Table::OpenType2WinAreasInfo(BYTE openType , BYTE &winType , BYTE &zhuang_dui , BYTE &xian_dui) { zhuang_dui = 0; xian_dui = 0; switch (openType) { case 0: winType = WIN_TYPE_ZHUANG; break; case 1: winType = WIN_TYPE_ZHUANG; zhuang_dui = 1; case 2: winType = WIN_TYPE_ZHUANG; xian_dui = 1; break; case 3: winType = WIN_TYPE_ZHUANG; zhuang_dui = 1; xian_dui = 1; case 4: winType = WIN_TYPE_XIAN; break; case 5: winType = WIN_TYPE_XIAN; xian_dui = 1; case 6: winType = WIN_TYPE_XIAN; zhuang_dui = 1; break; case 7: winType = WIN_TYPE_XIAN; zhuang_dui = 1; xian_dui = 1; case 8: winType = WIN_TYPE_HE; break; case 9: winType = WIN_TYPE_HE; zhuang_dui = 1; case 10: winType = WIN_TYPE_HE; xian_dui = 1; break; case 11: winType = WIN_TYPE_HE; zhuang_dui = 1; xian_dui = 1; break; default: winType = WIN_TYPE_ZHUANG; } } void Table::DisplayPlayerBetInfo() { _LOG_ERROR_("庄家: %d", bankeruid); for ( int32_t i = 0; i < GAME_PLAYER; ++i ) { Player* player = player_array[i]; if (player) { _LOG_ERROR_("%s, %s, %s, %d: 压庄[%d], 压闲[%d], 压和[%d], 压庄对[%d], 压闲对[%d]" , bankeruid == player->id ? "庄家" : "闲家" , player->source == E_MSG_SOURCE_ROBOT ? "机器人" : "真人" , player->name, player->id, player->m_lBetArray[AREA_ZHUANG] , player->m_lBetArray[AREA_XIAN] , player->m_lBetArray[AREA_PING] , player->m_lBetArray[AREA_ZHUANG_DUI] , player->m_lBetArray[AREA_XIAN_DUI]); } } } void Table::CalcualAllResult() { Player* banker = NULL; if (bankersid >= 0) { banker = this->player_array[bankersid]; } if (banker == NULL) { return; } bool isBankerRobot = (banker->source == E_MSG_SOURCE_ROBOT? true:false); for (BYTE i = 0; i < 12; ++i) //统计每种开奖的 { if (isBankerRobot) //系统坐庄 { AllOpenResult[i] = RobotBankerGetSystemWin(i); } else { AllOpenResult[i] = PlayerBankerGetSystemWin(i); } } SortOpenTypes(); } void Table::CalculateScore(short resultret) { //计算牌点 BYTE cbPlayerCount = m_GameLogic.GetCardListPip( m_cbTableCardArray[INDEX_PLAYER],m_cbCardCount[INDEX_PLAYER] ); BYTE cbBankerCount = m_GameLogic.GetCardListPip( m_cbTableCardArray[INDEX_BANKER],m_cbCardCount[INDEX_BANKER] ); //系统输赢 int64_t lSystemScoreCount = 0; //推断玩家 BYTE cbWinArea[AREA_MAX] = {FALSE}; DeduceWinner(cbWinArea); Player* banker = NULL; if(bankersid >=0) banker = this->player_array[bankersid]; if(banker == NULL) { //_LOG_ERROR_("CalculateScore: banker is NULL bankersid:%d bankeruid:%d\n", bankersid, bankeruid); return; } m_bWinType = getWinType(cbWinArea); m_cbBankerPair = cbWinArea[AREA_ZHUANG_DUI]; m_cbPlayerPair = cbWinArea[AREA_XIAN_DUI]; m_cbBankerPoint = cbBankerCount; m_cbPlayerPoint = cbPlayerCount; //游戏记录 ServerGameRecord &GameRecord = m_GameRecordArrary[m_nRecordLast]; GameRecord.cbBankerCount = m_cbBankerPoint; GameRecord.cbPlayerCount = m_cbPlayerPoint; GameRecord.bPlayerTwoPair = m_cbPlayerPair; GameRecord.bBankerTwoPair = m_cbBankerPair; GameRecord.cbWinType = m_bWinType; //if ( cbWinArea[AREA_TONG_DUI] == TRUE ) // GameRecord.cbKingWinner = AREA_TONG_DUI; LOGGER(E_LOG_INFO) << "wintype = " << m_bWinType << "banker point = " << m_cbBankerPoint << "player point = " << m_cbPlayerPoint << "banker pair = " << m_cbBankerPair << "player pair = " << m_cbPlayerPair; bool isBankerRobot = banker->source == E_MSG_SOURCE_ROBOT; for(int j = 0; j < GAME_PLAYER; ++j) { Player *player = this->player_array[j]; if (player==NULL) continue; if (player->id == this->bankeruid) continue; bool isRobot = player->source == E_MSG_SOURCE_ROBOT; for (BYTE wAreaIndex = 1; wAreaIndex < AREA_MAX; wAreaIndex++) { if (cbWinArea[wAreaIndex] == TRUE) { if (wAreaIndex == AREA_PING|| wAreaIndex == AREA_XIAN_DUI || wAreaIndex == AREA_ZHUANG_DUI) { player->m_lWinScore += player->m_lBetArray[wAreaIndex] * (Multiple[wAreaIndex] - 1); banker->m_lWinScore -= player->m_lBetArray[wAreaIndex] * (Multiple[wAreaIndex] - 1); this->m_lBankerWinScoreCount -= player->m_lBetArray[wAreaIndex] * (Multiple[wAreaIndex] - 1); } else { player->m_lWinScore += player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; banker->m_lWinScore -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; this->m_lBankerWinScoreCount -= player->m_lBetArray[wAreaIndex] * Multiple[wAreaIndex]; } } else { if (cbWinArea[AREA_PING] != TRUE) { player->m_lLostScore -= player->m_lBetArray[wAreaIndex]; banker->m_lWinScore += player->m_lBetArray[wAreaIndex]; this->m_lBankerWinScoreCount += player->m_lBetArray[wAreaIndex]; } else { if (wAreaIndex == AREA_XIAN_DUI || wAreaIndex == AREA_ZHUANG_DUI) { player->m_lLostScore -= player->m_lBetArray[wAreaIndex]; banker->m_lWinScore += player->m_lBetArray[wAreaIndex]; this->m_lBankerWinScoreCount += player->m_lBetArray[wAreaIndex]; } } } // if (cbWinArea[AREA_PING] != TRUE) //如果和赢,则其他位置的下注都无需扣除 // { // player->m_lLostScore -= player->m_lBetArray[wAreaIndex]; // banker->m_lWinScore += player->m_lBetArray[wAreaIndex]; // this->m_lBankerWinScoreCount += player->m_lBetArray[wAreaIndex]; // } } } //移动下标 m_nRecordLast = (m_nRecordLast+1) % MAX_SCORE_HISTORY; if (m_historyCount < MAX_SCORE_HISTORY) { m_historyCount++; } else { m_historyCount = MAX_SCORE_HISTORY; } int64_t lsysrobotcount = 0; int64_t bankerwincount = 0; for(int j = 0; j < GAME_PLAYER; ++j) { Player *player = this->player_array[j]; if (player==NULL) continue; //player->m_lWinScore += player->m_lLostScore; if (player->m_lWinScore > 0) { //Util::taxDeduction(player->m_lWinScore, this->m_nTax, player->tax); int64_t needTaxMoney = player->m_lWinScore + player->m_lLostScore; if (needTaxMoney > 0) { GameUtil::CalcSysWinMoney(needTaxMoney, player->tax, this->m_nTax); player->m_lWinScore -= player->tax; } else { player->tax = 0; } if (E_MSG_SOURCE_ROBOT == player->source) { int64_t lRobotWin = player->m_lWinScore + player->tax + player->m_lLostScore; lsysrobotcount += lRobotWin; if (!RedisLogic::AddRobotWin(Tax(), player->pid, Configure::getInstance()->m_nServerId, (int)lRobotWin)) { LOGGER(E_LOG_WARNING) << "OperationRedis::AddRobotWin Error, pid=" << player->pid << ", m_nServerId=" << Configure::getInstance()->m_nServerId << ", win=" << lRobotWin; } } else { if (player->id == bankeruid) this->m_lBankerWinScoreCount -= player->tax; if (!RedisLogic::UpdateTaxRank(Tax(), player->pid, Configure::getInstance()->m_nServerId, GAME_ID, Configure::getInstance()->m_nLevel, player->tid, player->id, player->tax)) { LOGGER(E_LOG_WARNING) << "OperationRedis::GenerateTip Error, pid=" << player->pid << ", m_nServerId=" << Configure::getInstance()->m_nServerId << ", gameid=" << GAME_ID << ", level=" << Configure::getInstance()->m_nLevel << ", id=" << player->id << ", Tax=" << player->tax; } } } else //机器人输钱也需要算 { if (player->source == E_MSG_SOURCE_ROBOT) { lsysrobotcount += player->m_lWinScore + player->m_lLostScore; } } player->m_lMoney += player->m_lWinScore + player->m_lReturnScore + player->m_lLostScore; } if(banker->source != E_MSG_SOURCE_ROBOT) { bankerwincount = banker->m_lWinScore + banker->tax; } if(resultret > 0) { int notInsertRedis = 0; } else { if(lsysrobotcount != 0) { CoinConf::getInstance()->setWinCount(lsysrobotcount, 0, bankerwincount); } } ++bankernum; } void Table::reloadCfg() { CoinConf* coinCalc = CoinConf::getInstance(); Cfg* coincfg = coinCalc->getCoinCfg(); m_nTax = coincfg->tax; m_nLimitCoin = coincfg->limitcoin; m_nRetainCoin = coincfg->retaincoin; m_nBankerlimit = coincfg->bankerlimit; m_nMaxBankerNum = coincfg->bankernum; m_nMaxBetNum = coincfg->betnum; m_nMinBetNum = coincfg->minbetnum; this->m_nPersonLimitCoin = coincfg->PersonLimitCoin; for (int i = 0; i < CHIP_COUNT; i++) { m_nChipArray[i] = coincfg->chiparray[i]; } coinCalc->getRewardRates(m_nZhuangWinRate , m_nXianWinRate , m_nPingRate , m_nZhuangDuiRate , m_nXianDuiRate); } //==================================TableTimer================================================= void Table::startIdleTimer(int timeout) { timer.startIdleTimer(timeout); } void Table::stopIdleTimer() { timer.stopIdleTimer(); } void Table::startBetTimer(int timeout) { timer.startBetTimer(timeout); } void Table::stopBetTimer() { timer.stopBetTimer(); } void Table::startOpenTimer(int timeout) { timer.startOpenTimer(timeout); } void Table::stopOpenTimer() { timer.stopOpenTimer(); } bool Table::EnterSeat(int seatid, Player *player) { if (seatid > MAX_SEAT_NUM || seatid == 0) { _LOG_ERROR_("Table::EnterSeat : Seatid=[%d] is overflow.\n", seatid); return false; } if (m_SeatidArray[seatid-1] != NULL) { _LOG_ERROR_("Table::EnterSeat : Seatid=[%d] be seated uid=[%d].\n", seatid, m_SeatidArray[seatid-1]->id); return false; } if (player->m_seatid != 0) { LeaveSeat(player->m_seatid); } player->m_seatid = seatid; m_SeatidArray[seatid - 1] = player; _LOG_INFO_("Table::EnterSeat : successed uid=[%d] Seatid=[%d] seated .\n", m_SeatidArray[seatid-1]->id, seatid); return true; } bool Table::LeaveSeat(int seatid) { if (seatid > MAX_SEAT_NUM || seatid == 0) { _LOG_ERROR_("Table::LeaveSeat : Seatid=[%d] is overflow.\n", seatid); return false; } if (m_SeatidArray[seatid-1] != NULL) { _LOG_INFO_("Table::LeaveSeat : successed uid=[%d] Seatid=[%d] seated .\n", m_SeatidArray[seatid-1]->id, seatid); m_SeatidArray[seatid-1]->m_seatid = 0; m_SeatidArray[seatid-1] = NULL; return true; } return false; } void Table::SendSeatInfo(Player *player) { _LOG_INFO_("Table::SendSeatInfo : player->uid=[%d]\n", player->id); if (player == NULL) { _LOG_ERROR_("Table::SendSeatInfo : why player is null.\n"); return; } OutputPacket response; response.Begin(CLIENT_MSG_REFRESH_SEATLIST, player->id); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteInt((Configure::getInstance()->m_nServerId << 16) | this->id); response.WriteInt(MAX_SEAT_NUM); //一共多少桌位号 for (int i = 0; i < MAX_SEAT_NUM; ++i) { if (m_SeatidArray[i] != NULL) { response.WriteInt(i+1); //座位ID response.WriteInt(m_SeatidArray[i]->id); //玩家ID response.WriteString(m_SeatidArray[i]->name); //玩家名称 response.WriteString(m_SeatidArray[i]->headlink);//玩家头像url response.WriteInt64(m_SeatidArray[i]->m_lMoney); //玩家金币 } else { response.WriteInt(i+1); //座位ID response.WriteInt(0); //玩家ID response.WriteString(""); //玩家名称 response.WriteString(""); //玩家头像url response.WriteInt64(0); //玩家金币 } } for (int i = 0; i < MAX_SEAT_NUM; ++i) { if (m_SeatidArray[i] != NULL) { response.WriteString(m_SeatidArray[i]->json); //player json } else { response.WriteString(""); //player json } } response.End(); HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false); } void Table::NotifyPlayerSeatInfo() { _LOG_INFO_("Table::NotifyPlayerSeatInfo"); for(int i = 0; i < GAME_PLAYER; ++i) { if (this->player_array[i]) { SendSeatInfo(this->player_array[i]); } } } void Table::DispatchTableCard(int randSeed, BYTE type, BYTE zhuang_dui, BYTE xian_dui) { if (!receivePhpPush) { if (type > 0) { RandCardByAssignedType(randSeed , type); } else //随机扑克 { RandCardByWinType(randSeed); } } else { phpRandCard(randSeed); } //首次发牌 m_cbCardCount[INDEX_PLAYER] = 2; m_cbCardCount[INDEX_BANKER] = 2; //计算点数 BYTE cbBankerCount = m_GameLogic.GetCardListPip(m_cbTableCardArray[INDEX_BANKER], m_cbCardCount[INDEX_BANKER]); BYTE cbPlayerTwoCardCount = m_GameLogic.GetCardListPip(m_cbTableCardArray[INDEX_PLAYER], m_cbCardCount[INDEX_PLAYER]); //闲家补牌 BYTE cbPlayerThirdCardValue = 0; //第三张牌点数 if (cbPlayerTwoCardCount <= 5 && cbBankerCount < 8) { //计算点数 m_cbCardCount[INDEX_PLAYER]++; cbPlayerThirdCardValue = m_GameLogic.GetCardPip(m_cbTableCardArray[INDEX_PLAYER][2]); } //庄家补牌 if (cbPlayerTwoCardCount < 8 && cbBankerCount < 8) { switch(cbBankerCount) { case 0: case 1: case 2: m_cbCardCount[INDEX_BANKER]++; break; case 3: if((m_cbCardCount[INDEX_PLAYER] == 3 && cbPlayerThirdCardValue!=8) || m_cbCardCount[INDEX_PLAYER] == 2) m_cbCardCount[INDEX_BANKER]++; break; case 4: if((m_cbCardCount[INDEX_PLAYER] == 3 && cbPlayerThirdCardValue!=1 && cbPlayerThirdCardValue!=8 && cbPlayerThirdCardValue!=9 && cbPlayerThirdCardValue!=0) || m_cbCardCount[INDEX_PLAYER] == 2) m_cbCardCount[INDEX_BANKER]++; break; case 5: if((m_cbCardCount[INDEX_PLAYER] == 3 && cbPlayerThirdCardValue!=1 && cbPlayerThirdCardValue!=2 && cbPlayerThirdCardValue!=3 && cbPlayerThirdCardValue!=8 && cbPlayerThirdCardValue!=9 && cbPlayerThirdCardValue!=0) || m_cbCardCount[INDEX_PLAYER] == 2) m_cbCardCount[INDEX_BANKER]++; break; case 6: if(m_cbCardCount[INDEX_PLAYER] == 3 && (cbPlayerThirdCardValue == 6 || cbPlayerThirdCardValue == 7)) m_cbCardCount[INDEX_BANKER]++; break; //不须补牌 case 7: case 8: case 9: break; default: break; } } } void Table::DeduceWinner(BYTE *pWinArea) { //计算牌点 BYTE cbPlayerCount = m_GameLogic.GetCardListPip(m_cbTableCardArray[INDEX_PLAYER],m_cbCardCount[INDEX_PLAYER]); BYTE cbBankerCount = m_GameLogic.GetCardListPip(m_cbTableCardArray[INDEX_BANKER],m_cbCardCount[INDEX_BANKER]); //胜利区域-------------------------- //平 if( cbPlayerCount == cbBankerCount ) { pWinArea[AREA_PING] = TRUE; //同点平 if (m_cbCardCount[INDEX_PLAYER] == m_cbCardCount[INDEX_BANKER]) { WORD wCardIndex = 0; for (; wCardIndex < m_cbCardCount[INDEX_PLAYER]; ++wCardIndex ) { BYTE cbBankerValue = m_GameLogic.GetCardValue(m_cbTableCardArray[INDEX_BANKER][wCardIndex]); BYTE cbPlayerValue = m_GameLogic.GetCardValue(m_cbTableCardArray[INDEX_PLAYER][wCardIndex]); if ( cbBankerValue != cbPlayerValue ) break; } if ( wCardIndex == m_cbCardCount[INDEX_PLAYER] ) { pWinArea[AREA_PING] = TRUE; } } } // 庄 else if ( cbPlayerCount < cbBankerCount) { pWinArea[AREA_ZHUANG] = TRUE; //天王判断 if ( cbBankerCount == 8 || cbBankerCount == 9 ) { //pWinArea[AREA_ZHUANG_TIAN] = TRUE; } } // 闲 else { pWinArea[AREA_XIAN] = TRUE; //天王判断 if ( cbPlayerCount == 8 || cbPlayerCount == 9 ) { //pWinArea[AREA_XIAN_TIAN] = TRUE; } } //对子判断 if (m_GameLogic.GetCardValue(m_cbTableCardArray[INDEX_PLAYER][0]) == m_GameLogic.GetCardValue(m_cbTableCardArray[INDEX_PLAYER][1])) { pWinArea[AREA_XIAN_DUI] = TRUE; } if (m_GameLogic.GetCardValue(m_cbTableCardArray[INDEX_BANKER][0]) == m_GameLogic.GetCardValue(m_cbTableCardArray[INDEX_BANKER][1])) { pWinArea[AREA_ZHUANG_DUI] = TRUE; } } BetArea::BetArea(BET_TYPE bt, Table* tab) { this->betType = bt; this->table = tab; this->gameRecord = 0; this->betLimit = 0; this->betMoney = 0; this->betRealMoney = 0; } void BetArea::updateBetLimit() { } void BetArea::updateBetMoney(Player *p) { if (p == NULL) { return; } //this->betMoney += p->be } void BetArea::updateRealMoney(Player *p) { }
// Grading Students // https://www.hackerrank.com/challenges/grading/problem #include<bits/stdc++.h> using namespace std; int last(stack<int> stk) { } int main() { stack<int> stk; cout<<stk.top(); cout<<endl; return 0; }
#pragma once namespace u_interface_classes { void classes_interface(); }
#include "cointoss.h" #include "ui_cointoss.h" #include <stdlib.h> /**************** * Do not modify ****************/ coinToss::coinToss(QWidget *parent) : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint ), Minigame(), ui(new Ui::coinToss) { ui->setupUi(this); ui->start_jackpot->setEnabled(false); ui->b_ok->setEnabled(false); for (int i=0; i<3; i++) arr[i] = 0; configureGame(); } /**************** * Clean all minigame code ****************/ coinToss::~coinToss() { for(int i = 0; i < num1; i++) delete this->tile[i]; delete ui; } /******** PRIVATE **********/ /**************** * Configure minigame ****************/ void coinToss::configureGame() { //srand(0); connect(ui->start_jackpot, SIGNAL(clicked()), this, SLOT(on_start_jackpot_clicked())); for(int i = 0; i < num1; i++) { tile[i] = new CointossTile(i, true, this); tile[i]->setText(QString("Slot")); tile[i]->setFixedSize(100, 100); connect(tile[i], SIGNAL(clicked()), this, SLOT(on_b_tile_clicked())); ui->g_grid->addWidget(tile[i], 0, i); tile[i]->setStyleSheet("background:Green;"); } disableGame(); } void coinToss::disableGame() { for(int i = 0; i < num1; i++) this->tile[i]->setEnabled(false); } /**************** * Do not modify ****************/ void coinToss::setWin() { Minigame::setWin(); ui->t_result->setText(QString("You Win!")); ui->t_result->setAlignment(Qt::AlignCenter); } /**************** * Do not modify ****************/ void coinToss::setLose() { Minigame::setLose(); ui->t_result->setText(QString("You Lose!")); ui->t_result->setAlignment(Qt::AlignCenter); } /**************** * Do not modify ****************/ void coinToss::quit() { Minigame::quit(); disableGame(); ui->b_ok->setEnabled(true); } /******** PRIVATE SLOTS **********/ /**************** * Set win or lose ****************/ /*void coinToss::on_b_tile_clicked() { CointossTile* tile = (CointossTile*)sender(); if(tile->getUnique()) setWin(); else setLose(); quit(); }*/ /**************** * Do not modify ****************/ void coinToss::on_b_ok_clicked() { this->done(QDialog::Accepted); } void coinToss::on_num_1_currentTextChanged(const QString &arg1) { this->selectedFirstSlotValue= arg1.toStdString(); } void coinToss::on_num_2_currentTextChanged(const QString &arg1) { this->selectedSecondSlotValue = arg1.toStdString(); } void coinToss::on_num_3_currentTextChanged(const QString &arg1) { this->selectedThirdSlotValue = arg1.toStdString(); if (this->selectedFirstSlotValue.compare("select") != 0 && this->selectedSecondSlotValue.compare("select") != 0 && this->selectedThirdSlotValue.compare("select") != 0) { ui->start_jackpot->setEnabled(true); } } void coinToss::on_start_jackpot_clicked() { for(int i=0; i<3; i++) arr[i] = rand() % 9 + 1; if (this->selectedFirstSlotValue.compare("select") == 0 || this->selectedSecondSlotValue.compare("select") == 0 || this->selectedThirdSlotValue.compare("select") == 0) { // Do nothing and ask user to give all inputs } else { ui->num_1->setEnabled(false); ui->num_2->setEnabled(false); ui->num_3->setEnabled(false); int input1 = this->selectedFirstSlotValue[0] - '0'; int input2 = this->selectedSecondSlotValue[0] - '0'; int input3 = this->selectedThirdSlotValue[0] - '0'; for (int i=0; i<3; i++) tile[i]->setText(QString(arr[i] + '0')); if (arr[0] == input1 && arr[1] == input2 && arr[2] == input3) { setWin(); ui->t_result->setStyleSheet("background: Green;"); } else { setLose(); ui->t_result->setStyleSheet("background: Red;"); } ui->start_jackpot->setEnabled(false); quit(); } }
#include <iostream> #include <boost/thread.hpp> #include <boost/asio.hpp> void handler1(const boost::system::error_code &ec) { std::cout << "5 s. " << std::endl; } void handler2(const boost::system::error_code &ec) { std::cout << " 10 s " << std::endl; } boost::asio::io_service io_service; void run() { io_service.run(); } int main(int argc, char **argv) { boost::asio::deadline_timer t1(io_service, boost::posix_time::seconds(5)); t1.async_wait(handler1); boost::asio::deadline_timer t2(io_service, boost::posix_time::seconds(10)); t2.async_wait(handler2); boost::thread th1(run); boost::thread th2(run); th1.join(); th2.join(); }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SKLAND_WAYLAND_XDG_SHELL_HPP_ #define SKLAND_WAYLAND_XDG_SHELL_HPP_ #include "registry.hpp" #include <memory> namespace skland { namespace wayland { class XdgSurface; class XdgPositioner; struct XdgShellMeta; class XdgShell { friend class XdgSurface; friend class XdgPositioner; friend struct XdgShellMeta; XdgShell(const XdgShell &) = delete; XdgShell &operator=(const XdgShell &) = delete; public: static const struct wl_interface *GetInterface(); XdgShell(); ~XdgShell(); void Setup(const Registry &registry, uint32_t id, uint32_t version); void Destroy(); void Pong(uint32_t serial) const; void SetUserData(void *user_data); void *GetUserData() const; uint32_t GetVersion() const; bool IsValid() const; bool Equal(const void *object) const; /** * @brief A ping callback sent from compositor * @return Reference to the ping delegate */ DelegateRef<void(uint32_t)> ping() { return ping_; } private: std::unique_ptr<XdgShellMeta> metadata_; Delegate<void(uint32_t)> ping_; }; } } #endif // SKLAND_WAYLAND_XDG_SHELL_HPP_
#include<iostream> #include<math.h> //declaram 2 variabile pentru numar si pentru radacina int main(){//start main int nr, i; int sq; printf("\nIntroduce-ti un numar: "); scanf("%d",&nr); //verificam daca fiecare numar de la 0 pana la nr ridicat la patrat este egal cu numarul introdus for(i=0;i<=nr;i++){ if(nr == i*i){ printf("Numarul %d este patrat perfect\n", nr); //pentru a face uz de libraria math.h sq = sqrt(nr); printf("Radacina patrata a lui %d este %d\n", nr,sq); //daca conditia este indeplinita , return 0 si se opreste aici return 0; } } //un "else" in afara loop-ului printf("Numarul nu este patrat perfect\n"); return 0; }//end main
#ifndef UNITSTATE_H #define UNITSTATE_H #include <iostream> #include <string> class UnitState { private: std::string name; int maxHp; int dmg; protected: int hp; public: UnitState(const std::string& name, int health, int maxHealth, int damage, bool isUndead = false); virtual ~UnitState(); bool outOfHp() const; bool isUnDead; const std::string& getName() const; int getHp() const; int getMaxHp() const; int getDmg() const; void setName(const std::string& name); virtual void takeDamage(int dmg); virtual void takeMagicDamage(int dmg); virtual void takeTreatment(int hp); }; std::ostream& operator<<(std::ostream& out, const UnitState& state); #endif // UNITSTATE_H
#include <numeric> #include <afxdao.h> #include "city_forecast.h" #include "analy-day.h" //取消DAO数据库操作警告 #pragma warning( disable : 4995 ) //将实况插入数据库 bool insertDB(const char *dbname,const char * table, COleDateTime datet,std::vector<double> &vals) { using namespace std; CDaoDatabase daoDb; COleVariant OleV1,OleV2 ;//日期和数值字段 daoDb.Open(dbname,0,0,";PWD=1234%hnyl@20070701%"); //打开数据库 CDaoRecordset Record(&daoDb) ; //构造记录集 CString Sql = "SELECT * FROM "; CString SqlW; SqlW.Format(" WHERE date= #%s# ",datet.Format("%Y-%m-%d") ); Record.Open ( dbOpenDynaset, Sql+table+SqlW+" ORDER BY date" ) ; //初始化记录集 if(!Record.IsOpen()) return false; OleV1 = datet; bool isfind = (Record.GetRecordCount()>0); //cout<<Record.GetRecordCount()<<" "<<Record.GetAbsolutePosition(); if(isfind) //找到后修改 { Record.Edit(); } else //没找到添加 { Record.AddNew (); } Record.SetFieldValue(1,OleV1); for(int i=0;i<9;++i) { OleV2 = vals[i]; Record.SetFieldValue(i+2,OleV2); } // //cout<<"\r \r"; //cout<<"已完成: "<< 100.0*(j*n+i+1)/(m*n)<<"%"; //cout<<date<<" "<<names[i]<<" "<<vals[i][j]<<endl; Record.Update(); //更新数据 daoDb.Close(); //关闭数据库 AfxDaoTerm(); // return true; } void readVal() { using namespace std; string name="files/XQZL.csv_format.txt"; //cout<<"Input the text name:"; //cin>>name; ifstream fin(name.c_str()); vector<double> vals(9,0); COleDateTime datet(2008,6,1,0,0,0); CString datestr; string s,sline; getline(fin,s); while(getline(fin,sline)) { istringstream ssin(sline); ssin>>s; while( s != datet.Format("%m/%d/%y").GetBuffer() ) { datet += COleDateTimeSpan(1,0,0,0); } for(int i=0;i<9;++i) { ssin>>s; } for(int i=0;i<9;++i) { ssin>>vals[i]; } insertDB("files/rain-temph.mdb","min_temph",datet,vals); datet += COleDateTimeSpan(1,0,0,0); } cout<<"数据处理完毕"<<endl; } bool read_from_db(const char *dbname,const char * sql_statement, double &val) { using namespace std; CDaoDatabase daoDb; COleVariant OleV1; daoDb.Open(dbname,0,0,";PWD=271828"); //打开数据库 CDaoRecordset Record(&daoDb); //构造记录集 Record.Open (dbOpenDynaset, sql_statement) ; //初始化记录集 if(!Record.IsOpen()) return false; if(Record.GetRecordCount()<1) return false; Record.MoveFirst(); Record.GetFieldValue(0,OleV1); val = OleV1.dblVal; daoDb.Close(); //关闭数据库 AfxDaoTerm(); // return true; } bool stat_day(std::string worker, CTime when, std::map<int, stat_result> & statis_result) { using namespace std; string filename = get_filename(worker.c_str(),when); if(filename.size()<1) return false; string filepath = "person-forcast/"+filename; ifstream fin(filepath.c_str()); if(!fin.is_open()) { cout<<"打开文件 "<<filename<<"失败!"<<endl; return false; } city_fst record_per_day; string sline; while(getline(fin,sline) ) { if(sline.size()<30) continue; record_per_day.time = when; read_city_fst(sline,record_per_day); analyse_record(record_per_day, statis_result); } return true; } bool analyse_record(const city_fst &record_per_day, std::map<int, stat_result> & statis_result ) { using namespace std; //extern string person_result_details_filename="log.txt"; ofstream fout(person_result_details_filename.c_str(),ios_base::out|ios_base::app); if(!fout.is_open()) { cout<<"打开文件 "<<person_result_details_filename<<" 失败!"<<endl; } CTime when = record_per_day.time; string time_str = when.Format("%Y-%m-%d日").GetBuffer(); int stn_num = record_per_day.station_num; if(!statis_result.count(stn_num)) return false; statis_result[stn_num].avail_days += 1; analyse_rain(record_per_day, statis_result, fout); analyse_min_temph(record_per_day, statis_result, fout); analyse_max_temph(record_per_day, statis_result, fout); fout.close(); return true; } //根据时间获取文件名 //…… 判断16时 4时…… std::string get_filename(CString floder, CTime when) { when -= CTimeSpan(0,8,0,0); CString search_name; search_name =floder+ "\\Z_SEVP_C_BFLB_"+when.Format("%Y%m%d%H")+"*_P_RFFC-SPCC-*.TXT"; CFileFind findf; BOOL isfind = findf.FindFile(search_name); CString filename; if(isfind) { findf.FindNextFileA(); filename = findf.GetFilePath(); } return filename.GetBuffer(); } //从rain-temph.mdb数据库中获取降水或温度值 bool get_rain_temph_val(int i, int stn, CTime tm, double & val) { using namespace std; std::string dbname="files/rain-temph.mdb", colname, sql_statement; std::string time_str = tm.Format("#%Y-%m-%d#").GetBuffer(); std::ostringstream sout; sout<<'v'<<stn; colname = sout.str(); switch(i) { case 1: time_str = tm.Format("#%Y-%m-%d %H:00:00#").GetBuffer(); sql_statement = "SELECT "+colname+" FROM rain_last12hour WHERE date = " + time_str; break; case 2: sql_statement = "SELECT "+colname+" FROM min_temph WHERE date = " + time_str; break; case 3: if(tm.GetHour() < 20) { tm -= CTimeSpan(1,0,0,0); time_str = tm.Format("#%Y-%m-%d#").GetBuffer(); } sql_statement = "SELECT "+colname+" FROM max_temph WHERE date = " + time_str; break; default: break; } bool returnval; try { returnval=read_from_db(dbname.c_str(),sql_statement.c_str(),val); } catch(CDaoException *e) { //cout<<(e->m_pErrorInfo->m_strDescription).GetBuffer()<<endl; e->Delete(); AfxDaoTerm(); // return false; } return returnval; } bool analyse_rain(const city_fst &record_per_day, std::map<int, stat_result> & statis_result, std::ofstream &fout) { using namespace std; CTime when = record_per_day.time; string time_str = when.Format("%Y-%m-%d").GetBuffer(); int stn_num = record_per_day.station_num; //处理降水预报 for(int add_times=0; add_times!=record_per_day.israin.size(); ++add_times) { double rainval=0; if(get_rain_temph_val(1,stn_num,when+CTimeSpan(0,12*(add_times+1),0,0),rainval)) { bool israinb = rainval > 0.01, israin = ( israinb || beql(rainval,0.001) );//包含微量降水 if(record_per_day.israin[add_times] || israinb) { statis_result[stn_num].rain_all[add_times] += 1; if(record_per_day.israin[add_times] && israin) { statis_result[stn_num].rain_right[add_times] += 1; } else if(israinb) { statis_result[stn_num].rain_miss[add_times] +=1; fout<<time_str<<' '<<stn_num<<' '<<12*(add_times+1)<<"小时降水 漏报"<<endl; } else { statis_result[stn_num].rain_empty[add_times] +=1; fout<<time_str<<' '<<stn_num<<' '<<12*(add_times+1)<<"小时降水 空报"<<endl; } } } } return true; } bool analyse_min_temph(const city_fst &record_per_day, std::map<int, stat_result> & statis_result, std::ofstream &fout) { using namespace std; CTime when = record_per_day.time; string time_str = when.Format("%Y-%m-%d").GetBuffer(); int stn_num = record_per_day.station_num; for(int add_days=0; add_days!=record_per_day.min_t.size(); ++add_days) { double min_temp=0; if(get_rain_temph_val(2,stn_num,when+CTimeSpan(0,24*(add_days+1),0,0),min_temp) ) { double f_min_t=record_per_day.min_t[add_days], difference = min_temp-f_min_t, abs_diff = abs(difference); if( abs_diff <2 || beql(abs_diff,2.0)) { statis_result[stn_num].min_t[add_days] += 1; } else if(difference > 0) { statis_result[stn_num].min_t_low[add_days] += 1; fout<<time_str<<' '<<stn_num<<' '<<24*(add_days+1)<<"最低温度 预报偏低: "; fout<<"预报值:"<<f_min_t<<" 实际值:"<<min_temp<<endl; } else { statis_result[stn_num].min_t_high[add_days] += 1; fout<<time_str<<' '<<stn_num<<' '<<24*(add_days+1)<<"最低温度 预报偏高: "; fout<<"预报值:"<<f_min_t<<" 实际值:"<<min_temp<<endl; } } } return true; } bool analyse_max_temph(const city_fst &record_per_day, std::map<int, stat_result> & statis_result, std::ofstream &fout) { using namespace std; CTime when = record_per_day.time; string time_str = when.Format("%Y-%m-%d").GetBuffer(); int stn_num = record_per_day.station_num; for(int add_days=0; add_days!=record_per_day.max_t.size(); ++add_days) { double max_temp=0; if(get_rain_temph_val(3,stn_num,when+CTimeSpan(0,24*(add_days+1),0,0),max_temp) ) { double f_max_t = record_per_day.max_t[add_days], difference = max_temp-f_max_t, abs_diff = abs(difference); if( abs_diff <2 || beql(abs_diff,2.0) ) { statis_result[stn_num].max_t[add_days] += 1; } else if(difference > 0) { statis_result[stn_num].max_t_low[add_days] += 1; fout<<time_str<<' '<<stn_num<<' '<<24*(add_days+1)<<"最高温度 预报偏低: "; fout<<"预报值:"<<f_max_t<<" 实际值:"<<max_temp<<endl; } else { statis_result[stn_num].max_t_high[add_days] += 1; fout<<time_str<<' '<<stn_num<<' '<<24*(add_days+1)<<"最高温度 预报偏高: "; fout<<"预报值:"<<f_max_t<<" 实际值:"<<max_temp<<endl; } } } return true; } //输出统计结果 void person_result_out(std::map<int, stat_result> & statis, std::string &result) { using namespace std; ostringstream sout; vector<int> stn, all, right, wrong1, wrong2, lastline; int i=0, width=10; //--------------------------------------------------------------------------------------- //------降水预报 sout<<"降水预报:\n\n"; sout<<" 站号 总降水次数 正确次数 空报次数 漏报次数 正确率(%)\n" "-----------------------------------------------------------------\n"; for(map<int, stat_result>::iterator it=statis.begin();it != statis.end(); ++it) { stn.push_back((*it).first); all.push_back(accumulate((*it).second.rain_all.begin(),(*it).second.rain_all.end(),0 )); right.push_back(accumulate((*it).second.rain_right.begin(),(*it).second.rain_right.end(),0 ) ); wrong1.push_back(accumulate((*it).second.rain_empty.begin(),(*it).second.rain_empty.end(),0 ) ); wrong2.push_back(accumulate((*it).second.rain_miss.begin(),(*it).second.rain_miss.end(),0 ) ); sout<<setw(width)<<stn[i]<<setw(width)<<all[i]<<setw(width)<<right[i] <<setw(width)<<wrong1[i]<<setw(width)<<wrong2[i]<<setw(width)<<right[i]*100.0/all[i]<<endl; ++i; } lastline.push_back(accumulate(all.begin(),all.end(),0 ) ); lastline.push_back(accumulate(right.begin(),right.end(),0 ) ); lastline.push_back(accumulate(wrong1.begin(),wrong1.end(),0) ); lastline.push_back(accumulate(wrong2.begin(),wrong2.end(),0) ); sout<<endl<<setw(width)<<"总计 "<<setw(width)<<lastline[0]<<setw(width)<<lastline[1]<<setw(width)<<lastline[2] <<setw(width)<<lastline[3]<<setw(width)<<lastline[1]*100.0/lastline[0]<<endl; //------------------------------------------------------------------------------------------------------- stn.resize(0); all = right = wrong1 = wrong2 = lastline = stn; i = 0; //----最高温度预报 sout<<"\n\n最高温度:\n\n"; sout<<" 站号 总预报次数 正确次数 偏高次数 偏低次数 正确率(%)\n" "-----------------------------------------------------------------\n"; for(map<int, stat_result>::iterator it=statis.begin();it != statis.end(); ++it) { stn.push_back((*it).first); all.push_back((*it).second.avail_days*2); right.push_back(accumulate((*it).second.max_t.begin(),(*it).second.max_t.end(),0 ) ); wrong1.push_back(accumulate((*it).second.max_t_high.begin(),(*it).second.max_t_high.end(),0 ) ); wrong2.push_back(accumulate((*it).second.max_t_low.begin(),(*it).second.max_t_low.end(),0 ) ); sout<<setw(width)<<stn[i]<<setw(width)<<all[i]<<setw(width)<<right[i] <<setw(width)<<wrong1[i]<<setw(width)<<wrong2[i]<<setw(width)<<right[i]*100.0/all[i]<<endl; ++i; } lastline.push_back(accumulate(all.begin(),all.end(),0 ) ); lastline.push_back(accumulate(right.begin(),right.end(),0 ) ); lastline.push_back(accumulate(wrong1.begin(),wrong1.end(),0) ); lastline.push_back(accumulate(wrong2.begin(),wrong2.end(),0) ); sout<<endl<<setw(width)<<"总计 "<<setw(width)<<lastline[0]<<setw(width)<<lastline[1]<<setw(width)<<lastline[2] <<setw(width)<<lastline[3]<<setw(width)<<lastline[1]*100.0/lastline[0]<<endl; //------------------------------------------------------------------------------------------- stn.resize(0); all = right = wrong1 = wrong2 = lastline = stn; i = 0; //----最低温度预报 sout<<"\n\n最低温度:\n\n" ; sout<<" 站号 总预报次数 正确次数 偏高次数 偏低次数 正确率(%)\n" "-----------------------------------------------------------------\n"; for(map<int, stat_result>::iterator it=statis.begin();it != statis.end(); ++it) { stn.push_back((*it).first); all.push_back((*it).second.avail_days*2); right.push_back(accumulate((*it).second.min_t.begin(),(*it).second.min_t.end(),0 ) ); wrong1.push_back(accumulate((*it).second.min_t_high.begin(),(*it).second.min_t_high.end(),0 ) ); wrong2.push_back(accumulate((*it).second.min_t_low.begin(),(*it).second.min_t_low.end(),0 ) ); sout<<setw(width)<<stn[i]<<setw(width)<<all[i]<<setw(width)<<right[i] <<setw(width)<<wrong1[i]<<setw(width)<<wrong2[i]<<setw(width)<<right[i]*100.0/all[i]<<endl; ++i; } lastline.push_back(accumulate(all.begin(),all.end(),0 ) ); lastline.push_back(accumulate(right.begin(),right.end(),0 ) ); lastline.push_back(accumulate(wrong1.begin(),wrong1.end(),0) ); lastline.push_back(accumulate(wrong2.begin(),wrong2.end(),0) ); sout<<endl<<setw(width)<<"总计 "<<setw(width)<<lastline[0]<<setw(width)<<lastline[1]<<setw(width)<<lastline[2] <<setw(width)<<lastline[3]<<setw(width)<<lastline[1]*100.0/lastline[0]<<endl; result = sout.str(); }
#include "FlacUtils.h" #include <boost/format.hpp> #include <QString> #ifdef PG_HAS_FLAC #include "FLAC++/decoder.h" namespace PticaGovorun { namespace details { static bool write_little_endian_uint16(FILE *f, FLAC__uint16 x) { return fputc(x, f) != EOF && fputc(x >> 8, f) != EOF; } class OurDecoder : public FLAC::Decoder::File { FLAC__uint64 total_samples = 0; unsigned sample_rate = 0; unsigned channels = 0; unsigned bps = 0; const char* statusMsg_ = nullptr; std::vector<short>& resultFrames_; public: OurDecoder(std::vector<short>& resultFrames) : resultFrames_(resultFrames) { } unsigned sampleRate() const { return sample_rate; } protected: virtual ::FLAC__StreamDecoderWriteStatus write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) override; virtual void metadata_callback(const ::FLAC__StreamMetadata *metadata) override; virtual void error_callback(::FLAC__StreamDecoderErrorStatus status) override; private: OurDecoder(const OurDecoder&); OurDecoder&operator=(const OurDecoder&); }; void OurDecoder::error_callback(::FLAC__StreamDecoderErrorStatus status) { fprintf(stderr, "Got error callback: %s\n", FLAC__StreamDecoderErrorStatusString[status]); } void OurDecoder::metadata_callback(const ::FLAC__StreamMetadata *metadata) { /* print some stats */ if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO) { /* save for later */ total_samples = metadata->data.stream_info.total_samples; sample_rate = metadata->data.stream_info.sample_rate; channels = metadata->data.stream_info.channels; bps = metadata->data.stream_info.bits_per_sample; // NOTE: printing to std::cout when Unicode is set up is an ERROR (see _setmode call in main) //fprintf(stderr, "sample rate : %u Hz\n", sample_rate); //fprintf(stderr, "channels : %u\n", channels); //fprintf(stderr, "bits per sample: %u\n", bps); //fprintf(stderr, "total samples : %" PRIu64 "\n", total_samples); auto allSamples = total_samples * channels; resultFrames_.reserve(allSamples); } } ::FLAC__StreamDecoderWriteStatus OurDecoder::write_callback(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) { const FLAC__uint32 total_size = (FLAC__uint32)(total_samples * channels * (bps / 8)); size_t i; if (total_samples == 0) { fprintf(stderr, "ERROR: this example only works for FLAC files that have a total_samples count in STREAMINFO\n"); return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; } if (channels != 1 || bps != 16) { statusMsg_ = "ERROR: this example only supports 16bit stereo streams"; return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; } /* write decoded PCM samples */ for (i = 0; i < frame->header.blocksize; i++) { // left channel short value = static_cast<short>(buffer[0][i]); resultFrames_.push_back(value); } return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } } PG_EXPORTS bool readAllSamplesFlac(const boost::filesystem::path& filePath, std::vector<short>& result, float *sampleRate, ErrMsgList* errMsg) { details::OurDecoder decoder(result); decoder.set_md5_checking(true); FLAC__StreamDecoderInitStatus init_status = decoder.init(filePath.string()); if (init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK) { if (errMsg != nullptr) { const char* msg = FLAC__StreamDecoderInitStatusString[init_status]; auto sub = std::make_unique<ErrMsgList>(); sub->utf8Msg = msg; errMsg->utf8Msg = "Can't initialize decoder"; errMsg->next = std::move(sub); } return false; } bool ok = decoder.process_until_end_of_stream(); if (!ok) { if (errMsg != nullptr) errMsg->utf8Msg = "decoder.process_until_end_of_stream() failed"; return false; } if (sampleRate != nullptr) *sampleRate = decoder.sampleRate(); return true; } } #endif
#pragma once #include <string.h> namespace Application { static const unsigned int WIDTH = 900; static const unsigned int HEIGHT = 600; static const unsigned int NUM_PIXELS_ELEMNTS = WIDTH * HEIGHT * 4; static unsigned char* data; static unsigned int time; void Init(); void Update(); void Close(); }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_INTERFACE_IBUFFER_H_ #define BAJKA_INTERFACE_IBUFFER_H_ #include <util/ReflectionMacros.h> #include <string> #include <core/Object.h> namespace Sound { class IBuffer : public Core::Object { public: d__ virtual ~IBuffer () {} m_ (setLoad) virtual void setLoad (std::string const &path) = 0; /** * Nazwa pod jaką ten bufor będzie dostepny dla źródeł. */ m_ (setName) virtual void setName (std::string const &name) = 0; virtual std::string const &getName () const = 0; /** * Zwraca dane bufora. */ virtual void const *getData () const = 0; virtual size_t getSize () const = 0; E_ (IBuffer) }; } /* namespace Sound */ #endif /* IBUFFER_H_ */
/* Copyright © 2006, Drollic All rights reserved. http://www.drollic.com Redistribution of this software in source or binary forms, with or without modification, is expressly prohibited. You may not reverse-assemble, reverse-compile, or otherwise reverse-engineer this software in any way. THIS SOFTWARE ("SOFTWARE") IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdafx.h" #include "SegmentedNativeMomentsPainter.h" #include "TwoDVector.h" #include "NativeStroke.h" #include "ComputationProgress.h" #include "SegmentedRegion.h" #include <math.h> #include <time.h> namespace com { namespace drollic { namespace graphics { namespace painting { namespace native { namespace processing { SegmentedNativeMomentsPainter::SegmentedNativeMomentsPainter(int width, int height, std::vector<FastRawImage*> &theOriginals, std::vector<FastRawImage*> &strokes, int S) : INativeMomentsPainter(width, height, S, strokes), originals(theOriginals) { } SegmentedNativeMomentsPainter::~SegmentedNativeMomentsPainter() { } FastRawImage* SegmentedNativeMomentsPainter::CreatePainting() { return CreateSegmentedPainting(); } FastRawImage* SegmentedNativeMomentsPainter::CreateSegmentedPainting() { unsigned int totalOriginals = originals.size(); float totalOriginalsf = static_cast<float>(totalOriginals); // Return if we somehow got no originals if (totalOriginals <= 0) { ComputationProgress::Instance()->percentComplete = 100; return NULL; } float percentWorkForAllImageAnalysis = 45.0; float percentWorkPerImage = percentWorkForAllImageAnalysis / totalOriginalsf; std::pair<int, int> zeroOffset(0, 0); // First, determine the segment size based upon int widthSum = 0; int heightSum = 0; for (unsigned int i=0; i < totalOriginals; i++) { widthSum += originals[i]->Width; heightSum += originals[i]->Height; } int segmentWidth = (widthSum / totalOriginals) / 4; int segmentHeight = (heightSum / totalOriginals) / 3; list<SegmentedRegion> regions; list<SegmentedRegion>::iterator regionsIter; // Seed random number generator srand(static_cast<unsigned int>(time(static_cast<time_t*>(NULL)))); for (unsigned int i=0; i < totalOriginals; i++) { SegmentedRegion region; region.SetDimensions(segmentWidth, segmentHeight, originals[i]->Width, originals[i]->Height); GeneratePaintingStrokes(originals[i], S, region, zeroOffset, percentWorkPerImage); // Generate the interesting segments which are basically above // a given percentile in terms of number of strokes double interestingSegmentBaseThreshold = 10.0; int interestingSegmentPossibleRange = 25; double interestingSegmentsAreAboveThisPercentile = interestingSegmentBaseThreshold + (rand() % interestingSegmentPossibleRange); regions.push_back(region.AboveThresholdSegments(interestingSegmentsAreAboveThisPercentile)); //std::cout << "Completed. Threshold was " << interestingSegmentsAreAboveThisPercentile << std::endl; } ComputationProgress::Instance()->percentComplete = 50; SegmentedRegion finalRegion; finalRegion.SetDimensions(segmentWidth, segmentHeight, width, height); for (regionsIter = regions.begin(); regionsIter != regions.end(); regionsIter++) { finalRegion.AttemptIncorporation(*regionsIter); } StrokeContainer *strokeContainer = finalRegion.UnifyStrokes(); // Render the image FastRawImage* painting = Render(*strokeContainer); // Final cleanup delete strokeContainer; return painting; } } } } } } }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 4e5 + 100; struct bit{ LL a,b; bit(LL _a = 0,LL _b = 0) { a = _a;b = _b; } void set1(int k) { a = b = 0; if (k >= 60) a = (LL)1 << (k-60); else b = (LL)1 << k; } bit operator |(bit rhs) { return bit(a|rhs.a,b|rhs.b); } int cnt(int m) { int ans = 0; for (int i = 1;i < min(60,m+1); i++) if (b&((LL)1 << i)) ans++; for (int i = 60;i <= m;i++) if (a&((LL)1 << (i-60))) ans++; return ans; } }; bit t[maxn],lazy[maxn]; void down(int l,int mid,int r,int k) { if (lazy[k].a || lazy[k].b) { lazy[k<<1] = t[k<<1] = lazy[k]; lazy[k<<1|1] = t[k<<1|1] = lazy[k]; lazy[k].a = lazy[k].b = 0; } } void build(int l,int r,int k) { if (l == r) { int loc;scanf("%d",&loc); t[k].set1(loc); return; } int mid = (l + r) >> 1; build(l,mid,k<<1); build(mid+1,r,k<<1|1); t[k] = t[k<<1]|t[k<<1|1]; } void updata(int l,int r,int k,int x,int y,int val) { if (x <= l && r <= y) { lazy[k].set1(val);t[k].set1(val); return; } int mid = (l + r) >> 1; down(l,mid,r,k); if (x <= mid) updata(l,mid,k<<1,x,y,val); if (y > mid) updata(mid+1,r,k<<1|1,x,y,val); t[k] = t[k<<1]|t[k<<1|1]; } bit query(int l,int r,int k,int x,int y) { //cout << l << " " << r << endl; if (x <= l && r <= y) return t[k]; int mid = (l + r) >> 1; bit ans; down(l,mid,r,k); if (x <= mid) ans = ans|query(l,mid,k<<1,x,y); if (y > mid) ans = ans|query(mid+1,r,k<<1|1,x,y); return ans; } int main() { int n,m,q;char ch; int x,y,val; scanf("%d%d",&n,&m); build(1,n,1); scanf("%d",&q); while (q--) { getchar();ch = getchar(); if (ch == 'Q') { scanf("%d%d",&x,&y); bit b = query(1,n,1,x,y); printf("%d\n",b.cnt(m)); } else { scanf("%d%d%d",&x,&y,&val); updata(1,n,1,x,y,val); } } return 0; }
#include <iostream> #include <vector> #include <stdlib.h> #include <algorithm> #define min(x, y) (x > y ? y : x) using namespace std; int main(){ int N; int T, A; int H[1000]; int TEMP[1000]; cin >> N; cin >> T >> A; for(int i = 0; i < N; i++) { int tmp; cin >> tmp; H[i] = tmp; } //calc temp*1000 int tempdifmin = 10000000; int ans = 1001; for(int i = 0; i < N; i++) { TEMP[i] = T*1000 - 6*H[i]; int tempdif = abs(TEMP[i] - A*1000); if (tempdifmin > tempdif){ ans = i + 1; tempdifmin = tempdif; } } cout << ans << endl; }
( English:'Swedish'; Native:'Svenska'; LangFile:'swedish.lang'; DicFile:'svenska.dic'; FlagID:'se'; Letters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,Ä,Å,Æ,Ö,Ü'; LetterCount:'8,2,1,5,7,2,3,2,5,1,3,5,3,6,5,2,0,8,8,8,3,2,0,1,1,1,2,2,0,2,0'; LetterValue:'1,4,8,1,1,3,2,2,1,7,2,1,2,1,2,4,0,1,1,1,4,3,0,8,7,10,3,4,0,4,0'; NumberOfJokers:2; ReadingDirection:rdLeftToRight; ExcludedCat:'1'; RulesValid:true; NumberOfLetters:7; NumberOfRandoms:0; TimeControl:2; TimeControlEnd:false; TimeControlBuy:true; TimePerGame:'1:00:00'; PenaltyValue:10; PenaltyCount:5; GameLostByTime:true; WordCheckMode:2; ChallengePenalty:10; ChallengeTime:20; //nothing about that issue is found in the rules, that's why this value has been chosen arbitrarily JokerExchange:false; ChangeIsPass:true; CambioSecco:false; SubstractLetters:true; AddLetters:true; JokerPenalty:0; NumberOfPasses:3; LimitExchange:7; EndBonus:0; ScrabbleBonus:50) {References: http://www.scrabbleforbundet.se/index.php?option=content&task=view&id=16&Itemid=39 http://www.scrabbleforbundet.se The booklet with the game rules which is included when you buy the Swedish edition of the board game. Comment: Where nothing is written about some issue in the tournament rules, the settings refer to the booklet with the game rules which is included when you buy the Swedish edition of the board game. - Current state of implementation in this *.inc file: 2012-08-10 }
// Fri Apr 29 11:54:22 EDT 2016 // Evan S Weinberg // C++ file for preconditioned CG inverter. // To do: // 1. Template to support float, double. #include <iostream> #include <cmath> #include <string> #include <sstream> #include <complex> #include <vector> #include "generic_vector.h" #include "generic_cg_flex_precond.h" using namespace std; // Based on Minv_phi_3d in fem.c // Solves lhs = A^(-1) rhs using flexibly preconditioned Conjugate gradient. // Defined in FLEXIBLE CONJUGATE GRADIENTS by YVAN NOTAY. // Currently implemented without truncation. // Uses the preconditioner given in precond_matrix_vector. inversion_info minv_vector_cg_flex_precond(double *phi, double *phi0, int size, int max_iter, double eps, void (*matrix_vector)(double*,double*,void*), void* extra_info, void (*precond_matrix_vector)(double*,double*,int,void*,inversion_verbose_struct*), void* precond_info, inversion_verbose_struct* verb) { // see http://en.wikipedia.org/wiki/Conjugate_gradient_method // Initialize vectors. double *r, *p, *Ap, *z, *Az; vector<double*> p_store, Ap_store; // Flexible CG requires explicit reorthogonalization against old search vectors. double alpha, beta_ij, rsq, bsqrt, truersq; int k,i,ii; inversion_info invif; // For preconditioning verbosity. inversion_verbose_struct verb_prec; shuffle_verbosity_precond(&verb_prec, verb); // Allocate memory. r = new double[size]; p = new double[size]; Ap = new double[size]; z = new double[size]; Az = new double[size]; // Initialize values. rsq = bsqrt = truersq = 0.0; // Zero vectors; zero<double>(r, size); zero<double>(z, size); zero<double>(p, size); zero<double>(Ap, size); zero<double>(Az, size); // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // 1. Compute r = b - Ax (*matrix_vector)(p, phi, extra_info); invif.ops_count++; for (i = 0; i < size; i++) { r[i] = phi0[i] - p[i]; } // 2. z = M^(-1) r (*precond_matrix_vector)(z, r, size, precond_info, &verb_prec); // 3. p_0 = z_0. copy<double>(p, z, size); // Compute Ap. zero<double>(Ap, size); (*matrix_vector)(Ap, p, extra_info); invif.ops_count++; // iterate till convergence for(k = 0; k< max_iter; k++) { // If we've hit here, push the latest p, Ap to storage. p_store.push_back(p); Ap_store.push_back(Ap); // 4. alpha = z dot r / p A p alpha = dot<double>(p, r, size)/dot<double>(p, Ap, size); // 5. phi = phi + alpha p // 6. r = r - alpha A p for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i]; r[i] = r[i] - alpha*Ap[i]; } // Exit if new residual is small enough rsq = norm2sq<double>(r, size); print_verbosity_resid(verb, "FPCG", k+1, invif.ops_count, sqrt(rsq)/bsqrt); if (sqrt(rsq) < eps*bsqrt || k==max_iter-1) { // printf("Final rsq = %g\n", rsqNew); break; } // 7. z = M^(-1) r zero<double>(z, size); (*precond_matrix_vector)(z, r, size, precond_info, &verb_prec); // 8. Compute Az. zero<double>(Az, size); (*matrix_vector)(Az, z, extra_info); invif.ops_count++; // 9. b_ij = -<p_i, z>/<p_i, A p_i>; // 10. p_{j+1} = z_{j+1} + sum_i=0^j b_ij p_i // 11. Ap_{j+1} = Az_{j+1} + sum_i=0^j b_ij Ap_i p = new double[size]; copy<double>(p, z, size); Ap = new double[size]; copy<double>(Ap, Az, size); for (ii = 0; ii <= k; ii++) { beta_ij = -dot<double>(Ap_store[ii], z, size)/dot<double>(p_store[ii], Ap_store[ii], size); for (i = 0; i < size; i++) { p[i] += beta_ij*p_store[ii][i]; Ap[i] += beta_ij*Ap_store[ii][i]; } } } if(k == max_iter-1) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; //return 0;// Failed convergence } else { invif.success = true; } k++; zero<double>(Ap, size); (*matrix_vector)(Ap,phi,extra_info); invif.ops_count++; for(i=0; i < size; i++) truersq += (Ap[i] - phi0[i])*(Ap[i] - phi0[i]); // Free all the things! delete[] r; delete[] p; delete[] Ap; delete[] z; delete[] Az; ii = p_store.size(); for (i = 0; i < ii-1; i++) // not sure why it's ii-1... { delete[] p_store[i]; delete[] Ap_store[i]; } print_verbosity_summary(verb, "FPCG", invif.success, k, invif.ops_count, sqrt(truersq)/bsqrt); invif.resSq = truersq; invif.iter = k; invif.name = "Flexibly Preconditioned CG"; return invif; // Convergence } // Solves lhs = A^(-1) rhs using flexibly preconditioned Conjugate gradient, // restarting after restart_freq. // This may be sloppy, but it works. inversion_info minv_vector_cg_flex_precond_restart(double *phi, double *phi0, int size, int max_iter, double res, int restart_freq, void (*matrix_vector)(double*,double*,void*), void* extra_info, void (*precond_matrix_vector)(double*,double*,int,void*,inversion_verbose_struct*), void* precond_info, inversion_verbose_struct* verb) { int iter; // counts total number of iterations. int ops_count; inversion_info invif; double truersq = 0.0; int i; double bsqrt = sqrt(norm2sq<double>(phi0, size)); stringstream ss; ss << "Flexibly Preconditioned Restarted CG(" << restart_freq << ")"; inversion_verbose_struct verb_rest; shuffle_verbosity_restart(&verb_rest, verb); iter = 0; ops_count = 0; do { invif = minv_vector_cg_flex_precond(phi, phi0, size, restart_freq, res, matrix_vector, extra_info, precond_matrix_vector, precond_info, &verb_rest); iter += invif.iter; ops_count += invif.ops_count; print_verbosity_restart(verb, ss.str(), iter, ops_count, sqrt(invif.resSq)/bsqrt); } while (iter < max_iter && invif.success == false && sqrt(invif.resSq)/bsqrt > res); double *Aphi = new double[size]; (*matrix_vector)(Aphi, phi, extra_info); ops_count++; for(i=0; i < size; i++) truersq += (Aphi[i] - phi0[i])*(Aphi[i] - phi0[i]); invif.resSq = truersq; delete[] Aphi; invif.iter = iter; invif.ops_count = ops_count; print_verbosity_summary(verb, ss.str(), invif.success, iter, invif.ops_count, sqrt(truersq)/bsqrt); invif.name = ss.str(); // invif.resSq is good. if (sqrt(invif.resSq)/bsqrt > res) { invif.success = false; } else { invif.success = true; } return invif; } inversion_info minv_vector_cg_flex_precond(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double eps, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, void (*precond_matrix_vector)(complex<double>*,complex<double>*,int,void*,inversion_verbose_struct*), void* precond_info, inversion_verbose_struct* verb) { // Initialize vectors. complex<double> *r, *p, *Ap, *z, *Az; vector<complex<double>*> p_store, Ap_store; // Flexible CG requires explicit reorthogonalization against old search vectors. complex<double> alpha, beta_ij; double rsq, bsqrt, truersq; int k,i,ii; inversion_info invif; // For preconditioning verbosity. inversion_verbose_struct verb_prec; shuffle_verbosity_precond(&verb_prec, verb); // Allocate memory. r = new complex<double>[size]; p = new complex<double>[size]; Ap = new complex<double>[size]; z = new complex<double>[size]; Az = new complex<double>[size]; // Initialize values. rsq = bsqrt = truersq = 0.0; // Zero vectors; zero<double>(r, size); zero<double>(z, size); zero<double>(p, size); zero<double>(Ap, size); zero<double>(Az, size); // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // 1. Compute r = b - Ax (*matrix_vector)(p, phi, extra_info); invif.ops_count++; for (i = 0; i < size; i++) { r[i] = phi0[i] - p[i]; } // 2. z = M^(-1) r (*precond_matrix_vector)(z, r, size, precond_info, &verb_prec); // 3. p_0 = z_0. copy<double>(p, z, size); // Compute Ap. zero<double>(Ap, size); (*matrix_vector)(Ap, p, extra_info); invif.ops_count++; // iterate till convergence for(k = 0; k< max_iter; k++) { // If we've hit here, push the latest p, Ap to storage. p_store.push_back(p); Ap_store.push_back(Ap); // 4. alpha = z dot r / p A p alpha = dot<double>(p, r, size)/dot<double>(p, Ap, size); // 5. phi = phi + alpha p // 6. r = r - alpha A p for (i = 0; i < size; i++) { phi[i] = phi[i] + alpha*p[i]; r[i] = r[i] - alpha*Ap[i]; } // Exit if new residual is small enough rsq = norm2sq<double>(r, size); print_verbosity_resid(verb, "FPCG", k+1, invif.ops_count, sqrt(rsq)/bsqrt); if (sqrt(rsq) < eps*bsqrt || k==max_iter-1) { // printf("Final rsq = %g\n", rsqNew); break; } // 7. z = M^(-1) r zero<double>(z, size); (*precond_matrix_vector)(z, r, size, precond_info, &verb_prec); // 8. Compute Az. zero<double>(Az, size); (*matrix_vector)(Az, z, extra_info); invif.ops_count++; // 9. b_ij = -<p_i, z>/<p_i, A p_i>; // 10. p_{j+1} = z_{j+1} + sum_i=0^j b_ij p_i // 11. Ap_{j+1} = Az_{j+1} + sum_i=0^j b_ij Ap_i p = new complex<double>[size]; copy<double>(p, z, size); Ap = new complex<double>[size]; copy<double>(Ap, Az, size); for (ii = 0; ii <= k; ii++) { beta_ij = -dot<double>(Ap_store[ii], z, size)/dot<double>(p_store[ii], Ap_store[ii], size); for (i = 0; i < size; i++) { p[i] += beta_ij*p_store[ii][i]; Ap[i] += beta_ij*Ap_store[ii][i]; } } } if(k == max_iter-1) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; //return 0;// Failed convergence } else { invif.success = true; } k++; zero<double>(Ap, size); (*matrix_vector)(Ap,phi,extra_info); invif.ops_count++; for(i=0; i < size; i++) truersq += real(conj(Ap[i] - phi0[i])*(Ap[i] - phi0[i])); // Free all the things! delete[] r; delete[] p; delete[] Ap; delete[] z; delete[] Az; ii = p_store.size(); for (i = 0; i < ii-1; i++) // not sure why it's ii-1... { delete[] p_store[i]; delete[] Ap_store[i]; } print_verbosity_summary(verb, "FPCG", invif.success, k, invif.ops_count, sqrt(truersq)/bsqrt); invif.resSq = truersq; invif.iter = k; invif.name = "Flexibly Preconditioned CG"; return invif; // Convergence } // Solves lhs = A^(-1) rhs using flexibly preconditioned Conjugate gradient, // restarting after restart_freq. // This may be sloppy, but it works. inversion_info minv_vector_cg_flex_precond_restart(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double res, int restart_freq, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, void (*precond_matrix_vector)(complex<double>*,complex<double>*,int,void*,inversion_verbose_struct*), void* precond_info, inversion_verbose_struct* verb) { int iter; // counts total number of iterations. int ops_count; inversion_info invif; double truersq = 0.0; int i; double bsqrt = sqrt(norm2sq<double>(phi0, size)); stringstream ss; ss << "Flexibly Preconditioned Restarted CG(" << restart_freq << ")"; inversion_verbose_struct verb_rest; shuffle_verbosity_restart(&verb_rest, verb); iter = 0; ops_count = 0; do { invif = minv_vector_cg_flex_precond(phi, phi0, size, restart_freq, res, matrix_vector, extra_info, precond_matrix_vector, precond_info, &verb_rest); iter += invif.iter; ops_count += invif.ops_count; print_verbosity_restart(verb, ss.str(), iter, ops_count, sqrt(invif.resSq)/bsqrt); } while (iter < max_iter && invif.success == false && sqrt(invif.resSq)/bsqrt > res); complex<double> *Aphi = new complex<double>[size]; (*matrix_vector)(Aphi, phi, extra_info); ops_count++; for(i=0; i < size; i++) truersq += real(conj(Aphi[i] - phi0[i])*(Aphi[i] - phi0[i])); invif.resSq = truersq; delete[] Aphi; print_verbosity_summary(verb, ss.str(), invif.success, iter, invif.ops_count, sqrt(truersq)/bsqrt); invif.iter = iter; invif.ops_count = ops_count; invif.name = ss.str(); // invif.resSq is good. if (sqrt(invif.resSq)/bsqrt > res) { invif.success = false; } else { invif.success = true; } return invif; }
// // Created by Nikita Kruk on 25.11.17. // #ifndef SPRAPPROXIMATEBAYESIANCOMPUTATION_PERIODICBOUNDARYCONDITIONSCONFIGURATION_HPP #define SPRAPPROXIMATEBAYESIANCOMPUTATION_PERIODICBOUNDARYCONDITIONSCONFIGURATION_HPP #include "../Definitions.hpp" #include "BoundaryConditionsConfiguration.hpp" #include "Vector2D.hpp" #include <vector> class PeriodicBoundaryConditionsConfiguration : public BoundaryConditionsConfiguration { public: PeriodicBoundaryConditionsConfiguration(Real x_size, Real y_size); ~PeriodicBoundaryConditionsConfiguration(); virtual void ClassAEffectiveParticleDistance(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy); virtual void ClassAEffectiveParticleDistance(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij); virtual void ClassBEffectiveParticleDistance_signed(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy); virtual void ClassBEffectiveParticleDistance_unsigned(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy); virtual void ClassBEffectiveParticleDistance_signed(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij); virtual void ClassBEffectiveParticleDistance_unsigned(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij); virtual void ClassCEffectiveParticleDistance_signed(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy); virtual void ClassCEffectiveParticleDistance_unsigned(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy); virtual void ClassCEffectiveParticleDistance_signed(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij); virtual void ClassCEffectiveParticleDistance_unsigned(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij); virtual void ApplyPeriodicBoundaryConditions(Real x, Real y, Real &x_pbc, Real &y_pbc); virtual void ApplyPeriodicBoundaryConditions(std::vector<Real> &system_state, int N); virtual void ApplyPeriodicBoundaryConditions(const Vector2D &r, Vector2D &r_pbc); }; #endif //SPRAPPROXIMATEBAYESIANCOMPUTATION_PERIODICBOUNDARYCONDITIONSCONFIGURATION_HPP
#pragma once #include <opencv2/core/mat.hpp> #include <iberbar/Poster/MathTypes.h> namespace iberbar { namespace Poster { // 安全绘制Mat,检查边界,不抛出异常 void SafeDrawMat( cv::Mat matSrc, cv::Mat matDest, const CRect2i& rcDest, const CColor4B* color = nullptr ); // 安全绘制Mat,检查边界,不抛出异常 void SafeDrawMat( cv::Mat matSrc, const CRect2i& rcSrc, cv::Mat matDest, const CRect2i& rcDest, const CColor4B* color = nullptr ); cv::Mat BuildMaskMat_Circle( int radius ); cv::Mat BuildMaskMat_RectangleWithCorners( const CSize2i& size, int cornerRadius ); } }
// O(NF^2) = O(n^3) dp where n <= 500 #include <iostream> using namespace std; int factory, layer, layers[600]; long long dist[600][600], recycle[600][600], produce[600][600]; long long dp_recycle[600][600], dp_produce[600][600]; // dp[layer][ball at which factory] int main(){ cin >> factory >> layer; for(int i = 0; i < factory; i++){ for(int j = 0; j < factory; j++) cin >> dist[i][j]; for(int j = 0; j < layer; j++){ cin >> produce[i][j]; if(produce[i][j] == -1) produce[i][j] = 1LL<<50; } for(int j = 0; j < layer; j++){ cin >> recycle[i][j]; if(recycle[i][j] == -1) recycle[i][j] = 1LL<<50; } } int n; cin >> n; for(int i = 0; i < n; i++){ cin >> layers[i]; layers[i]--; } // base case for(int i = 0; i < factory; i++){ // produce dp_produce[0][i] = produce[i][layers[0]]; // recycle dp_recycle[0][i] = recycle[i][layers[n-1]]; } // recurrence relation for(int l = 1; l < n; l++){ for(int f = 0; f < factory; f++){ // produce dp_produce[l][f] = 1LL<<50; for(int i = 0; i < factory; i++) dp_produce[l][f] = min(dp_produce[l][f], dist[i][f]+produce[f][layers[l]]+dp_produce[l-1][i]); // recycle dp_recycle[l][f] = 1LL<<50; for(int i = 0; i < factory; i++) dp_recycle[l][f] = min(dp_recycle[l][f], dist[i][f]+recycle[f][layers[n-l-1]]+dp_recycle[l-1][i]); } } long long produce_cost = 1LL<<50, recycle_cost = 1LL<<50; for(int i = 0; i < factory; i++){ produce_cost = min(produce_cost, dp_produce[n-1][i]); recycle_cost = min(recycle_cost, dp_recycle[n-1][i]); } cout << produce_cost+recycle_cost << endl; return 0; }