blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34 values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | text stringlengths 13 4.23M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
00c9e064407e701320a469797d37f4cc5463546d | C++ | Wagenod/Yandex_C_plus_plus_development | /white_belt/week 2/MoveStrings.cpp | UTF-8 | 593 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
void MoveStrings(vector<string>& source, vector<string>& destination){
for (string s: source){
destination.push_back(s);
}
source.clear();
}
int main(){
vector<string> s = {"world"};
vector<string> d = {"hello"};
MoveStrings(s, d);
cout << "печать вектора источника s" << endl;
for (auto w: s){
cout << w << endl;
}
cout << "печать вектора назначения d (куда копировали)" << endl;
for (auto w: d){
cout << w << endl;
}
return 0;
} | true |
7baff8cee78143d300b4aeb8bf6ff56f74c8c107 | C++ | qgolsteyn/CPP-Embedded-Application-Toolkit | /library/view/ButtonView.cpp | UTF-8 | 1,255 | 2.6875 | 3 | [] | no_license | #include "ButtonView.h"
#include "Log.h"
void ButtonView::onAttach() {
color = COLOR_BUTTON_DEFAULT;
focusedColor = COLOR_BUTTON_DEFAULT_FOCUSED;
View::addOnDownPressListener([](View* _view) -> int {
Log_Low("ButtonView", "On down press");
ButtonView* view = (ButtonView*) _view;
if(!view->focused) {
view->focused = 1;
view->invalidate();
}
return 1;
});
View::addOnUpPressListener([](View* _view) -> int {
Log_Low("ButtonView", "On up press");
ButtonView* view = (ButtonView*) _view;
if(view->focused) {
view->focused = 0;
view->invalidate();
}
return 1;
});
}
void ButtonView::onDraw(Canvas* canvas) {
if(focused) canvas->setFill(focusedColor);
else canvas->setFill(color);
canvas->setStroke(COLOR_BUTTON_DEFAULT_BORDER);
canvas->setBorderWidth(3);
canvas->drawRect(View::bounds->x1, View::bounds->y1, View::bounds->x2, View::bounds->y2);
//canvas.drawText((bounds->x1+bounds->x2)/2 - 5, (bounds->y1+bounds->y2)/2 - 7, text);
}
void ButtonView::setText(string text) {
ButtonView::text = text;
invalidate();
}
void ButtonView::setColour(int color) {
ButtonView::color = color;
invalidate();
}
void ButtonView::setFocusedColour(int color) {
ButtonView::focusedColor = color;
invalidate();
}
| true |
85f0033cb0aad9c08e0cce4838db141c68b07037 | C++ | intact-software-systems/cpp-software-patterns | /MicroMiddleware/ComponentManager.cpp | UTF-8 | 1,985 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "MicroMiddleware/ComponentManager.h"
#include "MicroMiddleware/ComponentBase.h"
namespace MicroMiddleware
{
ComponentManager* ComponentManager::componentManager_ = NULL;
ComponentManager::ComponentManager(string componentName)
: BaseLib::Thread(componentName)
, BaseLib::ObjectBase(componentName)
{
}
ComponentManager::~ComponentManager()
{
}
ComponentManager* ComponentManager::getOrCreate()
{
static Mutex staticMutex;
MutexLocker lock(&staticMutex);
if(ComponentManager::componentManager_ == NULL)
{
ComponentManager::componentManager_ = new ComponentManager();
ComponentManager::componentManager_->start();
}
return componentManager_;
}
void ComponentManager::run()
{
//IDEBUG() << "Component manager is up!" ;
while(true)
{
// do something!
sleep(1);
}
}
bool ComponentManager::AddComponent(ComponentBase *component)
{
MutexLocker lock(&mutex_);
if(mapIdComponent_.count(component->componentId() > 0))
{
IDEBUG() << "WARNING! Component " << component->componentId() << " already registered!";
return false;
}
mapIdComponent_[component->componentId()] = component;
//IDEBUG() << "Component " << component->componentId() << " " << component->componentName() << " started!" ;
return true;
}
bool ComponentManager::RemoveComponent(ComponentBase *component)
{
MutexLocker lock(&mutex_);
if(mapIdComponent_.count(component->componentId() <= 0))
{
IDEBUG() << "WARNING! Component " << component->componentId() << " already stopped!" ;
return false;
}
mapIdComponent_.erase(component->componentId());
IDEBUG() << "Component " << component->componentId() << " " << component->GetComponentName() << " stopped!" ;
return true;
}
ComponentBase* ComponentManager::GetComponent(ComponentId id)
{
MutexLocker lock(&mutex_);
if(mapIdComponent_.count((id) <= 0))
{
IDEBUG() << "WARNING! Component " << id << " not found!" ;
return NULL;
}
return mapIdComponent_[id];
}
}; // namespace MicroMiddleware
| true |
d547f0a611549edcbf51808dc99dfe39932006b3 | C++ | chen-san/PAT | /A1042有些点要注意下.cpp | GB18030 | 889 | 3.359375 | 3 | [] | no_license | //A1042
//Ųǰڸƹȥһβе仯ĹҲһ
//һǣڲУñŴ滨ɫҪźͻɫ֮ĶӦϵ
#include <cstdio>
int main(){
int start[55], end[55], shuff[55];
int n;
scanf("%d", &n);
for (int i = 1; i < 55; i++){
start[i] = i;
}
for (int i = 1; i < 55; i++){
scanf("%d", shuff + i);
}
for (int i = 0; i < n; i++){
for (int j = 1; j < 55; j++){
end[shuff[j]] = start[j];
}
for (int j = 1; j < 55; j++){
start[j] = end[j];
}
}
//źͻɫӦ
char huase[5] = { 'S', 'H', 'C', 'D', 'J' };
for (int i = 1; i < 55; i++){
printf("%c%d", huase[(start[i] - 1) / 13], (start[i] - 1) % 13 + 1);
if (i != 54)
printf(" ");
}
return 0;
} | true |
26ceb0cde2d1cb3ae005c8e8f2b22b1ac0423517 | C++ | ngsky/walker | /src/com/ngsky/walker/leetcode/n91/A.cpp | UTF-8 | 830 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
class Solution {
public:
int numDecodings(string s) {
int n=s.length();
if(n==0) return 0;
// dp[i]:前i个字符解密方式数量
int dp[n+1];
// 空串代表一种
dp[0]=1;
for(int i=1;i<=n;++i){
dp[i]=0;
int t=s[i-1]-'0';
if(t>=1 && t<=9){
dp[i]+=dp[i-1];
}
if(i>=2){
t=(s[i-2]-'0')*10+(s[i-1]-'0');
if(t>=10&&t<=26){
dp[i]+=dp[i-2];
}
}
}
return dp[n];
}
};
int main(){
string s;
cin >> s;
Solution so;
int res=so.numDecodings(s);
cout << res << endl;
return 0;
} | true |
4a43b125a7056e0f640d593670876166e923064f | C++ | KeremalpDurdabak/leetcode_solutions | /LC-1470.cpp | UTF-8 | 355 | 2.953125 | 3 | [] | no_license | class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> result;
int k = 0;
for(int i = 0; i< n; i++){
int x = n-(n-k);
int y = n+i;
result.push_back(nums.at(x));
result.push_back(nums.at(y));
k++;
}
return result;
}
}; | true |
ca382260dd2c1b16a2ef05d5ada8d18cd55f7555 | C++ | DangerInteractive/ArcticWolf | /src/GameStateManager.cpp | UTF-8 | 6,762 | 2.890625 | 3 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | #include "../include/GameStateManager.hpp"
void aw::GameStateManager::pushState (const std::shared_ptr<GameState>& state) {
m_states.push_back(state);
state->onPush();
state->onActivate();
if (m_states.size() > 1) {
auto prev = m_states[m_states.size() - 2];
prev->onDeactivate();
for (int i = m_states.size() - 2; i >= 0; --i) {
m_states[i]->onDescend();
}
}
refreshLiveStates();
}
void aw::GameStateManager::pushState (GameState* state) {
std::shared_ptr<GameState> ptrState(state);
pushState(ptrState);
}
bool aw::GameStateManager::pushState (const std::string& key) {
if (!GameStateStore::stateExists(key)) {
return false;
}
auto state = GameStateStore::getState(key);
pushState(state);
return true;
}
void aw::GameStateManager::dropState () {
auto top = m_states[m_states.size() - 1];
top->onDeactivate();
top->onPop();
top.reset();
if (m_states.size() > 0) {
auto top = m_states[m_states.size() - 1];
top->onActivate();
for (int i = m_states.size() - 1; i >= 0; --i) {
m_states[i]->onAscend();
}
}
refreshLiveStates();
}
std::shared_ptr<aw::GameState> aw::GameStateManager::popState () {
auto top = m_states[m_states.size() - 1];
top->onDeactivate();
top->onPop();
if (m_states.size() > 0) {
auto newTop = m_states[m_states.size() - 1];
newTop->onActivate();
for (int i = m_states.size() - 1; i >= 0; --i) {
m_states[i]->onAscend();
}
}
refreshLiveStates();
return top;
}
void aw::GameStateManager::refreshLiveStates () {
std::vector<std::shared_ptr<GameState>> liveRenderStates;
std::vector<std::shared_ptr<GameState>> liveUpdateStates;
std::vector<std::shared_ptr<GameState>> liveInputStates;
auto top = m_states[m_states.size() - 1];
liveRenderStates.push_back(top);
liveUpdateStates.push_back(top);
liveInputStates.push_back(top);
if (
m_states.size() > 1 &&
(
top->transparentRender ||
top->transparentUpdate ||
top->transparentInput
)
) {
auto prev = top;
bool renderBroken = !prev->transparentRender;
bool updateBroken = !prev->transparentUpdate;
bool inputBroken = !prev->transparentInput;
for (int i = m_states.size() - 2; i >= 0; --i) {
auto cur = m_states[i];
if (renderBroken && updateBroken && inputBroken) {
break;
}
if (prev->transparentRender) {
liveRenderStates.push_back(cur);
} else {
renderBroken = true;
}
if (prev->transparentUpdate) {
liveUpdateStates.push_back(cur);
} else {
updateBroken = true;
}
if (prev->transparentInput) {
liveInputStates.push_back(cur);
} else {
inputBroken = true;
}
prev = m_states[i];
}
}
m_statesLiveRender = liveRenderStates;
m_statesLiveUpdate = liveUpdateStates;
m_statesLiveInput = liveInputStates;
}
void aw::GameStateManager::clearWindow () {
for (int i = m_statesLiveRender.size() - 1; i >= 0; --i) {
m_statesLiveRender[i]->clearWindow();
}
}
void aw::GameStateManager::render (double deltaTime) {
for (int i = 0; i < m_statesLiveRender.size(); ++i) {
m_statesLiveRender[i]->render(deltaTime);
}
}
void aw::GameStateManager::update () {
for (int i = 0; i < m_statesLiveUpdate.size(); ++i) {
m_statesLiveUpdate[i]->update();
}
}
void aw::GameStateManager::loopInput () {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().loopCheck();
}
}
void aw::GameStateManager::keyPressCallback (sf::Keyboard::Key key, bool alt, bool control, bool shift) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onKeyPress(key, alt, control, shift);
}
}
void aw::GameStateManager::keyReleaseCallback (sf::Keyboard::Key key, bool alt, bool control, bool shift) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onKeyRelease(key, alt, control, shift);
}
}
void aw::GameStateManager::textCallback (sf::Uint32 character) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onText(character);
}
}
void aw::GameStateManager::cursorCallback (double xPos, double yPos) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onCursor(xPos, yPos);
}
}
void aw::GameStateManager::cursorInCallback () {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onCursorIn();
}
}
void aw::GameStateManager::cursorOutCallback () {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onCursorOut();
}
}
void aw::GameStateManager::focusCallback () {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onFocus();
}
}
void aw::GameStateManager::unfocusCallback () {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onUnfocus();
}
}
void aw::GameStateManager::mouseButtonPressCallback (int buttons, int x, int y) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onMouseButtonPress(buttons, x, y);
}
}
void aw::GameStateManager::mouseButtonReleaseCallback (int buttons, int x, int y) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onMouseButtonRelease(buttons, x, y);
}
}
void aw::GameStateManager::scrollCallback (double offset) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onScroll(offset);
}
}
void aw::GameStateManager::resizeCallback (int width, int height) {
for (int i = 0; i < m_statesLiveInput.size(); ++i) {
m_statesLiveInput[i]->getController().onResize(width, height);
}
}
std::vector<std::shared_ptr<aw::GameState>> aw::GameStateManager::m_states;
std::vector<std::shared_ptr<aw::GameState>> aw::GameStateManager::m_statesLiveRender;
std::vector<std::shared_ptr<aw::GameState>> aw::GameStateManager::m_statesLiveUpdate;
std::vector<std::shared_ptr<aw::GameState>> aw::GameStateManager::m_statesLiveInput;
| true |
2a4557fb8ccfb31cd811eddb6b57d242cee6ad78 | C++ | josefutbult-music/DigitalSynth | /Synth-test/Oscillator.cpp | UTF-8 | 2,548 | 3.46875 | 3 | [] | no_license | //
// Created by josef on 2019-06-26.
//
#include "Oscillator.h"
#include <vector>
#include <cstdlib>
#include <math.h>
#include <iostream>
#include <algorithm>
Oscillator::Oscillator(double frequency, int _length) {
// Generates an array for holding sinuids
sinusoid = new Sinusoid[length];
length = _length;
for(int i = 0; i < length; i++){
sinusoid[i].used = 0;
}
}
Oscillator::~Oscillator() {
delete sinusoid;
}
double Oscillator::generateSignal(double t) {
double result = 0;
for(int i = 0; i < length; i++){
if(!sinusoid[i].used){
break;
}
// Where the magic happens. The cosinus value of the frequency multiplied by the current time and
// offcet with the phase
result += sinusoid[i].amplitude * cos(sinusoid[i].frequency * 2.0 * M_PI * t + sinusoid[i].phase);
}
return result;
}
// Goes through the sinuid array and checks the used flag
int Oscillator::getZeroPosition(){
for(int zeroPosition = 0; zeroPosition < length; zeroPosition++ ){
if(!sinusoid[zeroPosition].used){
return zeroPosition;
}
}
}
void Oscillator::generateSawtoothWave(Sinusoid* model){
int zeroPosition = getZeroPosition();
// Appends sinuids to the sinuid array
for(int k = 1; k < 50; k++ ){
if(k >= length){
sinusoid[k + zeroPosition].used = 0;
}
else{
sinusoid[k + zeroPosition - 1].used = 1;
sinusoid[k + zeroPosition - 1].amplitude = (pow(-1, k) * 2.0 * model->amplitude) / ((double)k * M_PI);
sinusoid[k + zeroPosition - 1].frequency = k * model->frequency;
sinusoid[k + zeroPosition - 1].phase = M_PI / 2.0 + model->phase;
}
}
}
void Oscillator::generateSinusWave(Sinusoid* model){
int zeroPosition = getZeroPosition();
sinusoid[zeroPosition].used = 1;
sinusoid[zeroPosition].amplitude = model->amplitude;
sinusoid[zeroPosition].frequency = model->frequency;
sinusoid[zeroPosition].phase = model->phase;
}
void Oscillator::generateSquareWave(Sinusoid* model){
int zeroPosition = getZeroPosition();
for(int k = 1; k < 50; k++ ){
sinusoid[zeroPosition + k - 1].used = 1;
sinusoid[zeroPosition + k - 1].amplitude = (4.0 * model->amplitude) / (M_PI * (2.0 * k - 1.0));
sinusoid[zeroPosition + k - 1].frequency = (2.0 * k - 1.0) * model->frequency;
sinusoid[zeroPosition + k - 1].phase = (M_PI / 2.0) + model->phase;
}
} | true |
daaa8d34f57ce1d8d88d9a4aeddc79225d005c1a | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/boost/polygon/detail/voronoi_robust_fpt.hpp | UTF-8 | 14,746 | 2.828125 | 3 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | // Boost.Polygon library detail/voronoi_robust_fpt.hpp header file
// Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#ifndef BOOST_POLYGON_DETAIL_VORONOI_ROBUST_FPT
#define BOOST_POLYGON_DETAIL_VORONOI_ROBUST_FPT
#include <algorithm>
#include <cmath>
// Geometry predicates with floating-point variables usually require
// high-precision predicates to retrieve the correct result.
// Epsilon robust predicates give the result within some epsilon relative
// error, but are a lot faster than high-precision predicates.
// To make algorithm robust and efficient epsilon robust predicates are
// used at the first step. In case of the undefined result high-precision
// arithmetic is used to produce required robustness. This approach
// requires exact computation of epsilon intervals within which epsilon
// robust predicates have undefined value.
// There are two ways to measure an error of floating-point calculations:
// relative error and ULPs (units in the last place).
// Let EPS be machine epsilon, then next inequalities have place:
// 1 EPS <= 1 ULP <= 2 EPS (1), 0.5 ULP <= 1 EPS <= 1 ULP (2).
// ULPs are good for measuring rounding errors and comparing values.
// Relative errors are good for computation of general relative
// error of formulas or expressions. So to calculate epsilon
// interval within which epsilon robust predicates have undefined result
// next schema is used:
// 1) Compute rounding errors of initial variables using ULPs;
// 2) Transform ULPs to epsilons using upper bound of the (1);
// 3) Compute relative error of the formula using epsilon arithmetic;
// 4) Transform epsilon to ULPs using upper bound of the (2);
// In case two values are inside undefined ULP range use high-precision
// arithmetic to produce the correct result, else output the result.
// Look at almost_equal function to see how two floating-point variables
// are checked to fit in the ULP range.
// If A has relative error of r(A) and B has relative error of r(B) then:
// 1) r(A + B) <= max(r(A), r(B)), for A * B >= 0;
// 2) r(A - B) <= B*r(A)+A*r(B)/(A-B), for A * B >= 0;
// 2) r(A * B) <= r(A) + r(B);
// 3) r(A / B) <= r(A) + r(B);
// In addition rounding error should be added, that is always equal to
// 0.5 ULP or at most 1 epsilon. As you might see from the above formulas
// subtraction relative error may be extremely large, that's why
// epsilon robust comparator class is used to store floating point values
// and compute subtraction as the final step of the evaluation.
// For further information about relative errors and ULPs try this link:
// http://docs.sun.com/source/806-3568/ncg_goldberg.html
namespace boost {
namespace polygon {
namespace detail {
template <typename T>
T get_sqrt(const T& that) {
return (std::sqrt)(that);
}
template <typename T>
bool is_pos(const T& that) {
return that > 0;
}
template <typename T>
bool is_neg(const T& that) {
return that < 0;
}
template <typename T>
bool is_zero(const T& that) {
return that == 0;
}
template <typename _fpt>
class robust_fpt {
public:
typedef _fpt floating_point_type;
typedef _fpt relative_error_type;
// Rounding error is at most 1 EPS.
enum {
ROUNDING_ERROR = 1
};
robust_fpt() : fpv_(0.0), re_(0.0) {}
explicit robust_fpt(floating_point_type fpv) :
fpv_(fpv), re_(0.0) {}
robust_fpt(floating_point_type fpv, relative_error_type error) :
fpv_(fpv), re_(error) {}
floating_point_type fpv() const { return fpv_; }
relative_error_type re() const { return re_; }
relative_error_type ulp() const { return re_; }
bool has_pos_value() const {
return is_pos(fpv_);
}
bool has_neg_value() const {
return is_neg(fpv_);
}
bool has_zero_value() const {
return is_zero(fpv_);
}
robust_fpt operator-() const {
return robust_fpt(-fpv_, re_);
}
robust_fpt& operator+=(const robust_fpt& that) {
floating_point_type fpv = this->fpv_ + that.fpv_;
if ((!is_neg(this->fpv_) && !is_neg(that.fpv_)) ||
(!is_pos(this->fpv_) && !is_pos(that.fpv_))) {
this->re_ = (std::max)(this->re_, that.re_) + ROUNDING_ERROR;
} else {
floating_point_type temp =
(this->fpv_ * this->re_ - that.fpv_ * that.re_) / fpv;
if (is_neg(temp))
temp = -temp;
this->re_ = temp + ROUNDING_ERROR;
}
this->fpv_ = fpv;
return *this;
}
robust_fpt& operator-=(const robust_fpt& that) {
floating_point_type fpv = this->fpv_ - that.fpv_;
if ((!is_neg(this->fpv_) && !is_pos(that.fpv_)) ||
(!is_pos(this->fpv_) && !is_neg(that.fpv_))) {
this->re_ = (std::max)(this->re_, that.re_) + ROUNDING_ERROR;
} else {
floating_point_type temp =
(this->fpv_ * this->re_ + that.fpv_ * that.re_) / fpv;
if (is_neg(temp))
temp = -temp;
this->re_ = temp + ROUNDING_ERROR;
}
this->fpv_ = fpv;
return *this;
}
robust_fpt& operator*=(const robust_fpt& that) {
this->re_ += that.re_ + ROUNDING_ERROR;
this->fpv_ *= that.fpv_;
return *this;
}
robust_fpt& operator/=(const robust_fpt& that) {
this->re_ += that.re_ + ROUNDING_ERROR;
this->fpv_ /= that.fpv_;
return *this;
}
robust_fpt operator+(const robust_fpt& that) const {
floating_point_type fpv = this->fpv_ + that.fpv_;
relative_error_type re;
if ((!is_neg(this->fpv_) && !is_neg(that.fpv_)) ||
(!is_pos(this->fpv_) && !is_pos(that.fpv_))) {
re = (std::max)(this->re_, that.re_) + ROUNDING_ERROR;
} else {
floating_point_type temp =
(this->fpv_ * this->re_ - that.fpv_ * that.re_) / fpv;
if (is_neg(temp))
temp = -temp;
re = temp + ROUNDING_ERROR;
}
return robust_fpt(fpv, re);
}
robust_fpt operator-(const robust_fpt& that) const {
floating_point_type fpv = this->fpv_ - that.fpv_;
relative_error_type re;
if ((!is_neg(this->fpv_) && !is_pos(that.fpv_)) ||
(!is_pos(this->fpv_) && !is_neg(that.fpv_))) {
re = (std::max)(this->re_, that.re_) + ROUNDING_ERROR;
} else {
floating_point_type temp =
(this->fpv_ * this->re_ + that.fpv_ * that.re_) / fpv;
if (is_neg(temp))
temp = -temp;
re = temp + ROUNDING_ERROR;
}
return robust_fpt(fpv, re);
}
robust_fpt operator*(const robust_fpt& that) const {
floating_point_type fpv = this->fpv_ * that.fpv_;
relative_error_type re = this->re_ + that.re_ + ROUNDING_ERROR;
return robust_fpt(fpv, re);
}
robust_fpt operator/(const robust_fpt& that) const {
floating_point_type fpv = this->fpv_ / that.fpv_;
relative_error_type re = this->re_ + that.re_ + ROUNDING_ERROR;
return robust_fpt(fpv, re);
}
robust_fpt sqrt() const {
return robust_fpt(get_sqrt(fpv_),
re_ * static_cast<relative_error_type>(0.5) +
ROUNDING_ERROR);
}
private:
floating_point_type fpv_;
relative_error_type re_;
};
template <typename T>
robust_fpt<T> get_sqrt(const robust_fpt<T>& that) {
return that.sqrt();
}
template <typename T>
bool is_pos(const robust_fpt<T>& that) {
return that.has_pos_value();
}
template <typename T>
bool is_neg(const robust_fpt<T>& that) {
return that.has_neg_value();
}
template <typename T>
bool is_zero(const robust_fpt<T>& that) {
return that.has_zero_value();
}
// robust_dif consists of two not negative values: value1 and value2.
// The resulting expression is equal to the value1 - value2.
// Subtraction of a positive value is equivalent to the addition to value2
// and subtraction of a negative value is equivalent to the addition to
// value1. The structure implicitly avoids difference computation.
template <typename T>
class robust_dif {
public:
robust_dif() :
positive_sum_(0),
negative_sum_(0) {}
explicit robust_dif(const T& value) :
positive_sum_((value > 0)?value:0),
negative_sum_((value < 0)?-value:0) {}
robust_dif(const T& pos, const T& neg) :
positive_sum_(pos),
negative_sum_(neg) {}
T dif() const {
return positive_sum_ - negative_sum_;
}
T pos() const {
return positive_sum_;
}
T neg() const {
return negative_sum_;
}
robust_dif<T> operator-() const {
return robust_dif(negative_sum_, positive_sum_);
}
robust_dif<T>& operator+=(const T& val) {
if (!is_neg(val))
positive_sum_ += val;
else
negative_sum_ -= val;
return *this;
}
robust_dif<T>& operator+=(const robust_dif<T>& that) {
positive_sum_ += that.positive_sum_;
negative_sum_ += that.negative_sum_;
return *this;
}
robust_dif<T>& operator-=(const T& val) {
if (!is_neg(val))
negative_sum_ += val;
else
positive_sum_ -= val;
return *this;
}
robust_dif<T>& operator-=(const robust_dif<T>& that) {
positive_sum_ += that.negative_sum_;
negative_sum_ += that.positive_sum_;
return *this;
}
robust_dif<T>& operator*=(const T& val) {
if (!is_neg(val)) {
positive_sum_ *= val;
negative_sum_ *= val;
} else {
positive_sum_ *= -val;
negative_sum_ *= -val;
swap();
}
return *this;
}
robust_dif<T>& operator*=(const robust_dif<T>& that) {
T positive_sum = this->positive_sum_ * that.positive_sum_ +
this->negative_sum_ * that.negative_sum_;
T negative_sum = this->positive_sum_ * that.negative_sum_ +
this->negative_sum_ * that.positive_sum_;
positive_sum_ = positive_sum;
negative_sum_ = negative_sum;
return *this;
}
robust_dif<T>& operator/=(const T& val) {
if (!is_neg(val)) {
positive_sum_ /= val;
negative_sum_ /= val;
} else {
positive_sum_ /= -val;
negative_sum_ /= -val;
swap();
}
return *this;
}
private:
void swap() {
(std::swap)(positive_sum_, negative_sum_);
}
T positive_sum_;
T negative_sum_;
};
template<typename T>
robust_dif<T> operator+(const robust_dif<T>& lhs,
const robust_dif<T>& rhs) {
return robust_dif<T>(lhs.pos() + rhs.pos(), lhs.neg() + rhs.neg());
}
template<typename T>
robust_dif<T> operator+(const robust_dif<T>& lhs, const T& rhs) {
if (!is_neg(rhs)) {
return robust_dif<T>(lhs.pos() + rhs, lhs.neg());
} else {
return robust_dif<T>(lhs.pos(), lhs.neg() - rhs);
}
}
template<typename T>
robust_dif<T> operator+(const T& lhs, const robust_dif<T>& rhs) {
if (!is_neg(lhs)) {
return robust_dif<T>(lhs + rhs.pos(), rhs.neg());
} else {
return robust_dif<T>(rhs.pos(), rhs.neg() - lhs);
}
}
template<typename T>
robust_dif<T> operator-(const robust_dif<T>& lhs,
const robust_dif<T>& rhs) {
return robust_dif<T>(lhs.pos() + rhs.neg(), lhs.neg() + rhs.pos());
}
template<typename T>
robust_dif<T> operator-(const robust_dif<T>& lhs, const T& rhs) {
if (!is_neg(rhs)) {
return robust_dif<T>(lhs.pos(), lhs.neg() + rhs);
} else {
return robust_dif<T>(lhs.pos() - rhs, lhs.neg());
}
}
template<typename T>
robust_dif<T> operator-(const T& lhs, const robust_dif<T>& rhs) {
if (!is_neg(lhs)) {
return robust_dif<T>(lhs + rhs.neg(), rhs.pos());
} else {
return robust_dif<T>(rhs.neg(), rhs.pos() - lhs);
}
}
template<typename T>
robust_dif<T> operator*(const robust_dif<T>& lhs,
const robust_dif<T>& rhs) {
T res_pos = lhs.pos() * rhs.pos() + lhs.neg() * rhs.neg();
T res_neg = lhs.pos() * rhs.neg() + lhs.neg() * rhs.pos();
return robust_dif<T>(res_pos, res_neg);
}
template<typename T>
robust_dif<T> operator*(const robust_dif<T>& lhs, const T& val) {
if (!is_neg(val)) {
return robust_dif<T>(lhs.pos() * val, lhs.neg() * val);
} else {
return robust_dif<T>(-lhs.neg() * val, -lhs.pos() * val);
}
}
template<typename T>
robust_dif<T> operator*(const T& val, const robust_dif<T>& rhs) {
if (!is_neg(val)) {
return robust_dif<T>(val * rhs.pos(), val * rhs.neg());
} else {
return robust_dif<T>(-val * rhs.neg(), -val * rhs.pos());
}
}
template<typename T>
robust_dif<T> operator/(const robust_dif<T>& lhs, const T& val) {
if (!is_neg(val)) {
return robust_dif<T>(lhs.pos() / val, lhs.neg() / val);
} else {
return robust_dif<T>(-lhs.neg() / val, -lhs.pos() / val);
}
}
// Used to compute expressions that operate with sqrts with predefined
// relative error. Evaluates expressions of the next type:
// sum(i = 1 .. n)(A[i] * sqrt(B[i])), 1 <= n <= 4.
template <typename _int, typename _fpt, typename _converter>
class robust_sqrt_expr {
public:
enum MAX_RELATIVE_ERROR {
MAX_RELATIVE_ERROR_EVAL1 = 4,
MAX_RELATIVE_ERROR_EVAL2 = 7,
MAX_RELATIVE_ERROR_EVAL3 = 16,
MAX_RELATIVE_ERROR_EVAL4 = 25
};
// Evaluates expression (re = 4 EPS):
// A[0] * sqrt(B[0]).
_fpt eval1(_int* A, _int* B) {
_fpt a = convert(A[0]);
_fpt b = convert(B[0]);
return a * get_sqrt(b);
}
// Evaluates expression (re = 7 EPS):
// A[0] * sqrt(B[0]) + A[1] * sqrt(B[1]).
_fpt eval2(_int* A, _int* B) {
_fpt a = eval1(A, B);
_fpt b = eval1(A + 1, B + 1);
if ((!is_neg(a) && !is_neg(b)) ||
(!is_pos(a) && !is_pos(b)))
return a + b;
return convert(A[0] * A[0] * B[0] - A[1] * A[1] * B[1]) / (a - b);
}
// Evaluates expression (re = 16 EPS):
// A[0] * sqrt(B[0]) + A[1] * sqrt(B[1]) + A[2] * sqrt(B[2]).
_fpt eval3(_int* A, _int* B) {
_fpt a = eval2(A, B);
_fpt b = eval1(A + 2, B + 2);
if ((!is_neg(a) && !is_neg(b)) ||
(!is_pos(a) && !is_pos(b)))
return a + b;
tA[3] = A[0] * A[0] * B[0] + A[1] * A[1] * B[1] - A[2] * A[2] * B[2];
tB[3] = 1;
tA[4] = A[0] * A[1] * 2;
tB[4] = B[0] * B[1];
return eval2(tA + 3, tB + 3) / (a - b);
}
// Evaluates expression (re = 25 EPS):
// A[0] * sqrt(B[0]) + A[1] * sqrt(B[1]) +
// A[2] * sqrt(B[2]) + A[3] * sqrt(B[3]).
_fpt eval4(_int* A, _int* B) {
_fpt a = eval2(A, B);
_fpt b = eval2(A + 2, B + 2);
if ((!is_neg(a) && !is_neg(b)) ||
(!is_pos(a) && !is_pos(b)))
return a + b;
tA[0] = A[0] * A[0] * B[0] + A[1] * A[1] * B[1] -
A[2] * A[2] * B[2] - A[3] * A[3] * B[3];
tB[0] = 1;
tA[1] = A[0] * A[1] * 2;
tB[1] = B[0] * B[1];
tA[2] = A[2] * A[3] * -2;
tB[2] = B[2] * B[3];
return eval3(tA, tB) / (a - b);
}
private:
_int tA[5];
_int tB[5];
_converter convert;
};
} // detail
} // polygon
} // boost
#endif // BOOST_POLYGON_DETAIL_VORONOI_ROBUST_FPT
| true |
f8d78f3fc83615e60953659cb3d1a7c5a3e289c8 | C++ | RosinaGeorgieva/ObjectOrientedProgramming2021 | /Practicum/week 5/решения на самостоятелна работа/2/Rectangle.h | UTF-8 | 333 | 2.921875 | 3 | [] | no_license | #include <fstream>
#pragma once
struct Rectangle {
private:
double mA;
double mB;
public:
void initialize(double a, double b);
void print() const;
double enclosingCircleRadius() const;
double area() const;
double perimeter() const;
void readBinary(std::istream& in);
void writeBinary(std::ostream& out);
}; | true |
01be4b0ce9678af3ee09c24e26e5906f300a81b7 | C++ | GhulamMustafaGM/C-Programming | /03-C++ Programing/50.cpp | UTF-8 | 458 | 3.84375 | 4 | [] | no_license | // An interesting benefits from implicity constructor conversion
#include <iostream>
using namespace std;
class myclass
{
int num;
public:
myclass(int i) { num = i; }
int getnum() { return num; }
};
int main()
{
myclass o(10);
cout << o.getnum() << endl; // displays 10
// now, use implicity conversion to assign new value
o = 1000;
cout << o.getnum() << endl; // displays 1000
return 0;
}
/* Output:
10
1000
*/ | true |
4639d6ef8f19528f2b5ea68c7f73274d93bb1e74 | C++ | Peque/micromouse-maze | /libMaze/maze.h | UTF-8 | 9,582 | 2.625 | 3 | [
"MIT"
] | permissive | /************************************************************************
*
* Copyright (C) 2017 by Peter Harrison. www.micromouseonline.com
*
* 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 l> imitation 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.
*
************************************************************************/
#ifndef _maze_h
#define _maze_h
#include <cstdint>
#include "mazeconstants.h"
#include "floodinfo.h"
#include "priorityqueue.h"
class Maze {
public:
explicit Maze(uint16_t width);
enum FloodType {
MANHATTAN_FLOOD,
WEIGHTED_FLOOD,
RUNLENGTH_FLOOD,
DIRECTION_FLOOD
};
/// the maze is assumed to be square
uint16_t width() const; ///
uint16_t numCells(); ///
/// reset the wall, cost and direction data to defaults
void clearData();
/// clear the data and then set all the walls that exist in an empty maze
void resetToEmptyMaze(); ///
/// Clear the costs and directions and then copy the walls from an array
void copyMazeFromFileData(const uint8_t *wallData, uint16_t cellCount);
/// return the column number of given cell
inline uint16_t col(uint16_t cell) {
return cell / mWidth;
}
/// return the roww number of a given cell
inline uint16_t row(uint16_t cell) {
return cell % mWidth;
}
/// return the address of the cell ahead from this cardinal direction
static uint8_t ahead(uint8_t direction);
/// return the address of the cell on the right of this cardinal direction
static uint8_t rightOf(uint8_t direction);
/// return the address of the cell on the left of this cardinal direction
static uint8_t leftOf(uint8_t direction);
/// return the address of the cell behind this cardinal direction
static uint8_t behind(uint8_t direction);
/// return the address of the cell opposite the given wall
static uint8_t opposite(uint8_t direction);
static uint8_t differenceBetween(uint8_t oldDirection, uint8_t newDirection);
// static functions about neighbours
/// return the address of the cell in the indicated direction
uint16_t cellNorth(uint16_t cell);
/// return the address of the cell in the indicated direction
uint16_t cellEast(uint16_t cell);
/// return the address of the cell in the indicated direction
uint16_t cellSouth(uint16_t cell);
/// return the address of the cell in the indicated direction
uint16_t cellWest(uint16_t cell);
/// return the address of the cell in the given direction
uint16_t neighbour(uint16_t cell, uint16_t direction);
/// return the address of the home cell. Nearly always cell zero
uint16_t home();
/// return the cell address of the current goal
uint16_t goal();
/// set the current goal to a new value
void setGoal(uint16_t goal);
/// return the state of the four walls surrounding a given cell
uint8_t walls(uint16_t cell) const;
uint8_t internalWalls(uint16_t cell) const;
/// test whether a wall in a given direction has been observed
bool isSeen(uint16_t cell, uint8_t direction);
/// test for the absence of a wall. Don't care if it is seen or not
bool hasExit(uint16_t cell, uint8_t direction);
/// test for the presence of a wall. Don't care if it is seen or not
bool hasWall(uint16_t cell, uint8_t direction);
/// it is not clear that these two mthods have any actual use
/// test for the definite, observed absence of a wall.
bool hasRealExit(uint16_t cell, uint8_t direction);
/// test for the definite, observed presence of a wall.
bool hasRealWall(uint16_t cell, uint8_t direction);
/// return the stored direction for the given cell
uint8_t direction(uint16_t cell);
/// set the direction for the given cell
void setDirection(uint16_t cell, uint8_t direction);
/// test to see if all the walls of a given cell have been seen
bool isVisited(uint16_t cell);
/// set a cell as having all the walls seen
void setVisited(uint16_t cell);
/// set a cell as having none of the walls seen
void clearVisited(uint16_t cell);
/// NOT TO BE USED IN SEARCH. Unconditionally set a wall in a cell and mark as seen.
void setWall(uint16_t cell, uint8_t direction);
/// NOT TO BE USED IN SEARCH. Unconditionally clear a wall in a cell and mark as seen.
void clearWall(uint16_t cell, uint8_t direction);
/// NOT TO BE USED IN SEARCH. Update a single cell from stored map data.
void copyCellFromFileData(uint16_t cell, uint8_t wallData);
/// USE THIS FOR SEARCH. Update a single cell with wall data (normalised for direction)
void updateMap(uint16_t cell, uint8_t wallData);
/// Set all unseen walls as present. This is the closed maze used to test for a solution
void setUnknowns();
/// Set all unseen walls as present. This is the open maze used for path generation
void clearUnknowns();
/// return the cost value for a given cell. Used in flooding and searching
uint16_t cost(uint16_t cell);
/// return the cost in the neighbouring cell in the given direction
uint16_t cost(uint16_t cell, uint16_t direction);
/// return the cost in the neighbouring cell to the North
uint16_t costNorth(uint16_t cell);
/// return the cost in the neighbouring cell to the East
uint16_t costEast(uint16_t cell);
/// return the cost in the neighbouring cell to the South
uint16_t costSouth(uint16_t cell);
/// return the cost in the neighbouring cell to the West
uint16_t costWest(uint16_t cell);
/// set the cost in the given cell.
void setCost(uint16_t cell, uint16_t cost); ///
/// examine the goal area and move the goal if needed for a better entry speed
void recalculateGoal();
/// return the cost of the current best path assuming unknowns are absent
uint16_t openMazeCost() const;
/// return the cost of the current best path assuming unknowns are present
uint16_t closedMazeCost() const;
/// return the difference between the open and closed cost. Zero when the best route is found.
int32_t costDifference();
/// flood the maze for the give goal
uint16_t flood(uint16_t target);
/// RunLengthFlood is a specific kind of flood used in this mouse
uint16_t runLengthFlood(uint16_t target);
/// manhattanFlood is a the simplest kind of flood used in this mouse
uint16_t manhattanFlood(uint16_t target);
/// weightedFlood assigns a penalty to turns vs straights
uint16_t weightedFlood(uint16_t target);
/// directionFlood does not care about costs, only using direction pointers
uint16_t directionFlood(uint16_t target);
// TODO: is the closed maze needed? is it enough to see if the path has unvisited cells?
/// Flood the maze both open and closed and then test the cost difference
/// leaves the maze with unknowns clear
bool testForSolution();
/// returns the result of the most recent test for a solution
bool isSolved();
/// return the direction from the given cell to the least costly neighbour
uint8_t directionToSmallest(uint16_t cell);
/// for every cell in the maze, calculate and store the least costly direction
void updateDirections();
/// save the wall data, including visited flags in the target array. Not checked for overflow.
void save(uint8_t *data);
/// load the wall data, including visited flags from the target array. Not checked for overflow.
void load(const uint8_t *data);
/// set the Flood Type to use
void setFloodType(FloodType mFloodType);
/// used only for the weighted Flood
uint16_t getCornerWeight() const;
void setCornerWeight(uint16_t cornerWeight);
protected:
/// the width of the maze in cells. Assume mazes are always square
uint16_t mWidth;
/// stores the wall and visited flags. Allows for 32x32 maze but wastes space
uint8_t mWalls[1024];
/// stores the least costly direction. Allows for 32x32 maze but wastes space
uint8_t mDirection[1024];
/// stores the cost information from a flood. Allows for 32x32 maze but wastes space
uint16_t mCost[1024];
/// the current goal as defined by the conetst rules
uint16_t mGoal;
/// The cost of the best path assuming unseen walls are absent
uint16_t mPathCostOpen;
/// The cost of the best path assuming unseen walls are present
uint16_t mPathCostClosed;
/// flag set when maze has been solved
bool mIsSolved;
/// Remember which type of flood is to be used
FloodType mFloodType;
/// the weighted flood needs a cost for corners
uint16_t mCornerWeight;
/// used to set up the queue before running the more complex floods
void seedQueue(PriorityQueue<FloodInfo> &queue, uint16_t goal, uint16_t cost);
/// set all the cell costs to their maxumum value, except the target
void initialiseFloodCosts(uint16_t target);
};
#endif
| true |
5d8272358bb99eeae8bdbfb5aaa5330f64619a66 | C++ | zeos/signalflow | /source/src/node/envelope/envelope.cpp | UTF-8 | 3,966 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "signalflow/core/graph.h"
#include "signalflow/node/envelope/envelope.h"
#include <limits>
namespace signalflow
{
Envelope::Envelope(std::vector<NodeRef> levels,
std::vector<NodeRef> times,
std::vector<NodeRef> curves,
NodeRef clock,
bool loop)
: levels(levels), times(times), curves(curves), clock(clock), loop(loop)
{
this->level = std::numeric_limits<float>::max();
this->node_index = 0;
this->node_phase = 0.0;
this->set_channels(1, 1);
if (levels.size() < 2 || times.size() < 1 || (levels.size() != times.size() + 1))
{
throw std::runtime_error("Invalid levels/times combination");
}
if (curves.size() > 0 && curves.size() != times.size())
{
throw std::runtime_error("Invalid curves/times combination");
}
this->name = "envelope";
for (size_t i = 0; i < levels.size(); i++)
{
std::string input_name = "levels" + std::to_string(i);
this->create_input(input_name, this->levels[i]);
}
for (size_t i = 0; i < times.size(); i++)
{
std::string input_name = "times" + std::to_string(i);
this->create_input(input_name, this->times[i]);
}
for (size_t i = 0; i < curves.size(); i++)
{
std::string input_name = "curves" + std::to_string(i);
this->create_input(input_name, this->curves[i]);
}
this->create_input("clock", this->clock);
/*--------------------------------------------------------------------------------
* If no clock signal is specified, trigger immediately.
* If a clock is specified, don't trigger until a trigger is received.
*-------------------------------------------------------------------------------*/
if (clock)
{
this->state = SIGNALFLOW_NODE_STATE_STOPPED;
}
else
{
this->state = SIGNALFLOW_NODE_STATE_ACTIVE;
}
}
void Envelope::trigger(std::string name, float value)
{
if (name == SIGNALFLOW_DEFAULT_TRIGGER)
{
this->level = std::numeric_limits<float>::max();
this->node_index = 0;
this->node_phase = 0;
this->state = SIGNALFLOW_NODE_STATE_ACTIVE;
}
}
void Envelope::process(Buffer &out, int num_frames)
{
float phase_step = 1.0f / this->graph->get_sample_rate();
float rv = 0.0;
for (int frame = 0; frame < num_frames; frame++)
{
SIGNALFLOW_PROCESS_TRIGGER(this->clock, frame, SIGNALFLOW_DEFAULT_TRIGGER);
if (level == std::numeric_limits<float>::max())
{
level = this->levels[0]->out[0][frame];
}
if (this->state == SIGNALFLOW_NODE_STATE_ACTIVE)
{
if (node_index < levels.size() - 1)
{
float level_target = this->levels[node_index + 1]->out[0][frame];
float time = this->times[node_index]->out[0][frame];
float curve = (this->curves.size() > 0) ? (this->curves[node_index]->out[0][frame]) : 1;
float time_remaining = time - this->node_phase;
int steps_remaining = time_remaining * graph->get_sample_rate();
if (steps_remaining <= 0)
{
level = level_target;
this->node_phase = 0.0;
this->node_index++;
}
else
{
float step = (level_target - level) / steps_remaining;
level += step;
this->node_phase += phase_step;
}
rv = powf(level, curve);
}
else
{
if (this->loop)
{
this->trigger();
}
else
{
this->set_state(SIGNALFLOW_NODE_STATE_STOPPED);
}
}
}
out[0][frame] = rv;
}
}
}
| true |
b7f99f868648f70d7cb4659af8e22e7096b24575 | C++ | Jorgen-VikingGod/WiFiDuck32 | /esp_duck/src/led.h | UTF-8 | 616 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*!
\file leds.h
\brief helper class to highlight RGB leds with Neopixel library
\author Juergen Skrotzky
\copyright MIT License
*/
#pragma once
#include <Arduino.h> // String
namespace led {
void begin();
void update();
void setBrightness(uint8_t val);
void setColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b);
void setColors(uint8_t r, uint8_t g, uint8_t b);
void setPixelColor(uint16_t n, uint32_t c);
uint32_t getPixelColor(uint16_t n);
void crossFade(uint16_t n, uint8_t r, uint8_t g, uint8_t b, uint8_t speed, uint8_t step = 10);
void show();
uint32_t Wheel(byte WheelPos);
} // namespace led | true |
eb57d3a95cd822a281d76bd036461dd61f575443 | C++ | fatihaslaan/Avoid-Bullets-Cocos2d-x- | /Classes/Bullet.cpp | UTF-8 | 2,105 | 2.84375 | 3 | [] | no_license | #include "Bullet.h"
#include "Definitions.h"
USING_NS_CC;
Bullet::Bullet()
{
visibleSize = Director::getInstance()->getVisibleSize();
origin = Director::getInstance()->getVisibleOrigin();
}
void Bullet::SpawnBullet(cocos2d::Layer* layer)
{
bullet = Sprite::create("HelloWorld.png");
bullet->setScale(0.05f);
auto bulletBody = PhysicsBody::createBox(bullet->getContentSize());
auto randomStartingFace = CCRANDOM_0_1();
auto randomFinalFace = CCRANDOM_0_1();
Vec2 a, b; //One will be startingPosition and the other one will be finalPosition, related to randomSide value
if (randomStartingFace < 0.5f) //First position is somewhere in the top of the screen
{
a = Vec2(cocos2d::RandomHelper::random_real(origin.x, origin.x + visibleSize.width), origin.y + visibleSize.height + 10);
}
else //First position is somewhere in the right of the screen
{
a = Vec2(origin.x + visibleSize.width + 10, cocos2d::RandomHelper::random_real(origin.y, origin.y + visibleSize.height));
}
if (randomFinalFace < 0.5f) //Second position is somewhere in the down of the screen
{
b = Vec2(cocos2d::RandomHelper::random_real(origin.x, origin.x + visibleSize.width), origin.y - 10);
}
else //Second position is somewhere in the left of the screen
{
b = Vec2(origin.x - 10, cocos2d::RandomHelper::random_real(origin.y, origin.y + visibleSize.height));
}
auto randomSide = CCRANDOM_0_1();
if (randomSide < 0.5f) //Change bullet starting position side and make the bullets come from everywhere
{
startingPosition = a;
finalPosition = b;
}
else
{
startingPosition = b;
finalPosition = a;
}
bulletBody->setDynamic(false);
bulletBody->setCollisionBitmask(OBSTACLE_COLLISION_BITMASK);
bulletBody->setContactTestBitmask(true);
bullet->setPhysicsBody(bulletBody);
bullet->setPosition(startingPosition); //Set position of our bullet to startingPosition
layer->addChild(bullet);
auto fireBulletAction = MoveTo::create(bulletSpeed, finalPosition);
bullet->runAction(fireBulletAction); //Fire bullet to finalPosition
} | true |
1f08d3b3d30e90e9c7d4cd6b13e9072525814d67 | C++ | ijiangpeiyong/ijiang | /cpp/testJacobi.cpp | UTF-8 | 2,159 | 2.8125 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
#include <iostream>
int main()
{
double tol = 1e-6;
int iter_max = 1e4;
const int n = 32;
const int m = 32;
int *A = new int[m, n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
/*
if (j < n / 3)
A[i, j] = 0.;
else if (j > n * 2 / 3)
A[i, j] = 0.;
else
A[i, j] = 0.5;
*/
/*
else if (i < m / 3)
{
std::cout << m * 2 / 3 << " " << i << " " << j << " " << std::endl;
A[i, j] = 0.3;
}
else if (i > m * 2 / 3)
A[i, j] = 0.4;
*/
/*
if (i < m / 3)
A[i, j] = 0.;
else if (i > m * 2 / 3)
A[i, j] = 0.;
else
A[i, j] = 0.5;
*/
/*
if ((i>10) &&(i<20))
A[i, j] = 0.5;
else
A[i, j] = 0.;
*/
A[i, j] = i+j;
std::cout << i << " " << j << " " <<i+j<< std::endl;
}
}
/*
#pragma acc data copy(A, Anew)
while ( error > tol && iter < iter_max )
{
error = 0.f;
#pragma omp parallel for shared(m, n, Anew, A)
#pragma acc kernels
for( int j = 1; j < n-1; j++)
{
for( int i = 1; i < m-1; i++ )
{
Anew[j][i] = 0.25f * ( A[j][i+1] + A[j][i-1]
+ A[j-1][i] + A[j+1][i]);
error = fmaxf( error, fabsf(Anew[j][i]-A[j][i]));
}
}
#pragma omp parallel for shared(m, n, Anew, A)
#pragma acc kernels
for( int j = 1; j < n-1; j++)
{
for( int i = 1; i < m-1; i++ )
{
A[j][i] = Anew[j][i];
}
}
if(iter % 100 == 0) printf("%5d, %0.6fn", iter, error);
iter++;
}
double runtime = GetTimer();
printf(" total: %f sn", runtime / 1000.f);
}
*/
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
std::cout << A[i, j] << " ";
}
std::cout << std::endl;
}
delete[] A;
std::cout << "END" << std::endl;
return 0;
}
| true |
566c7eeee07b9407d7fa4217cafb10c7d2036fb9 | C++ | scarlet2131/DSA-and-competitive-codes | /DSA/hackerearth/disjoint_set/marriage_problem.cpp | UTF-8 | 1,595 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
ll getPar(ll x,ll par[]){
while(x!=par[x])
x = par[x];
return x;
}
ll find(ll x,ll y,ll par[])
{
return getPar(x,par) == getPar(y,par);
}
ll doUnion(ll x,ll y,ll par[],ll size[])
{
if( find(x,y,par) )
return -1;
ll p1 = getPar(x,par);
ll p2 = getPar(y,par);
ll s1 = size[p1];
ll s2 = size[p2];
if( s1 > s2 )
{
par[p2] = p1;
size[p1] += s2;
}
else
{
par[p1] = p2;
size[p2] += s1;
}
return 1;
}
int main()
{
ll n,m;
cin >> n >> m;
ll par[n+m+1],size[n+m+1];
for(ll i=1;i<=n+m;i++)
{
par[i] = i;
size[i] = 1;
}
ll q1;
cin>>q1;
ll x,y;
for(ll i=0;i<q1;i++)
{
cin>>x>>y;
doUnion(x,y,par,size);
}
ll q2;
cin>>q2;
for(ll i=0;i<q2;i++)
{
cin>>x>>y;
doUnion(x+n,y+n,par,size);
}
ll q3;
cin>>q3;
for(ll i=0;i<q3;i++)
{
cin>>x>>y;
doUnion(x,y+n,par,size);
}
ll ans=0;
unordered_map<ll,pair<ll,ll>> g;
for(ll i=1;i<n+m+1;i++)
{
ll l=getPar(i,par);
if(i<=n)
g[l].first++;
else
g[l].second++;
}
for(auto it=g.begin();it!=g.end();it++)
{
ans+=it->second.first*(m-it->second.second);
}
cout<<ans<<endl;
} | true |
3e62a66b5776fbfca7587afc24b482a22d2103aa | C++ | vaishnaviawasthi01/lab5.5 | /lab5.5_q1.cpp | UTF-8 | 545 | 3.71875 | 4 | [] | no_license | //to write a program for arranging stars in box shape(k*l).
//include library
#include <iostream>
using namespace std;
//include function
int main (){
//introducing variable
int k, l;
//giving commands to take input.
cout <<"what is the number of rows : ";
cin >> k;
cout << "what is the number of columns : ";
cin >> l;
//creating outer loop
for (int i=0; i<k; i++)
//creating inner loop
{
for (int j=0; j<l;j++)
{
cout<< "*";
}
cout<<endl;
}
//ending.
return 0;
}
| true |
badbe55b5c212ee81143bfac0a9f9f1f5b4d42af | C++ | WOOPICH/Structures-and-Algorithms | /Laba2/Laba2.cpp | WINDOWS-1251 | 1,549 | 3.5 | 4 | [] | no_license | #include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int n;
vector <int> newArray;
vector <int> deleted;
void fill(int n, vector <int> &array)
{
for (int i = 0; i < n; i++) {
array.push_back(rand() % 10000 + 1);
}
}
void display(vector <int> &array)
{
for (int i = 0; i < array.size(); i++) {
cout << array[i] << " ";
}
cout << endl << endl;
}
void deleteElements(vector <int> &array)
{
int first, second;
for (int i = 0; i < array.size(); i++) {
first = array[i] % 10;
second = array[i];
while (second/10 != 0) {
second /= 10;
}
if (first == second) {
deleted.push_back(array[i]);
array.erase(array.begin() + i);
}
}
}
int main()
{
setlocale(LC_ALL, "rus");
cout << " 2, 3, , -02-17" << endl;
cout << " : ' '" << endl << endl;
cout << " " << endl;
cin >> n;
while (n > 100 || n < 1) {
cout << "" << endl;
cout << " " << endl;
cin >> n;
}
fill(n, newArray);
cout << " " << endl;
display(newArray);
deleteElements(newArray);
cout << " " << endl;
display(newArray);
cout << "" << endl;
display(deleted);
system("pause");
return 0;
}
| true |
292d8da0acc87891e4b2a36b3d5f0816fbb638f5 | C++ | hpc-cecal-uy/cursoAE | /MapColouring/malva/rep/SA/maxsat/SA.pro.cc | ISO-8859-1 | 45,254 | 2.765625 | 3 | [] | no_license | /************************************************
*** ***
*** Simulated Annealing Skeleton v1.0 ***
*** Provided classes and methods ***
*** Developed by: Carlos Cotta Porras ***
*** ***
************************************************/
#include <iostream.h>
#include <math.h>
#include "SA.hh"
#include "Mallba/random.hh"
#include "Mallba/time.hh"
skeleton SA
{
// SetUpParams -----------------------------------------------------------
SetUpParams::SetUpParams ():
_independent_runs(0),
_max_evaluations(0),
_MarkovChain_length(0),
_temperature_decay(0),
_refresh_global_state(0),
_synchronized(0),
_display_state(0),
_cooperation(0)
{}
istream& operator>> (istream& is, SetUpParams& setup)
{
char buffer[MAX_BUFFER]; // current line in the setup file
char command[50];
int op;
double dop;
short int nb_param=0;
short int nb_section=0;
short int nb_LAN_param=0;
while (is.getline(buffer,MAX_BUFFER,'\n'))
{
sscanf(buffer," %s ",command);
if (!(strcmp(command,"General"))) nb_section=0;
if (!(strcmp(command,"LAN-configuration"))) nb_section=1;
if (nb_param==3 && nb_section==0)
{
dop=-1;
sscanf(buffer," %lf ",&dop);
if (dop<0) continue;
}
else
{
op=-1;
sscanf(buffer," %ld%*s ",&op);
if (op<0) continue;
}
switch (nb_section)
{
case 0: switch (nb_param)
{
case 0: setup.independent_runs(op); break;
case 1: setup.max_evaluations(op); break;
case 2: setup.MarkovChain_length(op); break;
case 3: setup.temperature_decay(dop); break;
case 4: setup.display_state(op); break;
}
nb_param++;
break;
case 1: if (nb_LAN_param>=3) break;
if (nb_LAN_param==0) setup.refresh_global_state(op);
if (nb_LAN_param==1) setup.synchronized(op);
if (nb_LAN_param==2) setup.cooperation(op);
nb_LAN_param++;
break;
} // end switch
} // end while
return is;
}
ostream& operator<< (ostream& os, const SetUpParams& setup)
{
os << "CONFIGURATION -------------------------------------------" << endl << endl;
os << "\t" << "Independent runs : " << setup.independent_runs() << endl
<< "\t" << "Evaluation steps: " << setup.max_evaluations() << endl
<< "\t" << "Markov-Chain Length: " << setup.MarkovChain_length() << endl
<< "\t" << "Temperature Decay: " << setup.temperature_decay() << endl;
if (setup.display_state())
os << "\t" << "Display state" << endl;
else
os << "\t" << "Not display state" << endl;
os << endl << "\t" << "LAN configuration:" << endl
<< "\t" << "----------------------" << endl << endl
<< "\t" << "Refresh global state in number of generations: " << setup.refresh_global_state() << endl;
if (setup.synchronized())
os << "\t" << "Running in synchronous mode" << endl;
else
os << "\t" << "Running in asynchronous mode" << endl;
if (!setup.cooperation())
os << "\t" << "Running without cooperation" << endl << endl;
else
os << "\t" << "Running with cooperation in " << setup.cooperation() << " iterations. " << endl << endl;
os << endl << endl << "END CONFIGURATION -------------------------------------------" << endl << endl;
return os;
}
const unsigned int SetUpParams::independent_runs() const
{
return _independent_runs;
}
const unsigned long SetUpParams::max_evaluations() const
{
return _max_evaluations;
}
const unsigned int SetUpParams::MarkovChain_length() const
{
return _MarkovChain_length;
}
const double SetUpParams::temperature_decay() const
{
return _temperature_decay;
}
const bool SetUpParams::display_state() const
{
return _display_state;
}
const unsigned long SetUpParams::refresh_global_state() const
{
return _refresh_global_state;
}
const bool SetUpParams::synchronized() const
{
return _synchronized;
}
const unsigned int SetUpParams::cooperation() const
{
return _cooperation;
}
void SetUpParams::independent_runs(const unsigned int val)
{
_independent_runs = val;
}
void SetUpParams::max_evaluations(const unsigned long val)
{
_max_evaluations= val;
}
void SetUpParams::MarkovChain_length(const unsigned int val)
{
_MarkovChain_length= val;
}
void SetUpParams::temperature_decay(const double val)
{
_temperature_decay= val;
}
void SetUpParams::display_state(const bool val)
{
_display_state=val;
}
void SetUpParams::refresh_global_state(const unsigned long val)
{
_refresh_global_state=val;
}
void SetUpParams::synchronized(const bool val)
{
_synchronized=val;
}
void SetUpParams::cooperation(const unsigned int val)
{
_cooperation=val;
}
SetUpParams::~SetUpParams()
{}
// Statistics ------------------------------------------------------
Statistics::Statistics()
{}
ostream& operator<< (ostream& os, const Statistics& stats)
{
int j;
os << "\n---------------------------------------------------------------" << endl;
os << " STATISTICS OF CURRENT TRIAL " << endl;
os << "------------------------------------------------------------------" << endl;
for (int i=0;i< stats.stats_data.size();i++)
{
os << endl
<< " Evaluations: " << stats.stats_data[i].nb_evaluations
<< " Best: " << stats.stats_data[i].best_cost
<< " Current: " << stats.stats_data[i].current_cost;
}
os << endl << "------------------------------------------------------------------" << endl;
return os;
}
Statistics& Statistics::operator= (const Statistics& stats)
{
stats_data = stats.stats_data;
return *this;
}
void Statistics::update(const Solver& solver)
{
/* struct stat *new_stat;
if ((new_stat=(struct stat *)malloc(sizeof(struct stat)))==NULL)
show_message(7);
new_stat->trial = solver.current_trial();
new_stat->nb_evaluations= solver.current_iteration();
new_stat->best_cost = solver.current_best_cost();
new_stat->current_cost = solver.current_cost();
stats_data.append(*new_stat); */
}
Statistics::~Statistics()
{
stats_data.remove();
}
void Statistics::clear()
{
stats_data.remove();
}
// Solver (superclass)---------------------------------------------------
Solver::Solver (const Problem& pbm, const SetUpParams& setup)
: problem(pbm),
params(setup),
_stat(),
_userstat(),
_sc(),
_direction(pbm.direction()),
current(pbm),
tentative(pbm),
currentTemperature(0.0),
time_spent_in_trial(0.0),
total_time_spent(0.0),
start_trial(0.0),
start_global(0.0),
_current_trial("_current_trial",_sc),
_current_iteration("_current_iteration",_sc),
_current_best_solution("_current_best_solution",_sc),
_current_best_cost("_current_best_cost",_sc),
_current_solution("_current_solution",_sc),
_current_cost("_current_cost",_sc),
_current_time_spent("_current_time_spent",_sc),
_initial_temperature_trial("_initial_temperature_trial",_sc),
_time_best_found_trial("_time_best_found_trial",_sc),
_iteration_best_found_trial("_iteration_best_found_trial",_sc),
_temperature_best_found_trial("_temperature_best_found_trial",_sc),
_time_spent_trial("_time_spent_trial",_sc),
_trial_best_found("_trial_best_found",_sc),
_iteration_best_found("_iteration_best_found;",_sc),
_global_best_solution("_global_best_solution",_sc),
_global_best_cost("_global_best_cost",_sc),
_time_best_found("_time_best_found",_sc),
_temperature("_temperature",_sc),
_display_state("_display_state",_sc)
{
current_trial(0);
current_iteration(0);
current_best_solution(current),
current_best_cost((-1) * pbm.direction() * infinity());
current_solution(current);
current_cost((-1) * pbm.direction() * infinity());
current_time_spent(total_time_spent);
initial_temperature_trial(0);
time_best_found_trial(time_spent_in_trial);
iteration_best_found_trial(0);
temperature_best_found_trial(0.0);
time_spent_trial(time_spent_in_trial);
trial_best_found(0);
iteration_best_found(0);
global_best_solution(current);
global_best_cost((-1) * pbm.direction() * infinity());
time_best_found(total_time_spent);
temperature(currentTemperature);
display_state(setup.display_state());
move = new DefaultMove;
}
int Solver::pid() const
{
return 0;
}
bool Solver::end_trial() const
{
return _end_trial;
}
unsigned int Solver::current_trial() const
{
unsigned int value=0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_current_trial",(char *)&value, nitems, length);
return value;
}
unsigned long Solver::current_iteration() const
{
unsigned long value=0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_current_iteration",(char *)&value, nitems, length);
return value;
}
Solution Solver::current_best_solution() const
{
Solution sol(problem);
unsigned long nitems,length;
char data_stored[_current_best_solution.get_nitems() + _current_best_solution.get_length()];
_sc.get_contents_state_variable("_current_best_solution", data_stored, nitems, length);
sol.to_Solution(data_stored);
return sol;
}
double Solver::current_best_cost() const
{
double value=0.0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_current_best_cost",(char *)&value, nitems, length);
return value;
}
double Solver::current_cost() const
{
double value=0.0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_current_cost",(char *)&value, nitems, length);
return value;
}
Solution Solver::current_solution() const
{
Solution sol(problem);
char data_stored[_current_solution.get_nitems() + _current_solution.get_length()];
unsigned long nitems,length;
_sc.get_contents_state_variable("_current_solution",data_stored, nitems, length);
sol.to_Solution((char *)data_stored);
return sol;
}
float Solver::current_time_spent() const
{
float value=0.0;
unsigned long nitems,length;
_current_time_spent.get_contents((char *)&value, nitems, length);
return value;
}
float Solver::time_best_found_trial() const
{
float value=0.0;
unsigned long nitems,length;
_time_best_found_trial.get_contents((char *)&value, nitems, length);
return value;
}
unsigned int Solver::iteration_best_found_trial() const
{
unsigned int value=0;
unsigned long nitems,length;
_iteration_best_found_trial.get_contents((char *)&value, nitems, length);
return value;
}
double Solver::initial_temperature_trial() const
{
double value=0.0;
unsigned long nitems,length;
_initial_temperature_trial.get_contents((char *)&value, nitems, length);
return value;
}
double Solver::temperature_best_found_trial() const
{
double value=0.0;
unsigned long nitems,length;
_temperature_best_found_trial.get_contents((char *)&value, nitems, length);
return value;
}
float Solver::time_spent_trial() const
{
float value=0.0;
unsigned long nitems,length;
_time_spent_trial.get_contents((char *)&value, nitems, length);
return value;
}
unsigned int Solver::trial_best_found() const
{
unsigned int value=0;
unsigned long nitems,length;
_trial_best_found.get_contents((char *)&value, nitems, length);
return value;
}
unsigned int Solver::iteration_best_found() const
{
unsigned int value=0;
unsigned long nitems,length;
_iteration_best_found.get_contents((char *)&value, nitems, length);
return value;
}
Solution Solver::global_best_solution() const
{
Solution sol(problem);
char data_stored[_global_best_solution.get_nitems() + _global_best_solution.get_length()];
unsigned long nitems,length;
_sc.get_contents_state_variable("_global_best_solution",data_stored, nitems, length);
sol.to_Solution(data_stored);
return sol;
}
double Solver::global_best_cost() const
{
double value=0.0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_global_best_cost",(char *)&value, nitems, length);
return value;
}
float Solver::time_best_found() const
{
float value=0.0;
unsigned long nitems,length;
_time_best_found.get_contents((char *)&value, nitems, length);
return value;
}
double Solver::temperature() const
{
double value=0.0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_temperature",(char *)&value, nitems, length);
return value;
}
int Solver::display_state() const
{
int value=0;
unsigned long nitems,length;
_sc.get_contents_state_variable("_display_state",(char *)&value, nitems, length);
return value;
}
void Solver::current_trial(const unsigned int value)
{
_sc.set_contents_state_variable("_current_trial",(char *)&value,1,sizeof(int));
}
void Solver::current_iteration(const unsigned long value)
{
_sc.set_contents_state_variable("_current_iteration",(char *)&value,1,sizeof(long));
}
void Solver::current_best_solution(const Solution& sol)
{
_sc.set_contents_state_variable("_current_best_solution",sol.to_String(),1,sol.size());
}
void Solver::current_best_cost(const double value)
{
_sc.set_contents_state_variable("_current_best_cost",(char *)&value,1,sizeof(double));
}
void Solver::current_cost(const double value)
{
_sc.set_contents_state_variable("_current_cost",(char *)&value,1,sizeof(double));
}
void Solver::current_solution(const Solution& sol)
{
_sc.set_contents_state_variable("_current_solution",sol.to_String(),1,sol.size());
}
void Solver::current_time_spent(const float value)
{
_current_time_spent.set_contents((char *)&value,1,sizeof(float));
}
void Solver::time_best_found_trial(const float value)
{
_time_best_found_trial.set_contents((char *)&value,1,sizeof(float));
}
void Solver::iteration_best_found_trial(const unsigned int value)
{
_iteration_best_found_trial.set_contents((char *)&value,1,sizeof(int));
}
void Solver::initial_temperature_trial(const double value)
{
_initial_temperature_trial.set_contents((char *)&value,1,sizeof(double));
}
void Solver::temperature_best_found_trial(const double value)
{
_temperature_best_found_trial.set_contents((char *)&value,1,sizeof(double));
}
void Solver::time_spent_trial(const float value)
{
_time_spent_trial.set_contents((char *)&value,1,sizeof(float));
}
void Solver::trial_best_found(const unsigned int value)
{
_trial_best_found.set_contents((char *)&value,1,sizeof(int));
}
void Solver::iteration_best_found(const unsigned int value)
{
_iteration_best_found.set_contents((char *)&value,1,sizeof(int));
}
void Solver::global_best_solution(const Solution& sol)
{
_sc.set_contents_state_variable("_global_best_solution",sol.to_String(),1,sol.size());
}
void Solver::global_best_cost(const double value)
{
_sc.set_contents_state_variable("_global_best_cost",(char *)&value,1,sizeof(double));
}
void Solver::time_best_found(const float value)
{
_time_best_found.set_contents((char *)&value,1,sizeof(float));
}
void Solver::temperature(const double value)
{
_sc.set_contents_state_variable("_temperature",(char *)&value,1,sizeof(double));
}
void Solver::display_state(const int value)
{
_sc.set_contents_state_variable("_display_state",(char *)&value,1,sizeof(int));
}
const Statistics& Solver::statistics() const
{
return _stat;
}
const UserStatistics& Solver::userstatistics() const
{
return _userstat;
}
const SetUpParams& Solver::setup() const
{
return params;
}
const Problem& Solver::pbm() const
{
return problem;
}
void Solver::KeepHistory(const Solution& sol, const double curfit,const float time_spent_in_trial,const float total_time_spent)
{
bool betterG=false;
bool betterT=false;
switch (_direction)
{
case minimize: betterG = (curfit < global_best_cost() || (curfit == global_best_cost() && time_spent_in_trial < time_best_found()));
betterT = (curfit < current_best_cost() || (curfit == current_best_cost() && time_spent_in_trial < time_best_found_trial()));
break;
case maximize: betterG = (curfit > global_best_cost() || (curfit == global_best_cost() && time_spent_in_trial < time_best_found()));
betterT = (curfit > current_best_cost() || (curfit == current_best_cost() && time_spent_in_trial < time_best_found_trial()));
break;
}
if (betterT)
{
current_best_solution(sol);
current_best_cost(curfit);
time_best_found_trial(time_spent_in_trial);
iteration_best_found_trial(current_iteration());
temperature_best_found_trial(temperature());
if (betterG)
{
trial_best_found(current_trial());
iteration_best_found(current_iteration());
global_best_solution(sol);
global_best_cost(curfit);
time_best_found(time_spent_in_trial);
}
}
}
double Solver::UpdateT(double temp, int K)
{
//return temp * params.temperature_decay(); // initial
/*
if(K == 1) return temp/log(2);
else return temp * log(K) / log(K+1);
*/
/*
if(K == 1) return temp/2;
else return (temp * K) / (K + 1);
*/
if(K == 1) return temp / exp(2);
else return (temp * exp(K)) / exp(K+1);
}
StateCenter* Solver::GetState()
{
return &_sc;
}
void Solver::RefreshState()
{
current_solution(current);
current_cost(curfit);
current_time_spent(total_time_spent);
time_spent_trial(time_spent_in_trial);
temperature(currentTemperature);
KeepHistory(current,curfit,time_spent_in_trial,total_time_spent);
}
void Solver::UpdateFromState()
{
current = current_solution();
curfit = current_cost();
total_time_spent=current_time_spent();
time_spent_in_trial=time_spent_trial();
currentTemperature = temperature();
KeepHistory(current,curfit,time_spent_in_trial,total_time_spent);
}
void Solver::show_state() const
{
cout << endl << "Current trial: " << current_trial();
cout << endl << "Current iteration: " << current_iteration();
cout << endl << "Current Temperature: " << temperature ();
cout << endl << "Current cost: " << current_cost();
cout << endl << "Best cost in trial: " << current_best_cost();
cout << endl << "Time of best solution found in trial: " << time_best_found_trial();
cout << endl << "Iteration of best solution found in trial: " << iteration_best_found_trial();
cout << endl << "Initial temperature in trial: " << initial_temperature_trial();
cout << endl << "Temperature of best solution found in trial: " << temperature_best_found_trial();
cout << endl << "Time spent in trial: " << time_spent_trial();
cout << endl << "Global best cost: " << global_best_cost();
cout << endl << "Trial of best global solution found: " << trial_best_found();
cout << endl << "Iteration of best global solution found: " << iteration_best_found();
cout << endl << "Time of global best solution found: " << time_best_found();
// cout << endl << "Current solution: " << current_solution();
// cout << endl << "Best solution of trial: " << current_best_solution();
// cout << endl << "Global solution: " << global_best_solution() << endl;
cout << endl << endl << "Current time spent (so far): " << current_time_spent() << endl;
}
Solver::~Solver()
{
_sc.removeAll();
delete move;
}
bool Solver::AcceptQ (double tent, double cur, double temperature)
{
if (_direction==minimize)
return (tent < cur) ||
((rand01()*(1+exp((tent-cur)/temperature)))<2.0);
else
return (tent > cur) ||
((rand01()*(1+exp((cur-tent)/temperature)))<2.0);
}
double Solver::Set_Initial_Temperature(const Problem& pbm)
{
const double beta = 1.05;
const double test = 10;
const double acrat = .8;
const double T = 1.0;
Solution current (pbm);
Solution newsol (pbm);
double ac;
double fit;
double temperature = T;
do
{
temperature *= beta;
ac = 0;
current.initialize();
fit = current.fitness();
for (int i=0; i<test; i++)
{
newsol = current;
move->Apply(newsol);
if (AcceptQ(newsol.fitness(),fit,temperature))
ac += 1.0/test;
}
} while (ac < acrat);
initial_temperature_trial(temperature);
return temperature;
}
void Solver::SetMove (Move* mov)
{
delete move;
move = mov;
}
// Solver sequencial -----------------------------------------------------
Solver_Seq::Solver_Seq (const Problem& pbm, const SetUpParams& setup)
: Solver(pbm,setup)
{
random_seed(time(0));
_end_trial=true;
}
Solver_Seq::~Solver_Seq ()
{}
void Solver_Seq::StartUp()
{
Solution sol(problem);
sol.initialize();
StartUp(sol, Set_Initial_Temperature(problem));
}
void Solver_Seq::StartUp(const Solution& sol)
{
StartUp(sol, Set_Initial_Temperature(problem));
}
void Solver_Seq::StartUp(const double initialTemperature)
{
Solution sol(problem);
sol.initialize();
StartUp(sol, initialTemperature);
}
void Solver_Seq::StartUp(const Solution& sol, const double initialTemperature)
{
start_trial=_used_time();
start_global=total_time_spent;
current_trial(current_trial()+1);
current_iteration(0);
k = 0;
time_spent_in_trial=0.0;
current = sol;
curfit = current.fitness();
current_best_cost((-1) * problem.direction() * infinity());
currentTemperature = initialTemperature;
iteration_best_found_trial(0);
temperature_best_found_trial(0);
time_best_found_trial(0.0);
RefreshState();
_stat.update(*this);
_userstat.update(*this);
if (display_state())
show_state();
}
void Solver_Seq::DoStep()
{
current_iteration(current_iteration()+1);
tentative = current;
move->Apply(tentative);
double tentfit = tentative.fitness();
if (AcceptQ(tentfit,curfit, currentTemperature))
{
current = tentative;
curfit = tentfit;
}
k++;
if (k>=params.MarkovChain_length())
{
currentTemperature = UpdateT(currentTemperature,current_iteration()/params.MarkovChain_length());
k = 0;
}
time_spent_in_trial = _used_time(start_trial);
total_time_spent = start_global + time_spent_in_trial;
RefreshState();
_stat.update(*this);
_userstat.update(*this);
if (display_state())
show_state();
}
void Solver_Seq::run (unsigned long int max_evaluations)
{
StartUp();
while (current_iteration()<max_evaluations && !TerminateQ(problem, *this, params))
DoStep();
}
void Solver_Seq::run (const Solution& sol, unsigned long int max_evaluations)
{
StartUp(sol);
while ((current_iteration()<max_evaluations) && !TerminateQ(problem, *this, params))
DoStep();
}
void Solver_Seq::run (const double initialTemperature)
{
while (current_trial() < params.independent_runs())
run(initialTemperature,params.max_evaluations());
}
void Solver_Seq::run (const Solution& sol,const double initialTemperature)
{
while (current_trial() < params.independent_runs())
run(sol,initialTemperature,params.max_evaluations());
}
void Solver_Seq::run (const double initialTemperature, unsigned long int max_evaluations)
{
StartUp(initialTemperature);
while ((current_iteration()<max_evaluations) && !TerminateQ(problem, *this, params))
DoStep();
}
void Solver_Seq::run (const Solution& sol,const double initialTemperature, unsigned long int max_evaluations)
{
StartUp(sol,initialTemperature);
while ((current_iteration()<max_evaluations) && !TerminateQ(problem, *this, params))
DoStep();
}
void Solver_Seq::run ()
{
while (current_trial() < params.independent_runs())
run(params.max_evaluations());
}
// Solver LAN -----------------------------------------------------------
Solver_Lan::Solver_Lan (const Problem& pbm, const SetUpParams& setup,int argc,char **argv):
_best_solution_trial(pbm),
Solver(pbm,setup),_netstream(),
// Termination phase //
final_phase(false),acum_evaluations(0)
{
NetStream::init(argc,argv);
mypid=_netstream.my_pid();
random_seed(time(0) + (mypid+1));
if (mypid!=0)
_netstream << set_source(0) << set_target(0);
}
Solver_Lan::~Solver_Lan ()
{
NetStream::finalize();
}
int Solver_Lan::pid() const
{
return mypid;
}
NetStream& Solver_Lan::netstream()
{
return _netstream;
}
void Solver_Lan::StartUp()
{
Solution sol(problem);
sol.initialize();
StartUp(sol, Set_Initial_Temperature(problem));
}
void Solver_Lan::StartUp(const Solution& sol)
{
StartUp(sol, Set_Initial_Temperature(problem));
}
void Solver_Lan::StartUp(const double initialTemperature)
{
Solution sol(problem);
sol.initialize();
StartUp(sol, initialTemperature);
}
void Solver_Lan::StartUp(const Solution& sol, const double initialTemperature)
{
_netstream << barrier;
start_trial=_used_time();
start_global=total_time_spent;
// Termination phase //
final_phase = false;
acum_evaluations = 0;
_end_trial=false;
current_trial(current_trial()+1);
current_iteration(0);
k = 0;
time_spent_in_trial=0.0;
current_best_cost((-1) * problem.direction() * infinity());
iteration_best_found_trial(0);
temperature_best_found_trial(0);
time_best_found_trial(0.0);
time_spent_trial(0.0);
if (mypid!=0)
{
current = sol;
curfit = current.fitness();
currentTemperature = initialTemperature;
RefreshState();
send_local_state_to(mypid);
_stat.update(*this);
_userstat.update(*this);
// if (display_state()) show_state();
}
}
void update(Direction direction, Solution &solution_received,double cost_received, Solution &solution_to_send, double &best_cost)
{
switch (direction)
{
case minimize: if (cost_received < best_cost)
{
solution_to_send=solution_received;
best_cost=cost_received;
}
case maximize: if (cost_received > best_cost)
{
solution_to_send=solution_received;
best_cost=cost_received;
}
}
}
int Solver_Lan::cooperation()
{
int received=false;
Solution solution_received(problem), solution_to_send(problem);
double cost_received=0, cost_to_send=0;
int pending=false;
int pid_source,pid_target;
if (mypid!=0)
{
if (((int)current_iteration() % params.refresh_global_state()) ==0) // isnot the server
{
_netstream << set_target(0);
send_local_state_to(mypid);
}
if (params.cooperation()==0) return received;
pid_target=mypid+1;
if (pid_target==_netstream.pnumber()) pid_target=1;
_netstream << set_target(pid_target);
pid_source=mypid-1;
if (pid_source==0) pid_source=_netstream.pnumber()-1;
_netstream << set_source(pid_source);
if ((((int)current_iteration() % params.cooperation())==0) && (params.max_evaluations()!=current_iteration()))
{
if (mypid==1)
_netstream << current_best_cost() << current_best_solution();
if (params.synchronized())
{
_netstream << wait(regular);
_netstream >> cost_received >> solution_received;
received=true;
}
}
if (!params.synchronized())
{
int pending=false;
_netstream._probe(regular,pending);
if (pending)
{
_netstream >> cost_received >> solution_received;
received=true;
}
}
if (mypid!=1 && received)
{
solution_to_send = current_best_solution();
cost_to_send=current_best_cost();
if (received)
{
update(problem.direction(),solution_received, cost_received, solution_to_send,cost_to_send);
}
_netstream << cost_to_send << solution_to_send;
}
if (received)
{
tentative=solution_received;
curfit=cost_received;
}
_netstream << set_target(0);
}
return received;
}
void Solver_Lan::DoStep()
{
current_iteration(current_iteration()+1);
// Termination phase //
_netstream << set_source(0);
int pending;
_netstream._probe(packed, pending);
if(pending)
{
Solution sol(problem);
_netstream << pack_begin >> sol << pack_end;
final_phase = true;
}
////////////////////////
int received=cooperation();
if (!received)
{
tentative = current;
move->Apply(tentative);
}
double tentfit = tentative.fitness();
if (AcceptQ(tentfit,curfit, currentTemperature))
{
current = tentative;
curfit = tentfit;
}
k++;
if (k>=params.MarkovChain_length())
{
currentTemperature = UpdateT(currentTemperature,current_iteration()/params.MarkovChain_length());
k = 0;
}
time_spent_in_trial = _used_time(start_trial);
total_time_spent = start_global + time_spent_in_trial;
RefreshState();
_stat.update(*this);
_userstat.update(*this);
// if (display_state())
// show_state();
}
void Solver_Lan::send_local_state_to(int _mypid)
{
_netstream << set_target(0);
_netstream << pack_begin
<< _mypid
<< current_trial()
<< current_iteration()
<< current_solution()
<< current_cost()
<< current_best_solution()
<< current_best_cost()
<< time_best_found_trial()
<< iteration_best_found_trial()
<< temperature_best_found_trial()
<< temperature()
<< pack_end;
}
int Solver_Lan::receive_local_state_from(int source_pid)
{
_netstream << set_source(source_pid);
int received_pid=0;
_netstream._wait(packed);
_netstream << pack_begin
>> received_pid
>> _current_trial
>> _current_iteration
>> current
>> curfit
>> _best_solution_trial
>> _best_cost_trial
>> _time_best_found_in_trial
>> _iteration_best_found_in_trial
>> _temperature_best_found_in_trial
>> currentTemperature
<< pack_end;
return received_pid;
}
void Solver_Lan::check_for_refresh_global_state() // Executed in process with pid 0
{
unsigned int nb_finalized_processes=0;
int received_pid;
int nb_proc=_netstream.pnumber();
while (!_end_trial)
{
// checking for all processes
received_pid=0;
received_pid=receive_local_state_from(MPI_ANY_SOURCE);
// refresh the global state with received data ( a local state )
current_trial(_current_trial);
current_iteration(_iteration_best_found_in_trial);
temperature(_temperature_best_found_in_trial);
KeepHistory(_best_solution_trial,_best_cost_trial,_time_best_found_in_trial,start_global + _time_best_found_in_trial);
if (received_pid==-1)
{
// Termination phase //
if(!final_phase && TerminateQ(problem,*this,params))
{
Solution sol(problem);
acum_evaluations = params.max_evaluations() * nb_finalized_processes;
for(int i = 1; i < _netstream.pnumber(); i++)
{
_netstream << set_target(i);
_netstream << pack_begin << sol << pack_end;
}
final_phase = true;
}
nb_finalized_processes++;
acum_evaluations += _iteration_best_found_in_trial;
}
if (nb_finalized_processes==nb_proc-1) _end_trial=true;
current_iteration(_current_iteration);
temperature(currentTemperature);
time_spent_in_trial = _used_time(start_trial);
total_time_spent = start_global + time_spent_in_trial;
RefreshState();
_stat.update(*this);
//_userstat.update(*this);
// display current global state
if (display_state()) show_state();
} // end while
// Actualizacin de las estadsticas // Termination phase //
iteration_best_found_trial(acum_evaluations/(_netstream.pnumber()-1));
bool betterG=false;
double best_cost = current_best_cost();
switch (problem.direction())
{
case minimize: betterG = (best_cost < global_best_cost() || (best_cost == global_best_cost() && time_best_found_trial() <= time_best_found()));
break;
case maximize: betterG = (best_cost > global_best_cost() || (best_cost == global_best_cost() && time_best_found_trial() <= time_best_found()));
break;
}
if (betterG)
iteration_best_found(iteration_best_found_trial());
RefreshState();
_stat.update(*this);
_userstat.update(*this);
// display the global state at the end of the current trial
if (display_state()) show_state();
}
void Solver_Lan::run ()
{
while (current_trial() < params.independent_runs())
run(params.max_evaluations());
}
void Solver_Lan::run (const unsigned long int max_evaluations)
{
StartUp();
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Lan::run (const Solution& sol, unsigned long int max_evaluations)
{
StartUp(sol);
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Lan::run (const double initialTemperature)
{
while (current_trial() < params.independent_runs())
run(initialTemperature,params.max_evaluations());
}
void Solver_Lan::run (const Solution& sol,const double initialTemperature)
{
while (current_trial() < params.independent_runs())
run(sol,initialTemperature,params.max_evaluations());
}
void Solver_Lan::run (const double initialTemperature, unsigned long int max_evaluations)
{
StartUp(initialTemperature);
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Lan::run (const Solution& sol,const double initialTemperature, unsigned long int max_evaluations)
{
StartUp(sol,initialTemperature);
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Lan::reset()
{
Solution left_solution(problem);
double left_cost;
_netstream << set_source(MPI_ANY_SOURCE);
if (mypid!=0)
{
int pendingr = false;
int pendingp = false;
do
{
pendingr = false;
pendingp = false;
_netstream._probe(regular,pendingr);
_netstream._probe(packed,pendingp);
if (pendingr) _netstream >> left_cost >> left_solution;
if (pendingp) _netstream << pack_begin >> left_solution << pack_end;
} while (pendingr || pendingp);
}
_netstream << barrier;
}
// Solver WAN ------------------------------------------------------------
Solver_Wan::Solver_Wan (const Problem& pbm, const SetUpParams& setup,int argc,char **argv):
_best_solution_trial(pbm),
Solver(pbm,setup),_netstream(),
// Termination phase //
final_phase(false),acum_evaluations(0)
{
NetStream::init(argc,argv);
mypid=_netstream.my_pid();
random_seed(time(0) + (mypid+1));
if (mypid!=0)
_netstream << set_source(0) << set_target(0);
}
Solver_Wan::~Solver_Wan ()
{
NetStream::finalize();
}
int Solver_Wan::pid() const
{
return mypid;
}
NetStream& Solver_Wan::netstream()
{
return _netstream;
}
void Solver_Wan::StartUp()
{
Solution sol(problem);
sol.initialize();
StartUp(sol, Set_Initial_Temperature(problem));
}
void Solver_Wan::StartUp(const Solution& sol)
{
StartUp(sol, Set_Initial_Temperature(problem));
}
void Solver_Wan::StartUp(const double initialTemperature)
{
Solution sol(problem);
sol.initialize();
StartUp(sol, initialTemperature);
}
void Solver_Wan::StartUp(const Solution& sol, const double initialTemperature)
{
_netstream << barrier;
start_trial=_used_time();
start_global=total_time_spent;
// Termination phase //
final_phase = false;
acum_evaluations = 0;
_end_trial=false;
current_trial(current_trial()+1);
current_iteration(0);
k = 0;
time_spent_in_trial=0.0;
current_best_cost((-1) * problem.direction() * infinity());
iteration_best_found_trial(0);
temperature_best_found_trial(0);
time_best_found_trial(0.0);
time_spent_trial(0.0);
if (mypid!=0)
{
current = sol;
curfit = current.fitness();
currentTemperature = initialTemperature;
RefreshState();
send_local_state_to(mypid);
_stat.update(*this);
_userstat.update(*this);
// if (display_state()) show_state();
}
}
int Solver_Wan::cooperation()
{
int received=false;
Solution solution_received(problem), solution_to_send(problem);
double cost_received=0, cost_to_send=0;
int pending=false;
int pid_source,pid_target;
if (mypid!=0)
{
if (((int)current_iteration() % params.refresh_global_state()) ==0) // isnot the server
{
_netstream << set_target(0);
send_local_state_to(mypid);
}
if (params.cooperation()==0) return received;
pid_target=mypid+1;
if (pid_target==_netstream.pnumber()) pid_target=1;
_netstream << set_target(pid_target);
pid_source=mypid-1;
if (pid_source==0) pid_source=_netstream.pnumber()-1;
_netstream << set_source(pid_source);
if ((((int)current_iteration() % params.cooperation())==0) && (params.max_evaluations()!=current_iteration()))
{
if (mypid==1)
_netstream << current_best_cost() << current_best_solution();
if (params.synchronized())
{
_netstream << wait(regular);
_netstream >> cost_received >> solution_received;
received=true;
}
}
if (!params.synchronized())
{
int pending=false;
_netstream._probe(regular,pending);
if (pending)
{
_netstream >> cost_received >> solution_received;
received=true;
}
}
if (mypid!=1 && received)
{
solution_to_send = current_best_solution();
cost_to_send=current_best_cost();
if (received)
{
update(problem.direction(),solution_received, cost_received, solution_to_send,cost_to_send);
}
_netstream << cost_to_send << solution_to_send;
}
if (received)
{
tentative=solution_received;
curfit=cost_received;
}
_netstream << set_target(0);
}
return received;
}
void Solver_Wan::DoStep()
{
current_iteration(current_iteration()+1);
// Termination phase //
_netstream << set_source(0);
int pending;
_netstream._probe(packed, pending);
if(pending)
{
Solution sol(problem);
_netstream << pack_begin >> sol << pack_end;
final_phase = true;
}
////////////////////////
int received=cooperation();
if (!received)
{
tentative = current;
move->Apply(tentative);
}
double tentfit = tentative.fitness();
if (AcceptQ(tentfit,curfit, currentTemperature))
{
current = tentative;
curfit = tentfit;
}
k++;
if (k>=params.MarkovChain_length())
{
currentTemperature = UpdateT(currentTemperature,current_iteration()/params.MarkovChain_length());
k = 0;
}
time_spent_in_trial = _used_time(start_trial);
total_time_spent = start_global + time_spent_in_trial;
RefreshState();
_stat.update(*this);
_userstat.update(*this);
// if (display_state())
// show_state();
}
void Solver_Wan::send_local_state_to(int _mypid)
{
_netstream << set_target(0);
_netstream << pack_begin
<< _mypid
<< current_trial()
<< current_iteration()
<< current_solution()
<< current_cost()
<< current_best_solution()
<< current_best_cost()
<< time_best_found_trial()
<< iteration_best_found_trial()
<< temperature_best_found_trial()
<< temperature()
<< pack_end;
}
int Solver_Wan::receive_local_state_from(int source_pid)
{
_netstream << set_source(source_pid);
int received_pid=0;
_netstream._wait(packed);
_netstream << pack_begin
>> received_pid
>> _current_trial
>> _current_iteration
>> current
>> curfit
>> _best_solution_trial
>> _best_cost_trial
>> _time_best_found_in_trial
>> _iteration_best_found_in_trial
>> _temperature_best_found_in_trial
>> currentTemperature
<< pack_end;
return received_pid;
}
void Solver_Wan::check_for_refresh_global_state() // Executed in process with pid 0
{
unsigned int nb_finalized_processes=0;
int received_pid;
int nb_proc=_netstream.pnumber();
while (!_end_trial)
{
// checking for all processes
received_pid=0;
received_pid=receive_local_state_from(MPI_ANY_SOURCE);
// refresh the global state with received data ( a local state )
current_trial(_current_trial);
current_iteration(_iteration_best_found_in_trial);
temperature(_temperature_best_found_in_trial);
KeepHistory(_best_solution_trial,_best_cost_trial,_time_best_found_in_trial,start_global + _time_best_found_in_trial);
if (received_pid==-1)
{
// Termination phase //
if(!final_phase && TerminateQ(problem,*this,params))
{
Solution sol(problem);
acum_evaluations = params.max_evaluations() * nb_finalized_processes;
for(int i = 1; i < _netstream.pnumber(); i++)
{
_netstream << set_target(i);
_netstream << pack_begin << sol << pack_end;
}
final_phase = true;
}
nb_finalized_processes++;
acum_evaluations += _iteration_best_found_in_trial;
}
if (nb_finalized_processes==nb_proc-1) _end_trial=true;
current_iteration(_current_iteration);
temperature(currentTemperature);
time_spent_in_trial = _used_time(start_trial);
total_time_spent = start_global + time_spent_in_trial;
RefreshState();
_stat.update(*this);
//_userstat.update(*this);
// display current global state
if (display_state()) show_state();
} // end while
// Actualizacin de las estadsticas // Termination phase //
iteration_best_found_trial(acum_evaluations/(_netstream.pnumber()-1));
bool betterG=false;
double best_cost = current_best_cost();
switch (problem.direction())
{
case minimize: betterG = (best_cost < global_best_cost() || (best_cost == global_best_cost() && time_best_found_trial() <= time_best_found()));
break;
case maximize: betterG = (best_cost > global_best_cost() || (best_cost == global_best_cost() && time_best_found_trial() <= time_best_found()));
break;
}
if (betterG)
iteration_best_found(iteration_best_found_trial());
RefreshState();
_stat.update(*this);
_userstat.update(*this);
// display the global state at the end of the current trial
if (display_state()) show_state();
}
void Solver_Wan::run ()
{
while (current_trial() < params.independent_runs())
run(params.max_evaluations());
}
void Solver_Wan::run (const unsigned long int max_evaluations)
{
StartUp();
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Wan::run (const Solution& sol, unsigned long int max_evaluations)
{
StartUp(sol);
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Wan::run (const double initialTemperature)
{
while (current_trial() < params.independent_runs())
run(initialTemperature,params.max_evaluations());
}
void Solver_Wan::run (const Solution& sol,const double initialTemperature)
{
while (current_trial() < params.independent_runs())
run(sol,initialTemperature,params.max_evaluations());
}
void Solver_Wan::run (const double initialTemperature, unsigned long int max_evaluations)
{
StartUp(initialTemperature);
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Wan::run (const Solution& sol,const double initialTemperature, unsigned long int max_evaluations)
{
StartUp(sol,initialTemperature);
if (mypid!=0)
{
while (!final_phase && (current_iteration() < max_evaluations) && !(TerminateQ(problem,*this,params)))
DoStep();
send_local_state_to(-1);
}
else
{
check_for_refresh_global_state();
}
_netstream << barrier;
reset();
}
void Solver_Wan::reset()
{
Solution left_solution(problem);
double left_cost;
_netstream << set_source(MPI_ANY_SOURCE);
if (mypid!=0)
{
int pendingr = false;
int pendingp = false;
do
{
pendingr = false;
pendingp = false;
_netstream._probe(regular,pendingr);
_netstream._probe(packed,pendingp);
if (pendingr) _netstream >> left_cost >> left_solution;
if (pendingp) _netstream << pack_begin >> left_solution << pack_end;
} while (pendingr || pendingp);
}
_netstream << barrier;
}
};
| true |
0446cdf8eb4c4901a3c64738a1f1e6feeb7be799 | C++ | tvanslyke/wasm-cpp | /include/vm/alloc/StackResource.h | UTF-8 | 9,691 | 2.734375 | 3 | [
"MIT"
] | permissive | #ifndef VM_ALLOC_STACK_RESOURCE_H
#define VM_ALLOC_STACK_RESOURCE_H
#include "vm/alloc/memory_resource.h"
#include <gsl/span>
#include <cstddef>
namespace wasm {
struct StackOverflowError:
public std::bad_alloc
{
StackOverflowError(const char* pos, std::size_t count):
std::bad_alloc(), at(pos), requested(count)
{
}
const char* const at;
const std::size_t requested;
};
struct BadAlignmentError:
public std::bad_alloc
{
StackOverflowError(std::size_t req):
std::bad_alloc(), requested(req)
{
}
const std::size_t requested;
};
struct StackResource:
public pmr::memory_resource
{
static constexpr const std::size_t max_alignment = alignof(std::max_align_t);
StackResource(char* base, std::size_t count):
StackResource(gsl::span<char>(base, count))
{
}
StackResource(gsl::span<char> buff):
base_(buff.data()),
buffer_(buff)
{
assert(buffer_.data() == base_);
}
StackResource(const StackResource& other) = delete;
void* expand(void* p, std::size_t old_size, std::size_t new_size, std::size_t alignment)
{
assert(pos + bytes <= buffer_.data());
assert(pos >= base_);
assert((pos < buffer_.data()) or (old_size == 0u));
assert(
(pos == (buffer_.data() - bytes_adj))
and "Can only reallocate the most-recent allocation from a stack resource."
);
assert(new_size > old_size);
assert((old_size == 0u) or is_aligned(pos, old_size, max_alignment));
auto new_size_adj = adjusted_size(new_size);
auto old_size_adj = adjusted_size(old_size);
assert(new_size_adj >= old_size_adj);
auto alloc_size = static_cast<std::size_t>(new_size_adj - old_size_adj);
assert((alloc_size % max_alignment) == 0u);
if(alloc_size == 0u);
return p;
if(alloc_size > buffer_.size())
throw StackOverflowError(buffer_.data(), alloc_size);
buffer_ = buffer.subspan(alloc_size);
return p;
}
void* contract(void* p, std::size_t old_size, std::size_t new_size) override
{
_assert_invariants();
const char* pos = static_cast<const char*>(p);
assert(pos + bytes <= buffer_.data());
assert(pos >= base_);
assert((pos < buffer_.data()) or (old_size == 0u));
assert(
(pos == (buffer_.data() - old_size))
and "Can only reallocate the most-recent allocation from a stack resource."
);
assert(new_size < old_size);
assert(is_aligned(pos, old_size, max_alignment));
auto new_size_adj = adjusted_size(new_size);
auto old_size_adj = adjusted_size(old_size);
assert(old_size_adj >= new_size_adj);
std::size_t dist = old_size_adj - new_size_adj;
if(dist == 0u);
return p;
assert(static_cast<std::ptrdiff_t>(dist) == (buffer_.data() - pos));
buffer_ = gsl::span<char>(p, buffer_.size() + dist);
_assert_invariants();
return p;
}
std::size_t capacity() const
{ return (buffer_.data() + buffer_.size()) - base_; }
gsl::span<const char> inspect() const
{ return gsl::span<const char>(base_, buffer_.data() - base_); }
private:
static bool is_power_of_two(std::size_t value)
{
assert(value > 0u);
return not static_cast<bool>(value & (value - 1u));
}
static bool is_aligned(const char* p, std::size_t count, std::size_t alignment)
{
assert(is_power_of_two(alignment));
return p == std::align(alignment, 1u, p, count);
}
static char* ensure_aligned(char*& base, std::size_t& count)
{
assert(base);
assert(count);
if(not std::align(alignof(std::max_align_t), 1u, base, count))
throw std::invalid_argument("Pointer-size pair could not be aligned in 'StackResource' constructor.");
}
static std::size_t adjust_size(std::size_t size)
{
auto err = size % max_alignment;
if(err != 0u)
size += max_alignment - err;
return size;
}
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override
{
_assert_invariants();
const char* pos = static_cast<const char*>(p);
std::size_t alloc_size = adjusted_size(bytes);
assert(is_aligned(pos, alloc_size, max_alignment));
assert(std::distance(base_, buffer_.data()) >= alloc_size);
assert(
pos + alloc_size == buffer_.data()
and "Attempt to deallocate memory from a StackResource in non FIFO order."
);
assert((pos < buffer_.data()) or (bytes == 0u));
assert(pos >= base_);
buffer_ = gsl::span<char>(pos, buffer_.size() + alloc_size);
_assert_invariants();
}
void* do_allocate(std::size_t bytes, std::size_t alignment) override
{
_assert_invariants();
void* pos = buffer_.data();
if(alignment > max_alignment)
throw BadAlignmentError(alignment);
std::size_t alloc_size = adjusted_size(bytes);
std::size_t len = buffer_.size();
if(buffer.size() < alloc_size)
throw StackOverflowError(buffer_.data(), bytes);
buffer_ = buffer_.subspan(alloc_size);
_assert_invariants();
return pos;
}
void _assert_invariants() const
{
auto buff_pos = buffer_.data();
assert(base_ <= buff_pos);
auto allocd = static_cast<std::size_t>(buff_pos - base_);
assert(allocd == 0u or is_aligned(base_, allocd, max_alignment));
assert(buffer_.size() == 0u or is_aligned(buff_pos, buffer_.size(), max_alignment));
}
bool do_is_equal(const pmr::memory_resource& other) const override
{
if(this == &other)
return true;
return false;
}
private:
char* const base_;
gsl::span<char> buffer_;
};
template <class T>
struct SimpleStack
{
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = std::reverse_iterator<pointer>;
using const_iterator = std::reverse_iterator<const_pointer>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
SimpleStack(StackResource& resource):
resource_(resource),
base_(resource_.allocate(0u, alignof(T))),
count_(0u)
{
}
~SimpleStack()
{
std::destroy(begin(), end());
resource_.deallocate(data(), size() * sizeof(T), alignof(T));
}
SimpleStack() = delete;
SimpleStack(const SimpleStack&) = delete;
SimpleStack(SimpleStack&&) = delete;
SimpleStack& operator=(const SimpleStack&) = delete;
SimpleStack& operator=(SimpleStack&&) = delete;
/// @name Iterators
/// @{
iterator begin()
{ return std::make_reverse_iterator(data() + size()); }
const_iterator begin() const
{ return cbegin(); }
const_iterator cbegin() const
{ return std::make_reverse_iterator(data() + size()); }
reverse_iterator rbegin()
{ return std::make_reverse_iterator(end()); }
const_reverse_iterator rbegin() const
{ return crbegin(); }
const_reverse_iterator crbegin() const
{ return std::make_reverse_iterator(cend()); }
iterator end()
{ return std::make_reverse_iterator(data()); }
const_iterator end() const
{ return cend(); }
const_iterator cend() const
{ return std::make_reverse_iterator(data()); }
reverse_iterator rend()
{ return std::make_reverse_iterator(begin()); }
const_reverse_iterator rend() const
{ return crend(); }
const_reverse_iterator crend() const
{ return std::make_reverse_iterator(cbegin()); }
/// @} Iterators
/// @name Modifiers
/// @{
void push(const T& value)
{ emplace(value); }
void push(T&& value)
{ emplace(std::move(value)); }
template <class ... Args>
reference emplace(Args&& ... args)
{
alloc_n(1u);
pointer p = ::new (base_ + (size() - 1)) T(std::forward<Args>(args)...);
return *p;
}
template <class ... Args>
reference replace_top(Args&& ... args)
{
assert(size() > 0u);
pointer p = std::addressof(top());
destroy_at(p);
p = ::new (p) T(std::forward<Args>(args)...);
return *std::launder(p);
}
value_type pop()
{
assert(not empty());
auto v = top();
pop(1u);
return v;
}
void pop_n(std::size_t n)
{
assert(n > 0u);
assert(size() >= n);
std::destroy(begin(), begin() + n);
dealloc_n(n);
}
/// @} Modifiers
/// @name Element Access
/// @{
const_reference top() const
{
assert(not empty());
return base_[size() - 1];
}
reference top()
{
assert(not empty());
return base_[size() - 1u];
}
const_reference operator[](size_type i) const
{
assert(not empty());
assert(i < size());
return data()[((size() - 1) - i)];
}
reference operator[](size_type i)
{ return const_cast<reference>(std::as_const(*this)[i]); }
const_reference at(size_type i) const
{
if(i < size())
return (*this)[i];
throw std::out_of_range("Attempt to access value in stack at an out-of-range depth.");
}
reference at(size_type i)
{ return const_cast<reference>(std::as_const(*this).at(i)); }
const_pointer data() const
{ return base_; }
pointer data()
{ return base_; }
/// @} Element Access
/// @name Capacity
/// @{
size_type size() const
{ return count_; }
size_type max_size() const
{ return std::numeric_limits<std::size_t>::max() / sizeof(T); }
bool empty() const
{ return size() == 0u; }
/// @} Capacity
const StackResource& get_resource() const
{ return resource_; }
StackResource& get_resource()
{ return resource_; }
private:
void alloc_n(std::size_t n)
{
assert(n > 0u);
T* pos = static_cast<T*>(resource_.expand(base_, sizeof(T) * n, alignof(T)));
assert(pos == base_);
base_ = pos;
count_ += n;
}
void dealloc_n(std::size_t n)
{
assert(n > 0u);
assert(count_ >= n);
T* pos = static_cast<T*>(resource_.contract(base_, n * sizeof(T), alignof(T)));
base_ = pos;
count_ -= n;
}
StackResource& resource_;
T* base_;
std::size_t count_;
};
} /* namespace wasm */
#endif /* VM_ALLOC_STACK_RESOURCE_H */
| true |
259158cb2276beb8d4cfd90ea6926efb3db21633 | C++ | Shreya935/DS-A-Assignments | /ShreyaBansal_2013512/Day8/Q38.cpp | UTF-8 | 608 | 2.75 | 3 | [] | no_license | class Solution {
public:
string longestCommonSuffix(vector<string>& strs) {
int l=strs.size(),c=0;
for(int i=0;i<l;i++)
reverse(strs[i].begin(),strs[i].end());
for(int i=0;i<l;i++)
sort(strs.begin(),strs.end());
int m=min(strs[0].size(),strs[l-1].size());
for(int i=0;i<m;i++)
if(strs[0][i]==strs[l-1][i])
c++;
else break;
if(c>0){
string s=strs[0].substr(0,c);
reverse(s.begin(),s.end());
return s;
}
else
return"";
}
};
| true |
bc9666e7c8fd7f675128aef75ee2050b6b3ee096 | C++ | LinkItONEDevGroup/LASS_WaterBoxV2 | /ArduinoLibrary/libraries/DS18B20/examples/Multiple/Multiple.ino | UTF-8 | 1,216 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <DS18B20.h>
DS18B20 ds(2);
void setup() {
Serial.begin(9600);
Serial.print("Devices: ");
Serial.println(ds.getNumberOfDevices());
Serial.println();
}
void loop() {
while (ds.selectNext()) {
switch (ds.getFamilyCode()) {
case MODEL_DS18S20:
Serial.println("Model: DS18S20/DS1820");
break;
case MODEL_DS1822:
Serial.println("Model: DS1822");
break;
case MODEL_DS18B20:
Serial.println("Model: DS18B20");
break;
default:
Serial.println("Unrecognized Device");
break;
}
uint8_t address[8];
ds.getAddress(address);
Serial.print("Address:");
for (uint8_t i = 0; i < 8; i++) {
Serial.print(" ");
Serial.print(address[i]);
}
Serial.println();
Serial.print("Resolution: ");
Serial.println(ds.getResolution());
Serial.print("Power Mode: ");
if (ds.getPowerMode()) {
Serial.println("External");
} else {
Serial.println("Parasite");
}
Serial.print("Temperature: ");
Serial.print(ds.getTempC());
Serial.print(" C / ");
Serial.print(ds.getTempF());
Serial.println(" F");
Serial.println();
}
delay(10000);
}
| true |
52aac8e58175f6ffdc673356cd2e4e0f4d77f161 | C++ | stratigoster/UW | /cs343/a5/printer.cc | UTF-8 | 2,190 | 2.734375 | 3 | [] | no_license | #include "printer.h"
#include <iostream>
#include <sstream>
using namespace std;
string Printer::states[] = { "S", "V", "B", "U", "C", "F" };
Printer::Printer( unsigned int NoOfTasks, unsigned int quorum ) : N(NoOfTasks), Q(quorum), last_id((unsigned int)-1) {
buffer = new string[N];
for (unsigned int i=0; i<N; i+=1) {
buffer[i] = "";
cout << "Voter" << i << "\t";
}
cout << endl;
for (unsigned int i=0; i<N; i+=1) {
cout << "======= ";
}
cout << endl;
}
Printer::~Printer() {
cout << "=================" << endl << "All tours started" << endl;
delete[] buffer;
}
void Printer::print( unsigned int id, Voter::states state ) {
Printer::id = id;
Printer::state = (int)state;
Printer::vote = Printer::nblocked = "";
resume();
}
void Printer::print( unsigned int id, Voter::states state, bool vote ) {
Printer::id = id;
Printer::state = (int)state;
Printer::vote = (vote ? "1" : "0");
Printer::nblocked = "";
resume();
}
void Printer::print( unsigned int id, Voter::states state, unsigned int numBlocked ) {
Printer::id = id;
Printer::state = (int)state;
Printer::vote = "";
// convert numBlocked to a string
stringstream ss;
ss << numBlocked;
Printer::nblocked = ss.str();
resume();
}
void Printer::main() {
unsigned int counter = 0;
for (;;) {
if (state == 5) {
counter += 1;
}
if (buffer[id] != "") {
// flush buffers
for (unsigned int i=0; i<N; i+=1) {
cout << buffer[i] << (i==id && last_id != id ? "*" : "") << "\t";
buffer[i] = "";
}
cout << endl;
last_id = id;
}
buffer[id] = states[state] + " " + nblocked + vote;
if (counter == Q) {
for (unsigned int i=0; i<N; i+=1) {
if (i != id) {
cout << "..." << "\t";
} else {
cout << buffer[i] << "\t";
}
buffer[i] = "";
}
cout << endl;
counter = 0;
}
suspend();
}
}
| true |
7812e3b7330acccddd1cd143c891770b33ba72c7 | C++ | lorenzo-rovigatti/ashell | /lib/OutputObservable.h | UTF-8 | 987 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
* OutputObservable.h
*
* Created on: 12 feb 2018
* Author: lorenzo
*/
#ifndef LIB_OUTPUTOBSERVABLE_H_
#define LIB_OUTPUTOBSERVABLE_H_
#include <vector>
#include <fstream>
#include <memory>
#include "computers/observables/Observable.h"
namespace ashell {
class InputFile;
class OutputObservable {
public:
OutputObservable(std::string stream_name, ullint print_every);
virtual ~OutputObservable();
void add_observable(std::shared_ptr<Observable> obs) {
_observables.push_back(obs);
}
bool is_ready(ullint step);
void print_output(ullint step);
ullint print_every() {
return _print_every;
}
void set_print_every(ullint n_print_every);
static std::shared_ptr<OutputObservable> make(InputFile &inp);
protected:
std::vector<std::shared_ptr<Observable> > _observables;
std::ofstream _output_stream;
std::ostream *_output;
ullint _print_every;
ullint _start_from;
ullint _stop_at;
};
} /* namespace ashell */
#endif /* LIB_OUTPUTOBSERVABLE_H_ */
| true |
13fa586133a8eee88753ea8f5b15ce6f56aca3c5 | C++ | PalashHawee/Data-Structures-and-Algorithms-My-Preparation-for-Software-Engineering | /Array ADT/Get_Set_Max.cpp | UTF-8 | 1,412 | 3.6875 | 4 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
struct Array
{
int A[10];
int size;
int length;
};
void display(struct Array arr)
{
int i;
printf("\nElements are: \n");
for(i=0;i<arr.length;i++)
printf("%d\n",arr.A[i]);
}
//Get method
int Get(struct Array arr,int index) //call by values
{
if(index>=0 && index<arr.length)
return arr.A[index];
return -1;
}
//set method
void Set(struct Array *arr,int index,int x) //call by address for modifying elements
{
if(index>=0 && index<arr->length)
arr->A[index]=x;
}
//max method
int Max(struct Array arr)
{
int max=arr.A[0];
int i;
for(i=1;i<arr.length;i++)
{
if(arr.A[i]>max)
max=arr.A[i];
}
return max; // O(N)
}
//Min method
int Min(struct Array arr)
{
int min=arr.A[0];
int i;
for(i=1;i<arr.length;i++)
{
if(arr.A[i]<min)
min=arr.A[i];
}
return min; // O(N)
}
//finding sum function
int Sum(struct Array arr)
{
int i;
int total=0;
for(i=0;i<arr.length;i++)
{
total+=arr.A[i];
}
return total; // O(N)
}
//finding average function
float Avg(struct Array arr)
{
return (float)Sum(arr)/arr.length;
}
int main()
{
struct Array arr={{2,3,4,5,6},20,5};
//printf("%d\n",Get(arr,2));
//Set(&arr,0,45);
//printf("%d\n",Max(arr));
//printf("%d\n",Min(arr));
//printf("%d\n",Sum(arr));
printf("%f\n",Avg(arr));
display(arr);
return 0;
}
| true |
042740c0832c8df79f1f9242775f94bccad37602 | C++ | CiarraMatthews/AntsNAnteaters | /Organism.cpp | UTF-8 | 3,270 | 3.078125 | 3 | [] | no_license | #ifndef _ORGANISM_CPP
#define _ORGANISM_CPP
#include <iostream>
#include <cmath>
#include "Organism.h"
using namespace std;
Organism::Organism() { };
Organism::Organism(World *world) {
m_world = world;
};
vector<int> Organism::vibeCheck() const {
vector<int> mapping;
if (m_world->rangeCheck(m_row - 1, m_column)) {
if (!m_world->organism(m_row - 1, m_column)) {
mapping.push_back(NORTH);
}
}
if (m_world->rangeCheck(m_row, m_column + 1)) {
if (!m_world->organism(m_row, m_column + 1)) {
mapping.push_back(EAST);
}
}
if (m_world->rangeCheck(m_row + 1, m_column)) {
if (!m_world->organism(m_row + 1, m_column)) {
mapping.push_back(SOUTH);
}
}
if (m_world->rangeCheck(m_row, m_column - 1)) {
if (!m_world->organism(m_row, m_column - 1)) {
mapping.push_back(WEST);
}
}
return mapping;
};
int Organism::what(const int row, const int column) const {
if (!m_world->rangeCheck(row, column)) {
return VIBE_CHECK_OUT_OF_RANGE;
}
else if (!m_world->organism(row, column)) {
return VIBE_CHECK_NOTHING;
}
else {
return m_world->organism(row, column)->is();
}
}
vector<vector<int> > Organism::radar(const int distance) const {
vector<vector<int> > ret_veveii;
ret_veveii.resize(DIRECTIONS_QTY);
for (int offset = 1; offset <= distance; offset++) {
if (m_world->rangeCheck(m_row - offset, m_column)) {
ret_veveii.at(NORTH).push_back(what(m_row - offset, m_column));
}
}
for (int offset = 1; offset <= distance; offset++) {
if (m_world->rangeCheck(m_row, m_column + offset)) {
ret_veveii.at(EAST).push_back(what(m_row, m_column + offset));
};
};
for (int offset = 1; offset <= distance; offset++) {
if (m_world->rangeCheck(m_row + offset, m_column)) {
ret_veveii.at(SOUTH).push_back(what(m_row + offset, m_column));
};
};
for (int offset = 1; offset <= distance; offset++) {
if (m_world->rangeCheck(m_row, m_column - offset)) {
ret_veveii.at(WEST).push_back(what(m_row, m_column - offset));
};
};
return ret_veveii;
};
bool Organism::move() {
int directionChoice = chooseDirection(vibeCheck());
if (directionChoice >= 0 && directionChoice < DIRECTIONS_QTY) { // confidence check
switch(directionChoice) {
case NORTH:
m_world->uncoupleOrganism(this);
m_row--;
m_world->coupleOrganism(this);
return 1;
case EAST:
m_world->uncoupleOrganism(this);
m_column++;
m_world->coupleOrganism(this);
return 1;
case SOUTH:
m_world->uncoupleOrganism(this);
m_row++;
m_world->coupleOrganism(this);
return 1;
case WEST:
m_world->uncoupleOrganism(this);
m_column--;
m_world->coupleOrganism(this);
return 1;
default:
return 0;
};
}
else {
return 0;
}
}
int Organism::chooseDirection(const vector<int> in_veii) const {
if (in_veii.size() == 0) {
return -1;
}
else if (in_veii.size() == 1) {
return in_veii.at(0);
}
else {
nanoSeed();
int random = rand() % in_veii.size();
return in_veii.at(random);
}
}
Organism::~Organism() {
m_world->uncoupleOrganism(this);
}
#endif | true |
81a0e3ebaab16146819e8d760bb4f50a810fab17 | C++ | Mushfiqur719/Archive-Problem-Solving | /UVA/CP Book 4/Introduction/Getting Started The Easy Problems/1641 - ASCII Area.cpp | UTF-8 | 507 | 3.15625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int w,h,i,j;
while(cin>>h>>w)
{
char area[h][w];
int slash=0,dot=0;
for(i=0; i<h; i++)
{
for(j=0; j<w; j++)
{
cin>>area[i][j];
if(area[i][j]=='/' || area[i][j]=='\\')
slash++;
if(slash%2!=0 && area[i][j]=='.')
dot++;
}
}
cout<<(slash/2)+dot<<endl;
}
return 0;
}
| true |
47187dca9e1a5475d85feb961a6c74c220201b36 | C++ | GuodongQi/LeetCode | /by_tags/暴力枚举法/1_Subsets.cpp | UTF-8 | 578 | 2.921875 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> path;
subsets(nums,path,0,res);
return res;
}
void subsets(vector<int> &S, vector<int> &path, int step, vector<vector<int>> &result){
if(step == S.size()){
result.push_back(path);
return;
}
subsets(S, path, step+1,result);
path.push_back(S[step]);
subsets(S, path, step+1, result);
path.pop_back();
}
}; | true |
1ad037af81fd31f5ab5f1ddb273a176714e8a83a | C++ | wyf2123/paintDatFiles | /paintdat/algorithm.h | UTF-8 | 4,364 | 2.671875 | 3 | [] | no_license | #ifndef ALGORITHM_H
#define ALGORITHM_H
//#include "opencv2/highgui/highgui.hpp"
//#include "opencv2/core/core.hpp"
//#include "opencv2/imgproc/imgproc.hpp"
//#include "mysqlitepatients.h"
#include <stdio.h>
extern const double scaleRate;
//using namespace cv;
//using std::sort;
//using std::vector;
//struct PointDistance
//{
// Point point;
// double distance;
//};
enum CalculateType {TypeCornealCurvature,TypeWhiteToWhite,TypePupilDiameter};
class OpticsAlgorithm
{
public:
OpticsAlgorithm() {}
~OpticsAlgorithm() {}
// 交换
template<class T>
inline static void swap(T &v1, T &v2)
{
T vt = v1;
v1 = v2;
v2 = vt;
}
// 计算平均值
// inline static double average(const double *data, int size)
// {
// if(data==NULL || size<=0)
// return 0;
// double sum = 0;
// for(int i=0; i<size; i++)
// sum += data[i];
// return sum/size;
// }
// inline static double average(double d1,double d2, double d3=0, int size=3)
// {
// double data[3] = {0};
// data[0] = d1;
// data[1] = d2;
// data[2] = d3;
// return average(data,size);
// }
// 计算标准偏差
// inline static double standardDeviation(int size, double n1, double n2, double n3=0)
// {
// double data[3];
// data[0] = n1;
// data[1] = n2;
// data[2] = n3;
// return standardDeviation(data,size);
// }
// inline static double standardDeviation(const double *data, int size)
// {
// if(size <= 1)
// return 0;
// double sum = 0;
// for(int i=0; i<size; i++)
// sum += data[i];
// double avg = sum/size;
// double sumOfSquare = 0;
// for(int i=0; i<size; i++)
// sumOfSquare += (data[i]-avg)*(data[i]-avg);
// return sqrt(sumOfSquare/(size-1));
// }
// 角度有效性检测
// inline static void degreeIdentity(double *data, int size)
// {
// // 是否有相差大于90度
// bool diff = false;
// for(int i=0; i<size-1; i++)
// {
// if(abs(data[i]-data[i+1]) > 90)
// {
// diff = true;
// break;
// }
// }
// // 如果是,大于90度的值减去180
// if(diff)
// {
// for(int i=0; i<size; i++)
// if(data[i] > 90)
// data[i] -= 180;
// }
// }
// 计算两点距离
// inline static double twoPointsDistance(Point p1, Point p2)
// {
// return sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2));
// }
// 将点按照距离排序的比较函数
// inline static bool sortPoint(PointDistance pd1, PointDistance pd2)
// {
// return pd1.distance<pd2.distance;
// }
// 迭代最佳阈值法
static int getIterativeBestThreshold(int histGram[]);
// 轮廓大小过滤
// static void contoursFilter(vector< vector<Point> > &contours,double minArea=50);
// 角膜曲率算法
// static bool calculateCornealCurvature(const Mat &image, CornealCurvature &curve, QString saveFileName, int index);
// 圆检测算法,计算直径
// static bool roundDetection(const Mat &img, const QString &saveFileName, CalculateType type, double &diameter, double &barycenterDX, double &barycenterDY, double &kappaX, double &kappaY);
// 白到白
// static bool calculateWhiteToWhite(const Mat &img, WhiteToWhite &wtw, QString saveFileName);
// 计算瞳孔直径
// static bool calculatePupilDiameter(const Mat &img, PupilData &pupil, QString saveFileName);
inline static double DS(double AL, double K1, double K2)
{
return 81.915 - 1.953*AL - 0.569*K1 - 0.28*K2;
}
// 滤波函数
static void trmul(double *a,double *b,double *c,int m,int n,int k);
static int rinv(double *a,int n);
static void filter(const double *x, double *y, int xlen, double *a, double *b, int nfilt, double *zi);
static int filtfilt(double* x, double* y, int xlen, double* a, double* b, int nfilt);
// 曲线拟合
static int polyfit(const double *const independentVariables, const double *const dependentVariables, unsigned int countOfElements, unsigned int order, double *coefficients);
};
#endif // ALGORITHM_H
| true |
b9ce8c031e617957039f8af09209a3064d435c96 | C++ | Shubhamag12/Data-Structures-and-Algorithms | /Leetcode/maximum_binary_tree.cpp | UTF-8 | 1,231 | 2.859375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define pi 3.1415926536
#define ll long long int
#define mod 1000000007
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
int getMax(vector<int>nums,int low,int high){
int res=INT_MIN;
int i;
for(i=low;i<=high;i++){
res=max(res,nums[i]);
}
return i;
}
TreeNode*buildTree(vector<int>nums,int low,int high){
if(low>high)
return NULL;
int curr = getMax(nums,low,high);
TreeNode*root=new TreeNode(nums[curr]);
root->left = buildTree(nums,low,curr-1);
root->right = buildTree(nums,curr+1,high);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return buildTree(nums,0,nums.size()-1);
}
int main(){
fastio
vector<int>v={3,2,1,6,0,5};
cout<<constructMaximumBinaryTree(v)->val;
} | true |
e1395f81520960f96e1cbeb6d218c36cae240fe0 | C++ | ashkan65/SyncThreads | /sync_threads_class/read.cpp | UTF-8 | 628 | 2.890625 | 3 | [] | no_license | #include "read.hpp"
void read::GetParam(int * _buffer, std::atomic<short>* _available, std::atomic<bool>* _NewFrame, bool* _running){
buffer = _buffer;
available = _available;
NewFrame = _NewFrame;
running = _running;
read_loc = 2;
};
void read::Run(){
while(*running){
if ((*NewFrame).load()){
temp = *available;
*available = read_loc;
read_loc = temp;
std::cout << *(buffer + read_loc) << std::endl;
*NewFrame = false;
std::this_thread::sleep_for(std::chrono::microseconds(1)); //This is an artificial delay
}
else{
std::cout << "No frame to read!" << std::endl;
}
}
}; | true |
ea8aa9793d557ee73e002580a636a67f4f8c261f | C++ | blizmax/AntiradianceCuts | /Framework/OGLResources/COGLTextureBuffer.cpp | UTF-8 | 1,276 | 2.578125 | 3 | [] | no_license | #include "COGLTextureBuffer.h"
COGLTextureBuffer::COGLTextureBuffer(GLenum type, std::string const& debugName)
: COGLResource(COGL_TEXTURE_BUFFER, debugName), m_Type(type)
{
glGenTextures(1, &m_TextureBufferTexture);
glGenBuffers(1, &m_Resource);
CheckGLError(m_DebugName, "COGLTextureBuffer::COGLTextureBuffer()");
}
COGLTextureBuffer::~COGLTextureBuffer()
{
glDeleteTextures(1, &m_TextureBufferTexture);
glDeleteBuffers(1, &m_Resource);
CheckGLError(m_DebugName, "COGLTextureBuffer::~COGLTextureBuffer()");
}
void COGLTextureBuffer::SetContent(size_t size, GLenum usage, void* content)
{
m_size = size;
glBindBuffer(GL_TEXTURE_BUFFER, m_Resource);
glBufferData(GL_TEXTURE_BUFFER, size, content, usage);
glBindBuffer(GL_TEXTURE_BUFFER, 0);
CheckGLError(m_DebugName, "COGLTextureBuffer::SetContent()");
}
void COGLTextureBuffer::Bind(COGLBindSlot slot)
{
COGLResource::Bind(slot);
glActiveTexture(GetGLSlot(m_Slot));
glBindTexture(GL_TEXTURE_BUFFER, m_TextureBufferTexture);
glTexBuffer(GL_TEXTURE_BUFFER, m_Type, m_Resource);
CheckGLError(m_DebugName, "COGLTextureBuffer::Bind()");
}
void COGLTextureBuffer::Unbind()
{
COGLResource::Unbind();
glBindTexture(GL_TEXTURE_BUFFER, 0);
CheckGLError(m_DebugName, "COGLTextureBuffer::Unbind()");
}
| true |
73f7e9b4bb24046146b3c8b00d773beab4853c8d | C++ | DeadTSAR/otTeacher | /ЛЕКЦИИ (пятницы)/count, count_if.cpp | UTF-8 | 1,275 | 3.09375 | 3 | [] | no_license | //// ConsoleApplication71.cpp: определяет точку входа для консольного приложения.
////
//// ConsoleApplication71.cpp: определяет точку входа для консольного приложения.
////
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
setlocale(LC_CTYPE, "Rus");
const int N = 10;
int arr[N];
cout << "Size of arr array = " << sizeof(arr) / sizeof(arr[0]) << endl;
for (int i = 0; i < N; i++){
cin >> arr[i];
}
// подсчёт элементов, равных 0
int count = 0;
for (int i = 0; i < N; i++){
if (arr[i] == 0){
count++;
}
}
cout << "Ручной подсчёт нулей = " << count << endl;
cout << "std::count() для нулей = " << std::count(arr, arr + N, 0) << endl;
count = 0;
for (int i = 0; i < N; i++){
if (arr[i] % 2 == 0){
count++;
}
}
cout << "Ручной подсчёт чётных = " << count << endl;
cout << "std::count() для чётных = " << std::count_if(arr, arr + N,
[](int x){ /*return x % 2 == 0;*/
if (x % 2 == 0){
return true;
}
else{
return false;
}
}
) << endl;
for (int i = 0; i < N; i++){
cout << arr[i] << '\t';
}
return 0;
} | true |
df7568fbd0855803395b4531636dcba05a963087 | C++ | zmh009/Xieyi | /Xieyi/ZUdp.h | UTF-8 | 823 | 2.546875 | 3 | [] | no_license | #ifndef ZUDP_H
#define ZUDP_H
#include <iostream>
#include "ITransport.h"
struct UdpForm
{
u_char mSrcPort[2];
u_char mDesPort[2];
u_char mDataLen[2];
u_char mCheckSum[2];
u_char mData[0];
};
class ZUdp : public ITransport
{
public:
ZUdp();
~ZUdp();
const u_char *transportContent() const; //get the Content of transport layer
int transportLen() const;
void setTransportContent(const u_char *Content,int length); // set the Content of transport layer
const u_char *applicationContent() const; // get the Content of application layer
int applicationLen() const;
int srcPort() const;
int dstPort() const;
private:
int getPortFormat(const u_char *bytes) const;
private:
UdpForm *mUdpContent;
int mUdpLen;
int mApplicationLen;
};
#endif // ZUDP_H
| true |
ce4e699d85ab3e2ff4b7ec0a38aae59721ca7f84 | C++ | leobesen28/VendingMachine_STM32F4 | /Src/AdControl.cpp | ISO-8859-1 | 6,878 | 3 | 3 | [] | no_license | /*
-----------------------------------------------------
| FEDERAL UNIVERSITY OF SANTA CATARINA |
| C++ FOR EMBEDDED SYSTEMS |
| PROJECT: VENDING MACHINE |
| PROFESSOR: EDUARDO AUGUSTO BEZERRA |
| LEONARDO AURLIO BESEN |
| JOO BATISTA CORDEIRO NETO |
-----------------------------------------------------
*/
#include "AdControl.h"
/*
List of messages to be displayed
*/
uint8_t noAds[] = "No ads to display...";//22
uint8_t emptyList[] = "List is empty";//13
uint8_t receiveAd[] = "Add new ad?";
uint8_t deleteAd[] = "Delete ad?";
uint8_t writeAd[] = "Write new ad below:";
uint8_t adAdded[] = "Added new AD";
uint8_t adDeleted[] = "Deleted AD";
uint8_t maxAdSize[] = "maximum AD size";
uint8_t minAdSize[] = "Minimum AD size";
uint8_t addToDisplay[] = "Transfer new ads ";
uint8_t addedToDisplay[] = "Transfered new ads ";
//Debug - Initial ads
char adv1[] = "--Leonardo Besen--";
char adv2[] = "---Joao Batista---";
//Constructor
AdControl::AdControl(OutputInterface* output, InputInterface* input){
outputPtr = output;//Set output interface
inputPtr = input;
//Initial advertisements - DEBUG test
Ad ad1(adv1); //create ad1
Ad ad2(adv2); //create ad2
displayAds.insertAfterLast(ad1); //insert ad1 in the displayAds queue
displayAds.insertAfterLast(ad2); //insert ad2 in the displayAds queue
}
AdControl::~AdControl(void){}
//Transfer the ads located in NewAds to DisplayAds
//Using overload of the operator +
void AdControl::addNewAds(void){
if(newAds.getHead() == 0){
outputPtr->printToUser(7, noAds, 22);
}else{
while(newAds.getHead() != 0){
displayAds.insertAfterLast(newAds.removeFirst());
}
}
}
//Display an Ad
void AdControl::sendAdToDisplay(uint32_t randomNumber, uint8_t* hour, uint8_t* date){
char* pfrom; //Local variable used to get an ad
uint8_t toDisplay[20]; //Local variable to store an ad and send it to the output interface
static char j = 0x03; //Controls the Hour/Date randomic presentation
//Get an ad from displayAds queue if it exist
if(displayAds.getHead() == 0){
outputPtr->clearLCD(5);
outputPtr->printToUser(10, emptyList, 13);
}else{
nowInDisplay = displayAds.removeFirst();
nowInDisplay.getAd(pfrom);
//char to uint8_t - the output only accepts uint8_t type
for(int i = 0; i < 20; i++){
toDisplay[i] = pfrom[i];
}
//clear and print an ad
outputPtr->clearLCD(5);
outputPtr->printToUser(10, toDisplay, sizeof(toDisplay));
//Control of the Hour/Date randomic presentation
//RNG generates and randomic number of 32 bits size
//The size was divided in four identical parts
//Each part will assign j with a different value between 3 and 6
if(j < 0x01){
if(randomNumber > 0x00000000 && randomNumber <= 0x3FFFFFFF)
j = 0x03;
else if(randomNumber > 0x3FFFFFFF && randomNumber <= 0x7FFFFFFF)
j = 0x04;
else if(randomNumber > 0x7FFFFFFF && randomNumber <= 0xBFFFFFFF)
j = 0x05;
else if(randomNumber > 0xBFFFFFFF && randomNumber <= 0xFFFFFFFF)
j = 0x06;
//print date and hour only when j = 0
outputPtr->printToUser(13, hour, 21);
outputPtr->printToUser(14, date, 21);
//If (j != 0) it will just clear the output and decrement j
}else if(j>=0x01){
j--;
outputPtr->clearLCD(13);
}
}
}
//Return the Ad from the display to the end of the list
void AdControl::getAdFromDisplay(void){
displayAds.insertAfterLast(nowInDisplay);
}
//Receive new ad from user
uint8_t AdControl::getAdFromUser(uint16_t GPIO_Pin){
static char addAd = 0x00; //keep state of adding a new ad
char delAd = 0x00; //inform if the user wants to delete the current ad
uint8_t status = 0x00; //not ready
static char text[20] = {97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97,97}; //ASCII 'a'
uint8_t display[20]; //print to user the current written message
static int j = 1; //
//Display info messages to the user
if(addAd == 0x00){
outputPtr->clearLCD(5);
outputPtr->printToUser(9, receiveAd, 20);
outputPtr->printToUser(10, deleteAd, 20);
outputPtr->printToUser(11, addToDisplay, 17);
}
//Checks what button was pressed
if(GPIO_Pin == GPIO_PIN_1){
outputPtr->clearLCD(5);
outputPtr->printToUser(9, writeAd, 20);
addAd = 0x01;
}else if(GPIO_Pin == GPIO_PIN_4){
outputPtr->clearLCD(5);
outputPtr->printToUser(9, adDeleted, 20);
delAd = 0x01;
}else if(GPIO_Pin == GPIO_PIN_5){
addNewAds(); // transfers ads from newAds to displayAds
status = 0x01; //status ready
outputPtr->clearLCD(5);
outputPtr->printToUser(10, addedToDisplay, 19);
}
//Routine to add a new advertisement
if(addAd == 0x01){
if(GPIO_Pin == GPIO_PIN_11){ //GPIO PC11 pressed - increment value in the current text vector position
text[j-1]++;
for(int i = 0; i < j; i++){ //get the current written message
display[i] = text[i];
}
//clear the output and display the current written message
outputPtr->clearLCD(5);
outputPtr->printToUser(10, display, j);
}else if(GPIO_Pin == GPIO_PIN_2){ //GPIO PD2 pressed - decrement value in the current text vector position
text[j-1]--;
for(int i = 0; i < j; i++){
display[i] = text[i]; //get the current written message
}
//clear the output and display the current written message
outputPtr->clearLCD(5);
outputPtr->printToUser(10, display, j);
}else if(GPIO_Pin == GPIO_PIN_7){ //GPIO PD7 pressed - next vector text position
if(j<=20) //checks maximum size
j++;
else{
outputPtr->clearLCD(5);
outputPtr->printToUser(10, maxAdSize, 17);
}
}else if(GPIO_Pin == GPIO_PIN_8){ //GPIO PC8 pressed - next vector text position
if(j>1) //checks minimum size
j--;
else{
outputPtr->clearLCD(5);
outputPtr->printToUser(10, minAdSize, 17);
}
}else if(GPIO_Pin == GPIO_PIN_9){ //GPIO PG9 pressed - stops advertisements receiving
for(int d = 20; d >= j; d--){ //clear unwanted values in not written positions of the text vector
text[d] = 0;
}
Ad ad(text); //creat an object with the new ad
newAds.insertAfterLast(ad); //Inset the new ad in the queue
status = 0x01; //status ready
//Set initial values
addAd = 0x00;
j = 1;
for(int i = 0; i < 20; i++){
text[i] = 97;
}
//clear output and send info message
outputPtr->clearLCD(5);
outputPtr->printToUser(9, adAdded, 20);
}
return status;
}else if(delAd == 0x01){
delAd = 0x00;
//To delete an advertisement, just send another ad without getting back the ad you want to delete
sendAdToDisplay(0,0,0);
status = 0x01; //status ready
return status;
}
return status;
}
| true |
cf0381f5b7e1257c981817aca0cc62931d15f359 | C++ | micmr0/SpaceWar | /src/GKiW_Lab6/Space.cpp | WINDOWS-1250 | 1,722 | 2.59375 | 3 | [] | no_license | #include "StdAfx.h"
#include "Space.h"
CSpace::CSpace(void) : CSceneObject()
{
}
CSpace::~CSpace(void)
{
}
void CSpace::Initialize(void)
{
_displayListId = glGenLists(1);
glNewList(_displayListId, GL_COMPILE);
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
//glFrontFace(GL_CW);
// Ustawienie sposobu teksturowania - GL_MODULATE sprawia, e wiato ma wpyw na tekstur; GL_DECAL i GL_REPLACE rysuj tekstur tak jak jest
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
_spaceTexture = new CTexture("Resources\\kosmos.bmp", GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR);
_spaceTexture->Load();
GLUquadricObj *sphere;
sphere = gluNewQuadric();
gluQuadricDrawStyle(sphere, GLU_FILL);
gluQuadricNormals(sphere, GLU_SMOOTH);
gluQuadricOrientation(sphere, GLU_INSIDE);
gluQuadricTexture(sphere, GL_TRUE);
// Wybr tekstury korzystajc z jej id
//glBindTexture(GL_TEXTURE_2D, _skyTexture->GetId());
glPushMatrix();
glRotatef(100, 1.0f, 0.0f, 0.0f);
gluSphere(sphere, 30.0f, 80, 80);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
//glFrontFace(GL_CCW);
glEnable(GL_LIGHTING);
glEndList();
}
void CSpace::Update(void)
{
//Rotation.y -= 0.015f;
}
void CSpace::Render(void)
{
glPushMatrix();
glTranslatef(Position.x, Position.y, Position.z);
glRotatef(Rotation.x, 1.0f, 0.0f, 0.0f);
glRotatef(Rotation.y, 0.0f, 1.0f, 0.0f);
glRotatef(Rotation.z, 0.0f, 0.0f, 1.0f);
//glEnable(GL_TEXTURE_2D);
//glBindTexture(GL_TEXTURE_2D, _skyTexture->GetId());
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glCallList(_displayListId);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
| true |
1e28ca1517f266746bdf0ae1d01ef1f3431cc49a | C++ | BluesHaru/Practice | /BOJ/10807_개수 세기.cpp | UHC | 984 | 3.1875 | 3 | [] | no_license | /*---------------------------------------------------
10807
迭
: N ־ , v ϴ α ۼϽÿ.
:
Input) ù° ٿ N(1 N 100) ־. ° ٿ еǾִ.
° ٿ ã ϴ v ־. Է ־ v -100 ũų , 100 ۰ų .
Output) ù° ٿ Է ־ N ߿ v Ѵ.
----------------------------------------------------*/
#pragma warning(disable:4996)
#include <stdio.h>
using namespace std;
int arr[201];
int main()
{
int N;
scanf("%d", &N);
for (int i = 0; i < N; ++i)
{
int idx;
scanf("%d", &idx);
++arr[idx + 100];
}
int findIdx;
scanf("%d", &findIdx);
printf("%d\n", arr[findIdx + 100]);
return 0;
} | true |
75cd42db7f1a57c8e314c77c649db7b95ffb0a3d | C++ | rovinbhandari/Programming_Scripting | /ACM-ICPC/ACM-ICPC_12/Amritapuri/online contest/ACM-ICPC Amritapuri 2012 Online Competition Accepted Solutions/E/cpp/00013096_E_SEQUENCES_amicpc120839.cpp | UTF-8 | 2,690 | 2.734375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string>
using namespace std;
#include<math.h>
template<class T>
class SegmentTree
{
int *A,size;
public:
SegmentTree(int N)
{
int x = (int)(ceil(log2(N)))+1;
size = 2*(int)pow(2,x);
A = new int[size];
for(int i=0;i<N;i++)
A[i]=-1;
}
void initialize(int node, int start,int end, T *array)
{
if (start==end)
A[node] = start;
else
{
int mid = (start+end)/2;
initialize(2*node,start,mid,array);
initialize(2*node+1,mid+1,end,array);
if (array[A[2*node]]>=array[A[2*node+1]])
A[node] = A[2 * node];
else
A[node] = A[2 * node + 1];
}
}
int query(int node, int start,int end, int i, int j, T *array)
{
int id1,id2;
if (i>end || j<start)
return -1;
if (start>=i && end<=j)
return A[node];
int mid = (start+end)/2;
id1 = query(2*node,start,mid,i,j,array);
id2 = query(2*node+1,mid+1,end,i,j,array);
if (id1==-1)
return id2;
if (id2==-1)
return id1;
if (array[id1]>=array[id2])
return id1;
else
return id2;
}
};
void print(int *A, int N)
{
printf("[");
for(int i=0;i<N;i++)
printf("%d ",A[i]);
printf("]\n");
}
int main()
{
int T;
scanf("%d",&T);
for(int t=0;t<T;t++)
{
int N;
scanf("%d",&N);
char *S=(char *)malloc(N*sizeof(char));
scanf("%s",S);
int *Z=(int *)malloc(N*sizeof(int)); //number of zeros <i
int *O=(int *)malloc(N*sizeof(int)); //number of ones >i
O[N-1]=0;
if(S[0]=='0')
Z[0]=0;
for(int i=1;i<N;i++)
{
if(S[i-1]=='0')
Z[i]=1+Z[i-1];
else
Z[i]=Z[i-1];
}
for(int i=N-1;i>=1;i--)
{
if(S[i]=='1')
O[i-1]=1+O[i];
else
O[i-1]=O[i];
}
int *Sum=(int *)malloc(N*sizeof(int)); //number of ones >i
for(int i=0;i<N;i++)
Sum[i]=Z[i]+O[i];
//print(Z,N);
//print(O,N);
SegmentTree<int> s(N);
s.initialize(1,0,N-1,Sum);
int Q;
scanf("%d",&Q);
for(int q=0;q<Q;q++)
{
int a,b;
scanf("%d %d",&a,&b);
a--;b--;
if(a==b)
{
printf("1\n");
continue;
}
//printf("for range: (%d, %d) \n",a,b);
int zeros_a=Z[a];
int ones_b=O[b];
int query=Sum[s.query(1,0,N-1,a,b,Sum)];
//printf("zeros_a= %d, ones_b= %d, query= %d\n: \n",zeros_a,ones_b,query);
printf("%d\n",(query-zeros_a-ones_b)+1);
}
free(S);
free(Z);
free(O);
free(Sum);
}
}
| true |
ac5a4e5729ccacb780c4e262529543219a934dd4 | C++ | pedris11s/coj-solutions | /lmm-p2171-Accepted-s552992.cpp | UTF-8 | 567 | 2.8125 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int freq[1000001];
int main()
{
int N;
cin >> N;
int min_a = (1 << 30), max_b = 0;
for(int i = 1; i <= N; i++)
{
int a, b;
cin >> a >> b;
freq[a]++;
freq[b + 1]--;
min_a = min(a, min_a);
max_b = max(b, max_b);
}
int sol = 0;
for(int i = min_a; i <= max_b; i++)
{
freq[i] += freq[i - 1];
if(freq[i] > sol)
sol = freq[i];
}
cout << sol << endl;
return 0;
}
| true |
b4cd6880e05c0a8750dff6ba1f6ed588fd7c9b3f | C++ | bluemellophone/JTM-Protocol | /atm.cpp | UTF-8 | 18,927 | 2.75 | 3 | [] | no_license | /**
@file atm.cpp
@brief Top level ATM implementation file
*/
#include "util.h"
int getch()
{
int ch;
struct termios t_old, t_new;
tcgetattr(STDIN_FILENO, &t_old);
t_new = t_old;
t_new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &t_new);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &t_old);
return ch;
}
std::string getPin(std::string prompt)
{
std::string pin;
unsigned char ch = 0;
cout << prompt;
while((ch = getch()) != 10 && pin.length() <= 6) // Enter
{
if(ch == 127) // Backspace
{
if(pin.length() != 0)
{
cout <<"\b \b";
pin.resize(pin.length() - 1);
}
}
else if('0' <= ch && ch <= '9')
{
pin += ch;
cout << '*';
}
}
printf("\n");
return pin;
}
void* formATMHandshake(char packet[], std::string atmNonce)
{
std::vector<std::string> tempVector;
tempVector.push_back((std::string) "handshake");
tempVector.push_back(atmNonce);
formPacket(packet, 512, tempVector);
}
void* formATMPacket(char packet[], std::string command, std::string username, std::string cardHash, std::string pin, std::string item1, std::string item2, std::string atmNonce, std::string bankNonce)
{
std::vector<std::string> tempVector;
tempVector.push_back(command);
tempVector.push_back(username);
tempVector.push_back(cardHash);
tempVector.push_back(pin);
tempVector.push_back(item1);
tempVector.push_back(item2);
tempVector.push_back(atmNonce);
tempVector.push_back(bankNonce);
formPacket(packet, 1023, tempVector);
}
int main(int argc, char* argv[])
{
char packet[1024];
char epacket[1408];
char hpacket[1041];
char buf[50];
std::vector<std::string> bufArray;
std::string command;
std::string username;
std::string cardHash;
std::string pin;
std::string item1;
std::string item2;
std::string atmNonce;
std::string bankNonce;
std::string temp;
std::string status;
std::string sessionAESKey;
std::string sessionAESBlock;
std::string encryptedPacket;
std::string decryptedPacket;
std::string errorString = "Error. Please contact the service team.\n";
int length;
int userTimeout = 0;
int messageTimeout = 0;
int sessionTimeout = 0;
bool sendPacket = false;
bool printError = false;
bool userLoggedIn = false;
bool validHandshake = false;
if(argc != 2)
{
printf("Usage: atm proxy-port\n");
return -1;
}
//socket setup
unsigned short proxport = atoi(argv[1]);
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(!sock)
{
printf("fail to create socket\n");
return -1;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(proxport);
unsigned char* ipaddr = reinterpret_cast<unsigned char*>(&addr.sin_addr);
ipaddr[0] = 127;
ipaddr[1] = 0;
ipaddr[2] = 0;
ipaddr[3] = 1;
if(0 != connect(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)))
{
printf("fail to connect to proxy\n");
return -1;
}
while(1)
{
sendPacket = false;
printError = false;
command = "";
item1 = "NOT USED";
item2 = "NOT USED";
buf[0] = '\0';
packet[0] = '\0';
epacket[0] = '\0';
hpacket[0] = '\0';
// Print the prompt
printf("atm> ");
fgets(buf, 49, stdin);
buf[strlen(buf)-1] = '\0'; //trim off trailing newline
// Parse data
bufArray.clear();
bufArray = split((std::string) buf, ' ', bufArray);
//input parsing
if(bufArray.size() >= 1 && ((std::string) "") != bufArray[0])
{
if(time(NULL) - userTimeout <= 90 || !userLoggedIn)
{
command = bufArray[0];
}
else
{
command = "timeout";
}
userTimeout = time(NULL);
if(time(NULL) - sessionTimeout > 180)
{
validHandshake = false;
}
if(((std::string) "login") == command)
{
if(!userLoggedIn)
{
if(bufArray.size() == 2)
{
temp = bufArray[1];
temp = temp.substr(0,32);
std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
temp = toAlpha(temp);
std::string cardFilename = "cards/" + temp + ".card";
std::ifstream cardFile(cardFilename.c_str());
if(cardFile)
{
sendPacket = true;
username = temp;
cardHash = getCardHash(cardFilename);
pin = getPin("PIN: ");
pin = pin.substr(0,6);
while(pin.length() < 6)
{
pin = pin + "0";
}
pin = toNumbers(pin);
}
else
{
temp = "";
cout << "ATM card not found.\n";
}
}
else
{
cout << "Usage: login [username]\n";
}
}
else
{
cout << "User already logged in. Due to this action, the current user has now been logged out. \n";
sendPacket = true;
command = "logout";
}
}
else if(((std::string) "balance") == command)
{
if(userLoggedIn)
{
if(bufArray.size() == 1)
{
sendPacket = true;
}
else
{
cout << "Usage: balance\n";
}
}
else
{
cout << "User not logged in. \n";
}
}
else if(((std::string) "withdraw") == command)
{
if(userLoggedIn)
{
if(bufArray.size() == 2 && isNumbersOnly(bufArray[1]))
{
sendPacket = true;
item1 = bufArray[1];
}
else
{
cout << "Usage: withdraw [whole dollar amount]\n";
}
}
else
{
cout << "User not logged in. \n";
}
}
else if(((std::string) "transfer") == command)
{
if(userLoggedIn)
{
if(bufArray.size() == 3 && isNumbersOnly(bufArray[1]))
{
sendPacket = true;
item1 = bufArray[1];
item2 = bufArray[2];
}
else
{
cout << "Usage: transfer [whole dollar amount] [username]\n";
}
}
else
{
cout << "User not logged in. \n";
}
}
else if(((std::string) "logout") == command || ((std::string) "timeout") == command)
{
if(userLoggedIn)
{
if(bufArray.size() == 1 || ((std::string) "timeout") == command)
{
if(((std::string) "timeout") == command)
{
cout << "Timeout: user inactivity has caused a timeout, the current user has now been logged out.\n";
}
sendPacket = true;
command = "logout";
}
else
{
cout << "Usage: logout\n";
}
}
else
{
cout << "User not logged in. \n";
}
}
else
{
cout << "Command '" << command << "' not recognized.\n";
}
if(sendPacket)
{
if(!validHandshake)
{
bankNonce = "";
sessionAESKey = "";
sessionAESBlock = "";
atmNonce = getRandom(32);
formATMHandshake(hpacket, atmNonce);
encryptedPacket = encryptRSAPacket((std::string) hpacket, "keys/bank.pub");
for(int i = 0; i < encryptedPacket.length(); i++)
{
hpacket[i] = encryptedPacket[i];
}
length = strlen(hpacket);
if(sizeof(int) != send(sock, &length, sizeof(int), 0))
{
break;
}
if(length != send(sock, (void*)hpacket, length, 0))
{
break;
}
hpacket[0] = '\0';
if(sizeof(int) != recv(sock, &length, sizeof(int), 0))
{
break;
}
if(length != recv(sock, hpacket, length, 0))
{
break;
}
if(length == 1040)
{
decryptedPacket = decryptRSAPacket((std::string) hpacket, "keys/atm");
bufArray.clear();
bufArray = split(decryptedPacket, ',', bufArray);
if(bufArray.size() == 7)
{
if(compareSHA512Hash(bufArray[6], bufArray[0] + "," + bufArray[1] + "," + bufArray[2] + "," + bufArray[3] + "," + bufArray[4] + "," + bufArray[5]))
{
if(atmNonce == bufArray[1])
{
atmNonce = getRandom(32);
if(((std::string) "handshake") == bufArray[0])
{
bankNonce = bufArray[2];
sessionAESKey = bufArray[3];
sessionAESBlock = bufArray[4];
validHandshake = true;
sessionTimeout = time(NULL);
}
else if(((std::string) "error") == bufArray[0])
{
printError = true;
}
}
else
{
printError = true;
}
}
else
{
printError = true;
}
}
else
{
printError = true;
}
}
}
if(validHandshake)
{
messageTimeout = time(NULL);
atmNonce = getRandom(32);
formATMPacket(packet, command, username, cardHash, pin, item1, item2, atmNonce, bankNonce);
encryptedPacket = encryptAESPacket((std::string) packet, sessionAESKey, sessionAESBlock);
for(int i = 0; i < encryptedPacket.length(); i++)
{
epacket[i] = encryptedPacket[i];
}
length = encryptedPacket.length();
if(sizeof(int) != send(sock, &length, sizeof(int), 0))
{
printf("fail to send packet length\n");
break;
}
if(length != send(sock, (void*)epacket, length, 0))
{
printf("fail to send packet\n");
break;
}
epacket[0] = '\0';
packet[0] = '\0';
if(sizeof(int) != recv(sock, &length, sizeof(int), 0))
{
printf("fail to read packet length\n");
break;
}
if(length > 1408)
{
printf("packet too long\n");
}
if(length != recv(sock, epacket, length, 0))
{
printf("fail to read packet\n");
break;
}
else if(length == 1408)
{
if(time(NULL) - messageTimeout < 30) // Bank Response needs to be in less that 30 seconds.
{
decryptedPacket = decryptAESPacket((std::string) epacket, sessionAESKey, sessionAESBlock);
bufArray.clear();
bufArray = split(decryptedPacket, ',', bufArray);
if(bufArray.size() == 6)
{
if(compareSHA512Hash(bufArray[5], bufArray[0] + "," + bufArray[1] + "," + bufArray[2] + "," + bufArray[3] + "," + bufArray[4]))
{
if(atmNonce == bufArray[2])
{
atmNonce = getRandom(32);
command = bufArray[0];
status = bufArray[1];
bankNonce = bufArray[3];
if(((std::string) "login") == command)
{
userLoggedIn = true;
cout << status;
}
else if(((std::string) "balance") == command)
{
cout << status;
}
else if(((std::string) "withdraw") == command)
{
cout << status;
}
else if(((std::string) "transfer") == command)
{
cout << status;
}
else if(((std::string) "logout") == command)
{
cout << status;
userTimeout = 0;
messageTimeout = 0;
sessionTimeout = 0;
sessionAESKey = "";
sessionAESBlock = "";
validHandshake = false;
userLoggedIn = false;
username = "";
cardHash = "";
pin = "";
}
else if(((std::string) "error") == command)
{
cout << status;
}
}
else
{
printError = true;
}
}
else
{
printError = true;
}
}
else
{
printError = true;
}
cout << endl;
}
else
{
printError = true;
}
}
}
else
{
printError = true;
}
}
if(printError)
{
cout << errorString;
}
}
else
{
cout << "Usage: [command] [argument...]\n";
}
}
//cleanup
close(sock);
return 0;
}
| true |
eb6b02ac5b6dcd0a05c0adf78accd0a7a0353d2f | C++ | pbssarath/excitonic_drift_diffusion | /include/initial_guess.h | UTF-8 | 6,809 | 2.890625 | 3 | [
"MIT"
] | permissive | /*
Copyright 2016-2017 Baskar Ganapathysubramanian
This file is part of TALYFem.
TALYFem is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 2.1 of the
License, or (at your option) any later version.
TALYFem is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with TALYFem. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INCLUDE_INITIALGUESS_H_
#define INCLUDE_INITIALGUESS_H_
#include <string> // for error string on construction
/**
* Class calculates the initial value at a node.
*
* The values are calculated as the following:
* 1 -> v = -Y + 0.5
* 2 -> n = exp(-60 Y)
* 3 -> p = exp(60(Y-1))
* 4 -> x = 0
* * Usage:
* InitialGuess sol(n_dimensions, p_grid);
* double intial_value = sol.ValueAt(node_id);
*
* Class is also responsible too find valueFEM and ValueDerivativeFEM for Hermite Basis function
*
* Usage:
* InitialGuess sol(n_dimensions, p_grid);
* double intial_value = sol.ValueAt(node_id);
*/
class InitialGuess {
public:
InitialGuess(int n_dimensions, GRID *p_grid, GridField<DDNodeData> *p_data) : n_dimensions_(n_dimensions),
p_grid_(p_grid), p_data_(p_data) {
if (n_dimensions_ < 1 || n_dimensions_ > 3) {
throw (std::string("Invalid number of dimensions in initial_guess."));
}
}
~InitialGuess() {
}
/**
* Returns the value at the given node at time zero.
*
* @param node_id ID of node where the value will be calculated.
* @return value of initial guess for the given node
*/
double ValueAt(int node_id, int n_dof) const {
const ZEROPTV &pNode = p_grid_->GetNode(node_id)->location(); // node we care about
double value = 1.0;
double scale = 0.0258520269359094;
switch (n_dof % 12) {
case 0: {
value *= 1. / scale * (0.5 - pNode(1));
break;
}
case 1: {
value *= exp(-60 * pNode(1));
break;
}
case 2: {
value *= exp(60 * (pNode(1) - 1));
break;
}
case 3: {
value *= 0;
break;
}
}
return value;
}
/**
* The library has a built-in function GridField::valueFEM that is used to calculate the interpolated
* node value at the gauss point. However, the library's implementation assumes that the hermite
* derivatives are stored contiguously (at index + 1, index + 2, index +3, etc.) This code stores
* the hermite derivatives in a stride (at index + 4*1, index + 4*2, index + 3*4, etc.), so we have
* our own valueFEM function to interpolate values when using hermite derivatives.
* @param index index of the variable to interpolate
* @param dof the total number of degrees of freedom
* @returns variable[index] at fe.position()
*/
double valueFEM(const FEMElm &fe, int index, int dof) const {
double sum = 0.0;
if (fe.basis_function() == BASIS_HERMITE) {
// Hermite is a special case - some basis functions are derivatives.
// This assumes the node data is stored such that u = index
// and du_x = index + 1, du_y = index + 2, etc.
// 1D: -, x
// 2D: -, x, y, xy
// 3D: -, x, y, z, xy, xz, yz, xyz
const int nbf = fe.nbf();
const int nbf_per_node = fe.nbf_per_node();
for (int a = 0; a < nbf; a++) {
const int node_idx = fe.elem()->ElemToLocalNodeID(a / nbf_per_node);
const int deriv = a % nbf_per_node;
// DIFFERENT FROM LIBRARY: deriv is multiplied by dof!
sum += fe.N(a) * this->p_data_->GetNodeData(node_idx).value(index + deriv * dof);
}
} else {
const int nbf = fe.nbf();
for (ElemNodeID a = 0; a < nbf; a++) {
const int node_index = fe.elem()->ElemToLocalNodeID(a);
sum += fe.N(a) * this->p_data_->GetNodeData(node_index).value(index);
}
}
return sum;
}
/**
* The library has a built-in function GridField::valueDerivativeFEM that is used to calculate the interpolated
* node derivative values at the gauss point. However, the library's implementation assumes that the hermite
* derivatives are stored contiguously (at index + 1, index + 2, index +3, etc.) This code stores
* the hermite derivatives in a stride (at index + 4*1, index + 4*2, index + 3*4, etc.), so we have
* our own valueDerivativeFEM function to interpolate values when using hermite derivatives.
* @param index index of the variable to interpolate
* @param dof the total number of degrees of freedom
* @returns derivative of variable[index] at fe.position()
*/
double valueDerivativeFEM(const FEMElm &fe, int index, int dir, int dof) const {
double sum = 0.0;
if (fe.basis_function() == BASIS_HERMITE) {
const int nbf = fe.nbf();
const int nbf_per_node = fe.nbf_per_node();
for (int a = 0; a < nbf; a++) {
const int node_idx = fe.elem()->ElemToLocalNodeID(a / nbf_per_node);
const int deriv = a % nbf_per_node;
sum += fe.dN(a, dir) * this->p_data_->GetNodeData(node_idx).value(index + deriv * dof);
}
} else {
const int nbf = fe.nbf();
for (ElemNodeID a = 0; a < nbf; a++) {
const int node_index = fe.elem()->ElemToLocalNodeID(a);
sum += fe.dN(a, dir) * this->p_data_->GetNodeData(node_index).value(index);
}
}
return sum;
}
double dot(ZEROPTV &idx_1, ZEROPTV &idx_2, int nsd = 2) const {
double sum = 0.0;
if (nsd == 2) {
sum += idx_1(0) * idx_2(0) + idx_1(1) * idx_2(1);
} else if (nsd == 3) {
sum += idx_1(0) * idx_2(0) + idx_1(1) * idx_2(1) + idx_1(2) * idx_2(2);
}
return (sum);
}
private:
int n_dimensions_; ///< number of spatial dimensions of system (1, 2, or 3)
GRID *p_grid_; ///< pointer to grid
GridField<DDNodeData> *p_data_; ///< pointer to grid field data
};
#endif // INCLUDE_HTANALYTICSOLUTION_H_
| true |
17b782180c38c11eb39e659c853fccaf263572a2 | C++ | eightnoteight/compro | /spoj/factcg.2.cc | UTF-8 | 4,925 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int32_t primes[65] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313}; // there are 446 primes under 10000000
int32_t sieve(int32_t n, int32_t* primes)
{
vector<bool> arr(n, true);
for (int32_t x = 4; x < n; x += 2)
{
arr[x] = false;
}
int32_t csn = ceil(sqrt(n));
for (int32_t x = 3; x < csn; ++x)
if(arr[x])
for (int32_t y = x*x; y < n; y += 2*x)
arr[y] = false;
primes[0] = 2;
csn = 1;
for (int x = 3; x < n; x += 2)
if(arr[x])
primes[csn++] = x;
return csn;
}
int32_t factors(int32_t n, int32_t* arr)
{
arr[0] = 1;
if (n == 1)
{
return 1;
}
int32_t arri = 1;
for(int32_t i = 0; i < 65;i++)
{
if(primes[i] > n)
break;
while((n % primes[i]) == 0)
{
n /= primes[i];
arr[arri++] = primes[i];
}
}
if(n != 1)
arr[arri++] = n;
return arri;
}
inline long long int glong()
{
long long int n = 0;
int sign=1;
register char c=0;
while(c<33){
c=getchar_unlocked();
if(c == -1)
return -1;
}
if (c=='-')
{
sign=-1;
c=getchar_unlocked();
}
while(c>='0'&&c<='9')
{
n=(n<<3)+(n<<1)+(c-'0');
c=getchar_unlocked();
if(c == -1)
return n*sign;
}
return n*sign;
}
void pint(int32_t a)
{
register char c;
char num[20];
int16_t i = 0;
if(a < 0){
putchar_unlocked('-');
a *= -1;
}
do
{
num[i++] = a%10 + 48;
a /= 10;
} while (a != 0);
i--;
while (i >= 0)
putchar_unlocked(num[i--]);
}
int32_t modpow(int32_t a, int32_t b, int32_t mod)
{
if(b == 1)
return a % mod;
if(b % 2){
int32_t tmp = modpow(a, b / 2, mod);
return (a * ((tmp*tmp) % mod)) % mod;
}
else {
int32_t tmp = modpow(a, b / 2, mod);
return (tmp*tmp) % mod;
}
}
void divmod(int32_t a, int32_t b, int32_t& q, int32_t& r)
{
q = a / b;
r = a % b;
}
bool try_composite(int32_t a, int32_t s, int32_t d, int32_t n)
{
if(modpow(a, d, n) == 1)
return false;
for(int16_t i = 0; i < s; i++)
if(modpow(a, pow(2, i)*d, n) == n - 1)
return false;
return true;
}
bool is_probable_prime(int32_t n)
{
// error for n < 2
if(n == 2)
return true;
if ((n % 2) == 0)
return false;
int32_t s = 0;
int32_t d = n - 1;
while(true)
{
int32_t q, r;
divmod(d, 2, q, r); // get this thing
if(r == 1)
break;
s++;
d = q;
}
for(int16_t i = 0; i < 5; i++) {
int32_t a = random() % (n - 2) + 2;
if(try_composite(a, s, d, n))
return false;
}
return true;
}
void fermatfactors(int32_t n, int32_t& f1, int32_t& f2)
{
long long int a = ceilf(sqrt(n));
long long int b2 = a*a - n;
if (n % 2 == 0)
{
f1 = 2;
f2 = n / 2;
return;
}
//cout << a <<" " << b2<< '\n';
while(fabs(sqrt(b2) - round(sqrt(b2))) > 0.0001) {
a++;
b2 = a*a - n;
}
f1 = (int32_t)(a - sqrt(b2));
f2 = (int32_t)(a + sqrt(b2));
return;
}
int32_t fermatfactorize(int32_t n, int32_t* arr)
{
arr[0] = 1;
if(n == 1) {
return 1;
}
stack<int32_t> st;
if(is_probable_prime(n)){
arr[1] = n;
return 2;
}
int32_t arri = 1;
st.push(n);
while(st.size() != 0) { // check it's complexity in cppman
int32_t f1, f2;
n = st.top();
st.pop();
fermatfactors(n, f1, f2);
cout << "-----" << "n = " << n << "; f1 = " << f1 << "; f2 = " << f2 << '\n';
if(f1 > 1 and is_probable_prime(f1))
arr[arri++] = f1;
else if(f1 > 1)
st.push(f1);
if(f2 > 1 and is_probable_prime(f2))
arr[arri++] = f2;
else if(f2 > 1)
st.push(f2);
}
sort(arr, arr + arri);
return arri;
}
int main(int argc, char *argv[])
{
int32_t arr[30];
int32_t count;
long long int n;
//sieve(ceil(sqrt(100001)), primes);
while((n = glong()) != -1)
{
//count = fermatfactorize(n, arr);
count = factors(n, arr);
//pint(n);
//putchar_unlocked(':');
pint(1);
for (int x = 1; x < count; ++x)
{
putchar_unlocked(' ');
putchar_unlocked('x');
putchar_unlocked(' ');
pint(arr[x]);
}
putchar_unlocked('\n');
}
return 0;
}
| true |
2bb6d736efd8cfa735cf57016cc11466f5fc6b0d | C++ | dastyk/SE | /SluaghEngine/includes/Utilz/Delegate.h | UTF-8 | 4,752 | 2.9375 | 3 | [] | no_license | #ifndef SE_UTILZ_DELEGATE_H_
#define SE_UTILZ_DELEGATE_H_
#include <functional>
namespace SE
{
namespace Utilz
{
template <typename T> class Delegate;
template<typename RET, typename... PARAMS>
class Delegate<RET(PARAMS...)>
{
std::function<RET(PARAMS...)> invoker;
//size_t uniqueIdentifier;
public:
Delegate() {}
operator bool() { return invoker.operator bool(); }
/**
*@brief Copy constructor.
*/
Delegate(const Delegate& other)
{
this->invoker = other.invoker;
//this->uniqueIdentifier = other.uniqueIdentifier;
}
/**
*@brief Copy constructor with rvalue.
*/
Delegate(const Delegate&& other)
{
this->invoker = std::move(other.invoker);
//this->uniqueIdentifier = other.uniqueIdentifier;
}
/**
*@brief Create delegate from function pointer.
*@param ptr The function pointer. (&foo)
* Example code:
* @code
* void Call(const Delegate<void()>& del) { del();}
* void foo(){cout << "Hello World" << endl;}
*
* Delegate<void()> del(&foo);
* del(); // Prints "Hello World"
* Call(&foo); // Prints "Hello World"
* @endcode
*/
Delegate(RET(ptr)(PARAMS...))
{
invoker = ptr;
//uniqueIdentifier = (size_t)ptr;
}
/**
*@brief Create delegate from lambda.
* Example code:
* @code
* void Call(const Delegate<void()>& del) { del();}
* void foo(){cout << "Hello World" << endl;}
*
* Delegate<void()> del([](){ cout << "Hello World" << endl;});
* del(); // Prints "Hello World"
* Call([&del](){foo(); del();}); // Prints "Hello World" twice
* @endcode
*/
template <typename T>
Delegate(const T& lambda)
{
invoker = lambda;
// uniqueIdentifier = lambda.target_type().hash_code();
}
/**
*@brief Create delegate from class method.
*@param [in] instance The pointer to the class object. (Both this, and &myClass) works.
*@param [in] TMethod The class method pointer. (&Class::Method)
* Example code:
* @code
* void Call(const Delegate<void()>& del) { del();}
* class A
*{
* public:
* void foo(){cout << "Hello World" << endl;}
*}
*
* A a;
* Delegate<void()> del = {&a, &A::foo};
* del(); // Prints "Hello World"
* Call(del); // Prints "Hello World"
* Call({&a, &A::foo}); // Prints "Hello World"
* @endcode
*/
template <class T>
Delegate(T* instance, RET(T::*TMethod)(PARAMS...))
{
invoker = [instance, TMethod](PARAMS... params) -> RET {
T* p = static_cast<T*>(instance);
return (instance->*TMethod)(std::forward<PARAMS>(params)...);
};
//union test
//{
// size_t conv[2] = { 0, 0 };
// RET(T::*ptr)(PARAMS...);
//};
//test ptr;
//ptr.ptr = TMethod;
//if (ptr.conv[1])
// int i = 0;
//uniqueIdentifier = (size_t)(instance) | ptr.conv[0];
// std::intptr_t b = reinterpret_cast<std::intptr_t>(TMethod);
// uniqueIdentifier = (size_t)instance | (size_t)TMethod;
}
/**
*@brief Create delegate from const class method.
*@param [in] instance The pointer to the class object. (Both this, and &myClass) works.
*@param [in] TMethod The class method pointer. (&Class::Method)
* Example code:
* @code
* void Call(const Delegate<void()>& del) { del();}
* class A
*{
* public:
* void foo()const{cout << "Hello World" << endl;}
*}
*
* A a;
* Delegate<void()> del = {&a, &A::foo};
* del(); // Prints "Hello World"
* Call(del); // Prints "Hello World"
* Call({&a, &A::foo}); // Prints "Hello World"
* @endcode
*/
template <class T>
Delegate(const T* instance, RET(T::*TMethod)(PARAMS...) const)
{
invoker = [instance, TMethod](PARAMS... params) -> RET {
T* const p = const_cast<T*>(instance);
return (instance->*TMethod)(std::forward<PARAMS>(params)...);
};
}
/**
*@brief No equal operator for now.
*/
bool operator==(const Delegate& other)const = delete;
bool operator+=(const Delegate& other)const = delete;
bool operator-=(const Delegate& other)const = delete;
bool operator+(const Delegate& other)const = delete;
bool operator-(const Delegate& other)const = delete;
/**
*@brief Assignment from Delegate to Delegate.
*/
Delegate& operator=(const Delegate& other)
{
this->invoker = other.invoker;
return *this;
}
/**
*@brief Assignment from Delegate to Delegate, with rvalue.
*/
Delegate& operator=(const Delegate&& other)
{
this->invoker = std::move(other.invoker);
return *this;
}
/**
*@brief Invoke the delegate.
*/
inline RET operator()(PARAMS... args)const
{
return invoker(std::forward<PARAMS>(args)...);
}
};
}
}
#endif // SE_UTILZ_DELEGATE_H_ | true |
5ade1992446ac0d43f1d31461dfeab74e1464937 | C++ | FahimCC/Problem-Solving | /Hackerearth/Linear Search/Min-Max.cpp | UTF-8 | 445 | 2.765625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n;
long a[100000],sum = 0,max,min,ans;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
sum = sum + a[i];
}
max = 0;
min = 10000000000000;
for(int i=1;i<=n;i++)
{
ans = sum - a[i];
if(max < ans)
max = ans;
if(min > ans)
min = ans;
}
cout<<min<<" "<<max<<endl;
return 0;
}
| true |
a5b567091ad2da91c6cdad360064e26326657378 | C++ | tud-zih-energy/nitro | /tests/string_test.cpp | UTF-8 | 5,249 | 3.9375 | 4 | [
"BSD-3-Clause"
] | permissive | #include <nitro/lang/string.hpp>
#include <catch2/catch.hpp>
TEST_CASE("String join works", "[lang]")
{
std::vector<std::string> str;
str.emplace_back("Hello");
str.emplace_back("World");
SECTION("using the vector overload")
{
REQUIRE(nitro::lang::join(str) == "Hello World");
}
SECTION("using the iterator overload")
{
REQUIRE(nitro::lang::join(str.begin(), str.end()) == "Hello World");
}
SECTION("joining empty strings gives an empty string")
{
REQUIRE(nitro::lang::join({ std::string(), std::string() }) == std::string());
}
SECTION("joining an empty string at last doesn't give a string with a dangling space")
{
REQUIRE(nitro::lang::join({ "Hello", std::string() }) == std::string("Hello"));
}
SECTION("joining an empty vector gives an empty string")
{
REQUIRE(nitro::lang::join({}) == std::string());
}
SECTION("joining an empty range gives an empty string")
{
REQUIRE(nitro::lang::join(str.begin(), str.begin()) == std::string());
}
SECTION("joining with a different infix works")
{
REQUIRE(nitro::lang::join(str, " cruel ") == "Hello cruel World");
}
SECTION("joining with an empty infix works")
{
REQUIRE(nitro::lang::join(str, std::string()) == "HelloWorld");
}
SECTION("joining a non string vector works too")
{
std::vector<int> ints;
ints.emplace_back(1);
ints.emplace_back(2);
ints.emplace_back(3);
ints.emplace_back(4);
ints.emplace_back(5);
ints.emplace_back(6);
ints.emplace_back(7);
ints.emplace_back(8);
ints.emplace_back(9);
ints.emplace_back(10);
REQUIRE(nitro::lang::join(ints.begin(), ints.end()) == "1 2 3 4 5 6 7 8 9 10");
}
}
TEST_CASE("String split works", "[lang]")
{
std::string str = "1234##5678##9101112";
SECTION("splitting with char works")
{
auto split = nitro::lang::split(str, "#");
REQUIRE(split.size() == 5);
REQUIRE(split[0] == "1234");
REQUIRE(split[1] == "");
REQUIRE(split[2] == "5678");
REQUIRE(split[3] == "");
REQUIRE(split[4] == "9101112");
}
SECTION("splitting with string works")
{
auto split = nitro::lang::split(str, "##");
REQUIRE(split.size() == 3);
REQUIRE(split[0] == "1234");
REQUIRE(split[1] == "5678");
REQUIRE(split[2] == "9101112");
}
SECTION("splitting with string works if at the beginning")
{
auto split = nitro::lang::split(str, "1234");
REQUIRE(split.size() == 2);
REQUIRE(split[0] == "");
REQUIRE(split[1] == "##5678##9101112");
}
SECTION("splitting with string works if at the end")
{
auto split = nitro::lang::split(str, "112");
REQUIRE(split.size() == 2);
REQUIRE(split[0] == "1234##5678##9101");
REQUIRE(split[1] == "");
}
SECTION("splitting an empty string works")
{
auto split = nitro::lang::split({}, "112");
REQUIRE(split.size() == 1);
REQUIRE(split[0] == "");
}
SECTION("splitting with an empty string throws")
{
REQUIRE_THROWS(nitro::lang::split(str, {}));
}
SECTION("splitting without match works")
{
auto split = nitro::lang::split(str, "@@@");
REQUIRE(split.size() == 1);
REQUIRE(split[0] == "1234##5678##9101112");
}
}
TEST_CASE("String starts_with works", "[lang]")
{
SECTION("Egg and Spam starts with Egg")
{
REQUIRE(nitro::lang::starts_with("Egg and Spam", "Egg") == true);
}
SECTION("Egg and Spam doesn't sart with Spam")
{
REQUIRE(nitro::lang::starts_with("Egg and Spam", "Spam") == false);
}
SECTION("Egg doesn't start with Egg and Spam")
{
REQUIRE(nitro::lang::starts_with("Egg", "Egg and Spam") == false);
}
SECTION("All strings start with the empty string")
{
REQUIRE(nitro::lang::starts_with("Egg", "") == true);
}
SECTION("The empty string starts with the empty string")
{
REQUIRE(nitro::lang::starts_with("", "") == true);
}
SECTION("the empty string starts with no string")
{
REQUIRE(nitro::lang::starts_with("", "Egg") == false);
}
}
TEST_CASE("String replace_all works", "[lang]")
{
SECTION("Egg, Bacon and Bacon becomes Egg, Spam and Spam")
{
std::string str("Egg, Bacon and Bacon");
nitro::lang::replace_all(str, "Bacon", "Spam");
REQUIRE(str == "Egg, Spam and Spam");
}
SECTION("replace_all handles replaces that are longer than the original")
{
std::string str("Egg and Spam");
nitro::lang::replace_all(str, " and Spam", ", Sausage and Spam");
REQUIRE(str == "Egg, Sausage and Spam");
}
SECTION("Replacing with empty string")
{
std::string str("Egg, Spam, Spam, Spam");
nitro::lang::replace_all(str, ", Spam", "");
REQUIRE(str == "Egg");
}
SECTION("Replaces in an empty string")
{
std::string str("");
nitro::lang::replace_all(str, "Egg", "Spam");
REQUIRE(str == "");
}
}
| true |
fc94ee2d4b37e832ae1ddbcf2d257e3733253df5 | C++ | dksem12gh/winApi-MapTool | /winApi/enemy.cpp | UHC | 1,747 | 2.59375 | 3 | [] | no_license | #include "stdafx.h"
#include "enemy.h"
enemy::enemy() : _currentFrameX(0),
_currentFrameY(0),
_x(0.0f),
_y(0.0f),
_rc(RectMake(0, 0, 0, 0)),
_worldTimeCount(0.0f),
_rndTimeCount(0.0f)
{
}
HRESULT enemy::init(void)
{
return S_OK;
}
HRESULT enemy::init(const char * imageName, POINT position)
{
_worldTimeCount = TIMEMANAGER->getWorldTime();
_rndTimeCount = RND->getFromFloatTo(0.04f, 0.1f);
_bulletFireCount = TIMEMANAGER->getWorldTime();
_rndFireCount = RND->getFromFloatTo(0.5f, 4.5f);
_image = IMAGEMANAGER->findImage(imageName);
_rc = RectMakeCenter(position.x, position.y,
_image->getFrameWidth(), _image->getFrameHeight());
return S_OK;
}
void enemy::release(void)
{
}
void enemy::update(void)
{
move();
}
void enemy::render(void)
{
draw();
animation();
}
//ʹ̸ Ʋ ӹ ڽĿ
void enemy::move(void)
{
}
void enemy::draw(void)
{
_image->frameRender(getMemDC(), _rc.left, _rc.top,
_currentFrameX, _currentFrameY);
}
void enemy::animation(void)
{
//if (_rndTimeCount + _worldTimeCount <= GetTickCount())
//{
// _worldTimeCount = GetTickCount();
// _currentFrameX++;
// if (_image->getMaxFrameX() < _currentFrameX)
// {
// _currentFrameX = 0;
// }
//}
if (_rndTimeCount + _worldTimeCount <= TIMEMANAGER->getWorldTime())
{
_worldTimeCount = TIMEMANAGER->getWorldTime();
_currentFrameX++;
if (_image->getMaxFrameX() < _currentFrameX)
{
_currentFrameX = 0;
}
}
}
bool enemy::bulletCountFire(void)
{
if (_rndFireCount + _bulletFireCount <= TIMEMANAGER->getWorldTime())
{
_bulletFireCount = TIMEMANAGER->getWorldTime();
_rndFireCount = RND->getFromFloatTo(2.0f, 6.0f);
return true;
}
return false;
}
| true |
6c360d5a0518124ad0e81b141467fcebe1f82f87 | C++ | m0hitbansal/Competitive-Programming | /Strings/string reverse indivual word.cpp | UTF-8 | 560 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
void reverse(char *s,int begin,int end){
int i=begin;
while(i<=end){
char temp=s[end];
s[end]=s[i];
s[i]=temp;
i++;
end--;
}
}
int main(){
char str1[100]="32 0121 3421 543 abcd";
int i=0;
int num=0;
while(str1[i]!='\0'){
if(str1[i]!=' '){
num++;
}
else{
int end=i-1;
int begin=end-num+1;
reverse(str1,begin,end);
num=0;
}
i++;
}
if(str1[i]==0){
int end=i-1;
int begin=end-num+1;
reverse(str1,begin,end);
}
cout<<str1;
}
| true |
d5ec65f4ecc0839e02ddb242b74a6c9fe463133f | C++ | chihyang/CPP_Primer | /chap13/Exer13_22_HasPtr.h | UTF-8 | 1,265 | 3.59375 | 4 | [
"Apache-2.0"
] | permissive | #ifndef HASPTR_H
#define HASPTR_H
#include <iostream>
#include <string>
class HasPtr{
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { i = ps->size(); }
// here, we can use private members directly! Because this is a member
// function of class HasPtr. They can access any member of the class. Review
// member functions, access control and class scope for more details.
HasPtr(const HasPtr& hp) : ps(new std::string(*(hp.ps))), i(hp.i) { }
// . has higher precedence, so the parenthesize could be ignored here
// copy-assignment operator required by exercise 13.8
HasPtr& operator=(const HasPtr&);
// destructor required by exercise 13.11
~HasPtr() { delete ps; }
private:
std::string *ps;
int i;
};
HasPtr& HasPtr::operator=(const HasPtr& hp)
{
// WARNING: ensure self assignment gets the correct result!!!
// Remember to free resources before deleting!!!
// WRONG way to write an assignment operator!
ps = new std::string(*hp.ps);
i = hp.i;
return *this; // return this object
}
#endif
// value-like copy and assign required by exercise 13.22
// Note: both copy and copy-assign member allocate new memory, so they make the
// class behave like a value.
| true |
a1f9c27d1877ab376d190438dfc97194aafe1676 | C++ | harshg0910/Graphics | /Assignment 4/sol-opengl.cpp | UTF-8 | 4,321 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <GL/glut.h>
#include <iostream>
using namespace std;
#define VIEWING_DISTANCE_MIN 3.0
static GLfloat g_fViewDistance = 3 * VIEWING_DISTANCE_MIN;
static GLfloat g_nearPlane = 1;
static GLfloat g_farPlane = 1000;
static int g_Width = 600; // Initial window width
static int g_Height = 600; // Initial window height
GLfloat bottomCubeSize = 0.6f;
GLfloat bottomCubePos = 0.6f;
void DrawCubeFace(float fSize)
{
fSize /= 2.0;
glBegin(GL_QUADS);
glVertex3f(-fSize, -fSize, fSize);
glVertex3f(fSize, -fSize, fSize);
glVertex3f(fSize, fSize, fSize);
glVertex3f(-fSize, fSize, fSize);
glEnd();
}
void DrawCube (float fSize)
{
glPushMatrix();
DrawCubeFace (fSize);
glRotatef (90, 1, 0, 0);
DrawCubeFace (fSize);
glRotatef (90, 1, 0, 0);
DrawCubeFace (fSize);
glRotatef (90, 1, 0, 0);
DrawCubeFace (fSize);
glRotatef (90, 0, 1, 0);
DrawCubeFace (fSize);
glRotatef (180, 0, 1, 0);
DrawCubeFace (fSize);
glPopMatrix();
}
void DrawCubeBoundary(float fSize)
{
fSize /= 2.0;
glBegin(GL_LINE_LOOP);
glVertex3f(-fSize, -fSize, fSize);
glVertex3f(fSize, -fSize, fSize);
glVertex3f(fSize, fSize, fSize);
glVertex3f(-fSize, fSize, fSize);
glEnd();
}
void DrawBoundary (float fSize) {
glPushMatrix();
DrawCubeBoundary (fSize);
glRotatef (90, 1, 0, 0);
DrawCubeBoundary (fSize);
glRotatef (90, 1, 0, 0);
DrawCubeBoundary (fSize);
glRotatef (90, 1, 0, 0);
DrawCubeBoundary (fSize);
glRotatef (90, 0, 1, 0);
DrawCubeBoundary (fSize);
glRotatef (180, 0, 1, 0);
DrawCubeBoundary (fSize);
glPopMatrix();
}
void RenderObjects(void)
{
float colorBlue[4] = { 0.0, 0.2, 1.0, 1.0 };
float colorRed[4] = { 1.0, 0.0, 0.0, 1.0 };
float colorGreen[4] = { 0.0, 1.0, 0.0, 1.0 };
float colorNone[4] = { 0.0, 0.0, 0.0, 0.0 };
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
//glTranslatef(-3, -2, 0);
//glRotatef(15, 1, 0, 0);
//glRotatef(60, 0, 1, 0);
glColor4fv(colorBlue);
DrawBoundary(1.0);
glTranslatef(0, bottomCubePos, 0);
glColor4fv(colorGreen);
DrawCube(bottomCubeSize);
glTranslatef(0, bottomCubeSize, 0);
glColor4fv(colorBlue);
DrawCube(bottomCubeSize);
glTranslatef(0, bottomCubeSize, 0);
glColor4fv(colorRed);
DrawCube(bottomCubeSize);
glPopMatrix();
}
void display(void)
{
// Clear frame buffer and depth buffer
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor (1,1,1,0);
glClear(GL_COLOR_BUFFER_BIT);
// Set up viewing transformation, looking down -Z axis
//glLoadIdentity();
//gluLookAt(0, 0, -g_fViewDistance, 0, 0, -1, 0, 1, 0);
// Render the scene
RenderObjects();
// Make sure changes appear onscreen
glutSwapBuffers();
}
GLdouble ex=0.0f, ey=0.0f, ez=g_fViewDistance;
GLdouble cx=0.5f, cy=0.5f, cz=0.5f;
GLdouble ux=0.0f, uy=1.0f, uz=0.0f;
void reshape(GLint width, GLint height)
{
// cout << "RESHAPE called" << endl;
g_Width = width;
g_Height = height;
glViewport(0, 0, g_Width, g_Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// gluPerspective(60.0, (float)g_Width / g_Height, g_nearPlane, g_farPlane);
// gluOrtho2D (-1,2,-1,2);
const int L = 3;
if (width<=height)
gluOrtho2D (-L, L, -L*height/width, L* height/width);
else
gluOrtho2D (-L*width/height, L*width/height, -L, L);
glMatrixMode(GL_MODELVIEW);
//glLoadIdentity( );
//gluLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz);
}
void keyboardFunc( unsigned char key, int x, int y )
{
switch( key )
{
case '1':
bottomCubePos += 0.2;
break;
case '2':
bottomCubePos -= 0.2;
break;
}
// do a reshape since g_eye_y might have changed
//reshape(g_Width, g_Height);
glutPostRedisplay( );
}
int main(int argc, char** argv)
{
// GLUT Window Initialization:
glutInit (&argc, argv);
glutInitWindowSize (g_Width, g_Height);
//glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitDisplayMode (GLUT_RGB | GLUT_SINGLE);
glutCreateWindow ("OpenGL Clipping, HSR, & Scan Conversion");
// Register callbacks:
glutDisplayFunc (display);
glutReshapeFunc (reshape);
glutKeyboardFunc(keyboardFunc);
// Turn the flow of control over to GLUT
glutMainLoop ();
return 0;
}
| true |
e35d25bf162d8452fc84c7dc70335997f0ad49c1 | C++ | xiaoqixian/Wonderland | /code/kruskal.cpp | UTF-8 | 3,262 | 3.421875 | 3 | [] | no_license | /**********************************************
> File Name : kruskal.cpp
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Fri 07 Aug 2020 06:42:20 PM CST
**********************************************/
#include <iostream>
using namespace std;
/*
* Kruskal算法原理:
* 我们假设一个图有m个节点,n条边。
* 首先,我们需要把m个节点看成m个独立的生成树,并且把n条边按照从小到大的数据进行排列。
* 在n条边中,我们依次取出其中的每一条边,如果发现边的两个节点分别位于两棵树上,那么把两棵树合并成为一颗树;
* 如果树的两个节点位于同一棵树上,那么忽略这条边,继续运行。
* 等到所有的边都遍历结束之后,如果所有的生成树可以合并成一条生成树,那么它就是我们需要寻找的最小生成树,反之则没有最小生成树。
*
* 其实这个思想和幷查集有点像
*/
#include <vector>
#include <algorithm>
class Kruskal {
private:
vector<vector<int>> graph;
public:
Kruskal(vector<vector<int>> graph) {
this->graph = graph;
}
static bool comp(vector<int> a, vector<int> b) {
return a[2] < b[2];
}
//找到节点a在幷查集中的根节点
int findRoot(vector<int>& sets, int a) {
while (sets[a] != a) {
a = sets[a];
}
return a;
}
//现在需要考虑的一个是如何将所有的边排序,以及排序后如何表示
//现在用二维vector表示排序后的边
vector<vector<int>> kruskal() {
vector<bool> viewed(graph.size(), false);
vector<vector<int>> edges;
vector<int> sets(graph.size()); //幷查集
vector<vector<int>> res(graph.size());
for (int i = 0; i < graph.size(); i++) {
for (int j = 0; j < graph[i].size(); j++) {
if (graph[i][j] != 0) {
if (!viewed[i] || !viewed[j]) {
vector<int> edge(3);
edge[0] = i;
edge[1] = j;
edge[2] = graph[i][j];
edges.push_back(edge);
}
}
}
sets[i] = i;
}
sort(edges.begin(), edges.end(), comp);
for (int i = 0; i < edges.size(); i++) {
vector<int> edge = edges[i];
int root1 = findRoot(sets, edge[0]), root2 = findRoot(sets, edge[1]);
if (root1 != root2) {
//合并两个根节点
sets[root2] = root1;
res[edge[0]].push_back(edge[1]);
res[edge[1]].push_back(edge[0]);
}
}
return res;
}
};
int main() {
vector<vector<int>> graph = {
{0,7,0,5,0,0,0},
{7,0,8,9,7,0,0},
{0,8,0,0,5,0,0},
{5,9,0,0,15,6,0},
{0,7,5,15,0,8,9},
{0,0,0,6,8,0,11},
{0,0,0,0,9,11,0}
};
Kruskal k(graph);
vector<vector<int>> res = k.kruskal();
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
cout << (char)(i+'A') << " -> " << (char)(res[i][j]+'A') << endl;
}
}
return 0;
}
| true |
ce66496171988ac30fc16565bdfccfe0afdc1abf | C++ | fszhaoholo/SmartScript | /test/map_clear.cpp | UTF-8 | 340 | 2.53125 | 3 | [] | no_license | #include "stdio.h"
#include <map>
using namespace std;
int main()
{
map<int, int> map_clear;
int i = 0;
int j = 0;
while(1)
{
map_clear.insert(pair<int, int>(i,i));
i++;
if (i == 10737400)
{
// map_clear.clear();
map<int, int>().swap(map_clear);
printf("+++++++++%d+++++\n", j);
i = 0;
j++;
}
}
return 0;
}
| true |
a7045a39e52218a3d5e7e6d0dc5bd89b0e759814 | C++ | PowerTravel/handmade | /code/intrinsics.h | UTF-8 | 2,517 | 2.75 | 3 | [] | no_license | #pragma once
// TODO: Replace math.h with cpu specific instructions
#include <cmath>
#include "types.h"
inline u32 GetThreadID()
{
// Read the pointer to thread local storage.
u8* ThreadLocalStorage = (u8*) __readgsqword(0x30);
u32 ThreadID = *(u32*) (ThreadLocalStorage + 0x48);
return ThreadID;
}
inline b32
IsNan(float Value)
{
bool Result = std::isnan(Value);
return Result;
}
inline u32
SafeTruncateToU32( u64 Value )
{
Assert(Value <= UINT32_MAX);
u32 Result = (u32) Value;
return(Result);
}
inline r64
Round( r64 Real64 )
{
r64 Result = round( Real64 );
return Result;
}
inline r32
Round( r32 Real32 )
{
// NOTE(Jakob): ROUNDF IS SLOW!!
// return floor(d + 0.5);
r32 Result = roundf( Real32 );
return Result;
}
inline r32
Ciel( r32 Real32 )
{
// i= 32768 - (int)(32768. - fp);
r32 Result = ceilf( Real32 );
return Result;
}
inline r32
Floor( r32 Real32 )
{
// i= (int)(fp + 32768.) - 32768;
r32 Result = floorf( Real32 );
return Result;
}
inline r32
Sin( r32 Angle )
{
r32 Result = sinf( Angle );
return Result;
}
inline r32
ASin( r32 Angle )
{
r32 Result = asinf( Angle );
return Result;
}
inline r32
Cos( r32 Angle )
{
r32 Result = cosf( Angle );
return Result;
}
inline r32
ACos( r32 Angle )
{
r32 Result = acosf( Angle );
return Result;
}
inline r32
ATan2( r32 Y, r32 X )
{
r32 Result = atan2f( Y, X );
return Result;
}
inline r32
Tan( r32 Angle )
{
r32 Result = tanf( Angle );
return Result;
}
inline r32
Sqrt( r32 A )
{
r32 Result = sqrtf( A );
return Result;
}
inline r32
Abs( r32 A )
{
r32 Result = (r32) fabs( A );
return Result;
}
inline r32
Pow( r32 Base, r32 Exponent )
{
r32 Result = (r32) powf( Base, Exponent );
return Result;
}
struct bit_scan_result
{
b32 Found;
u32 Index;
};
inline bit_scan_result
FindLeastSignificantSetBit( u32 Value )
{
bit_scan_result Result = {};
#if COMPILER_MSVC
Result.Found = _BitScanForward( (unsigned long*) &Result.Index, Value);
#else
for(u32 Test = 0; Test < 32; Test++)
{
u32 mask = (1 << Test);
if( (Value & mask ) != 0)
{
Result.Index = Test;
Result.Found = true;
break;
}
}
#endif
return Result;
}
inline u32 GetSetBitCount(u32 Value)
{
bit_scan_result BitScan = FindLeastSignificantSetBit(Value);
u32 Result = 0;
while(BitScan.Found)
{
++Result;
u32 LeastSetBit = 1 << BitScan.Index;
Value -= LeastSetBit;
BitScan = FindLeastSignificantSetBit(Value);
}
return Result;
}
| true |
d0ee194fa86334c3ed7f9ec188c7ad44ecb68f78 | C++ | billsioros/genetic-cpp17 | /include/genetic.ipp | UTF-8 | 2,043 | 3.15625 | 3 | [
"MIT"
] | permissive |
#pragma once
#include <cstdlib>
#include <type_traits>
template <typename T, typename Arithmetic>
Genetic<T, Arithmetic>::Genetic
(
std::function<T(const T&, const T&)>&& crossover,
std::function<void(T&)>&& mutate,
std::function<Arithmetic(const T&)>&& fitness
)
:
crossover(crossover),
mutate(mutate),
fitness(fitness)
{
static_assert
(
std::is_floating_point<Arithmetic>::value,
"Non floating point type given as the second template parameter"
);
}
template <typename T, typename Arithmetic>
T Genetic<T, Arithmetic>::operator()
(
std::vector<T> ancestors,
std::function<bool(const T&)>&& condition, std::size_t maxIterations,
Arithmetic mutationRate
) const
{
auto& best = ancestors.front(); Arithmetic max = fitness(best);
for (auto current = ++ancestors.begin(); current != ancestors.end(); ++current)
{
const Arithmetic value = fitness(*current);
if (value > max)
{
max = value; best = *current;
}
}
for (std::size_t it = 0UL; it < maxIterations && !condition(best); it++)
{
std::sort
(
ancestors.begin(), ancestors.end(),
[this](const auto& A, const auto& B)
{
return fitness(A) > fitness(B);
}
);
std::vector<T> successors;
for (std::size_t total = 0UL; total < ancestors.size(); total++)
{
const auto& ancestor1 = ancestors[std::rand() % ancestors.size() / 2];
const auto& ancestor2 = ancestors[std::rand() % ancestors.size() / 2];
auto child = crossover(ancestor1, ancestor2);
if (static_cast<Arithmetic>(std::rand()) / RAND_MAX < mutationRate)
mutate(child);
successors.push_back(child);
const Arithmetic value = fitness(child);
if (value > max)
{
max = value; best = child;
}
}
ancestors = successors;
}
return best;
}
| true |
fb4c7787d213da3d9ae5bf23c4f6ee721a4ec59b | C++ | theShroo/HexCraft | /Assignment 2 FPS/Assignment 2 FPS/Shader.cpp | UTF-8 | 9,595 | 2.5625 | 3 | [] | no_license | #include "Shader.h"
// static lite shader manager.
std::unordered_map<std::string, Shader*> Shader::m_shaders;
bool Shader::LoadShader(std::string ID, LPWSTR vertexShaderPath, LPWSTR pixelShaderPath, DirectX::XMFLOAT3 colour, ID3D11Device* Renderer) {
if (m_shaders.count(ID) > 0) {
delete m_shaders[ID];
m_shaders[ID] = 0;
}
m_shaders[ID] = new Shader();
return m_shaders[ID]->Initialise(Renderer, vertexShaderPath, pixelShaderPath, 0, colour);
}
bool Shader::LoadShader(std::string ID, LPWSTR vertexShaderPath, LPWSTR pixelShaderPath, ID3D11Device* Renderer) {
if (m_shaders.count(ID) > 0) {
delete m_shaders[ID];
m_shaders[ID] = 0;
}
m_shaders[ID] = new Shader();
return m_shaders[ID]->Initialise(Renderer, vertexShaderPath, pixelShaderPath, 1, DirectX::XMFLOAT3(1, 1, 1));
}
Shader* Shader::GetShader(std::string ID) {
if (m_shaders.count(ID) > 0) {
return m_shaders[ID];
}
else {
RaiseException(1, 0, 0, 0);
return NULL;
}
}
void Shader::Release()
{
std::unordered_map<std::string, Shader*>::iterator terminator;
for (terminator = m_shaders.begin(); terminator != m_shaders.end(); terminator++) {
if (terminator->second) {
delete terminator->second;
terminator->second = 0;
}
}
}
Shader::Shader()
{
m_vertexShader = 0;
m_pixelShader = 0;
m_layout = 0;
m_matrixBuffer = 0;
m_textureSampler = 0;
}
Shader::~Shader()
{
if (m_matrixBuffer) {
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
if (m_layout) {
m_layout->Release();
m_layout = 0;
}
if (m_pixelShader) {
m_pixelShader->Release();
m_pixelShader = 0;
}
if (m_vertexShader) {
m_vertexShader->Release();
m_vertexShader = 0;
}
if (m_textureSampler) {
m_textureSampler->Release();
m_textureSampler = 0;
}
}
bool Shader::Initialise(ID3D11Device* device, LPCWSTR vertexFilename, LPCWSTR pixelFilename, bool isTextured, DirectX::XMFLOAT3 colour)
{
ID3DBlob* vertexShaderBlob = 0;
ID3DBlob* pixelShaderBlob = 0;
ID3DBlob* errorBlob = 0;
const unsigned int numberOfVertexElements = 4;
D3D11_INPUT_ELEMENT_DESC vertexLayout[numberOfVertexElements];
D3D11_BUFFER_DESC matrixBufferDescription;
if (FAILED(D3DCompileFromFile(vertexFilename,
NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE,
"main",
"vs_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0,
&vertexShaderBlob, &errorBlob)))
{
if (errorBlob)
{
OutputShaderErrorMessage(errorBlob, vertexFilename);
errorBlob->Release();
}
if (vertexShaderBlob)
vertexShaderBlob->Release();
return false;
}
HRESULT result = D3DCompileFromFile(pixelFilename,
NULL,
D3D_COMPILE_STANDARD_FILE_INCLUDE,
"main",
"ps_4_0",
D3DCOMPILE_ENABLE_STRICTNESS, 0,
&pixelShaderBlob, &errorBlob);
if (FAILED(result))
{
if (errorBlob)
{
OutputShaderErrorMessage(errorBlob, pixelFilename);
errorBlob->Release();
}
if (vertexShaderBlob)
vertexShaderBlob->Release();
return false;
}
if (FAILED(device->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), NULL, &m_vertexShader)))
{
if (errorBlob)
errorBlob->Release();
if (vertexShaderBlob)
vertexShaderBlob->Release();
if (pixelShaderBlob)
pixelShaderBlob->Release();
}
if (FAILED(device->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), NULL, &m_pixelShader)))
{
if (errorBlob)
errorBlob->Release();
if (vertexShaderBlob)
vertexShaderBlob->Release();
if (pixelShaderBlob)
pixelShaderBlob->Release();
}
vertexLayout[0].SemanticName = "POSITION";
vertexLayout[0].SemanticIndex = 0;
vertexLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
vertexLayout[0].InputSlot = 0;
vertexLayout[0].AlignedByteOffset = 0;
vertexLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
vertexLayout[0].InstanceDataStepRate = 0;
vertexLayout[1].SemanticName = "COLOR";
vertexLayout[1].SemanticIndex = 0;
vertexLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
vertexLayout[1].InputSlot = 0;
vertexLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
vertexLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
vertexLayout[1].InstanceDataStepRate = 0;
vertexLayout[2].SemanticName = "NORMAL"; //The next element is the normal
vertexLayout[2].SemanticIndex = 0;
vertexLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; //A normal is 3 32-bit floats
vertexLayout[2].InputSlot = 0;
vertexLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
vertexLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
vertexLayout[2].InstanceDataStepRate = 0;
vertexLayout[3].SemanticName = "TEXCOORD"; //The final element is the texture coordinate
vertexLayout[3].SemanticIndex = 0;
vertexLayout[3].Format = DXGI_FORMAT_R32G32_FLOAT; //A texture coord is 2 32-bit floats
vertexLayout[3].InputSlot = 0;
vertexLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
vertexLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
vertexLayout[3].InstanceDataStepRate = 0;
if (FAILED(device->CreateInputLayout(vertexLayout, numberOfVertexElements, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &m_layout)))
{
if (errorBlob)
errorBlob->Release();
if (vertexShaderBlob)
vertexShaderBlob->Release();
if (pixelShaderBlob)
pixelShaderBlob->Release();
}
vertexShaderBlob->Release();
vertexShaderBlob = 0;
pixelShaderBlob->Release();
pixelShaderBlob = 0;
matrixBufferDescription.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDescription.ByteWidth = sizeof(MatrixBuffer);
matrixBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDescription.MiscFlags = 0;
matrixBufferDescription.StructureByteStride = 0;
if (FAILED(device->CreateBuffer(&matrixBufferDescription, NULL, &m_matrixBuffer)))
{
return false;
}
if (isTextured) {
return LoadSampler(device);
}
return true;
}
void Shader::Begin(ID3D11DeviceContext* context)
{
context->IASetInputLayout(m_layout);
context->VSSetShader(m_vertexShader, NULL, 0);
context->VSSetConstantBuffers(0, 1, &m_matrixBuffer);
context->PSSetShader(m_pixelShader, NULL, 0);
if (m_textureSampler) {
context->PSSetSamplers(0, 1, &m_textureSampler);
}
}
bool Shader::SetMatrices(ID3D11DeviceContext* context, DirectX::XMMATRIX worldMatrix, DirectX::XMMATRIX viewMatrix, DirectX::XMMATRIX projectionMatrix)
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBuffer* inputData;
unsigned int bufferNumber;
if (FAILED(context->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
{
return false;
}
inputData = (MatrixBuffer*)mappedResource.pData;
worldMatrix = XMMatrixTranspose(worldMatrix);
viewMatrix = XMMatrixTranspose(viewMatrix);
projectionMatrix = XMMatrixTranspose(projectionMatrix);
inputData->world = worldMatrix;
inputData->view = viewMatrix;
inputData->projection = projectionMatrix;
context->Unmap(m_matrixBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 0;
// Finanly set the constant buffer in the vertex shader with the updated values.
context->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
return true;
}
bool Shader::SetTexture(ID3D11DeviceContext* context, ID3D11ShaderResourceView* textureResource)
{
if (m_textureSampler) {
context->PSSetShaderResources(0, 1, &textureResource);
return true;
}
return false;
}
void Shader::OutputShaderErrorMessage(ID3D10Blob* errorMessage, LPCWCHAR shaderFilename)
{
char* compileErrors;
unsigned long long bufferSize, i;
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Write out the error message.
for (i = 0; i<bufferSize; i++)
{
std::cout << compileErrors[i] << std::endl;
}
// Release the error message.
errorMessage->Release();
errorMessage = 0;
// Pop a message up on the screen to notify the user to check the text file for compile errors.
std::cout << "Error compiling shader. \n";
}
bool Shader::LoadSampler(ID3D11Device* device) {
D3D11_SAMPLER_DESC textureSamplerDescription; //When we create a sampler we need a Description struct to describe how we want to create the sampler
textureSamplerDescription.Filter = D3D11_FILTER_ANISOTROPIC; //This is the Filtering method used for the texture...
//...different values will give you different quality texture output
textureSamplerDescription.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; //This defines what happens when we sample outside of the range [0...1]
textureSamplerDescription.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; //In our case we just want it to wrap around so that we always are sampling something
textureSamplerDescription.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
textureSamplerDescription.MipLODBias = 0.0f; //The rest of these values are really just "Defaults"
textureSamplerDescription.MaxAnisotropy = 8; //If you want more info look up D3D11_SAMPLER_DESC on MSDN
textureSamplerDescription.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
textureSamplerDescription.BorderColor[0] = 1;
textureSamplerDescription.BorderColor[1] = 1;
textureSamplerDescription.BorderColor[2] = 1;
textureSamplerDescription.BorderColor[3] = 1;
textureSamplerDescription.MinLOD = 0;
textureSamplerDescription.MaxLOD = D3D11_FLOAT32_MAX;
//and create the sampler!
if (FAILED(device->CreateSamplerState(&textureSamplerDescription, &m_textureSampler)))
{
return false;
}
return true;
}
| true |
3e5d66a1787a91901b75f3d353d66a8b819829fb | C++ | aenoskov/RankLib | /indri/tags/release-1.0/src/NotNode.cpp | UTF-8 | 1,536 | 2.65625 | 3 | [
"BSD-2-Clause"
] | permissive |
//
// NotNode
//
// 26 August 2004 -- tds
//
#include "indri/NotNode.hpp"
#include "indri/Annotator.hpp"
#include <cmath>
NotNode::NotNode( const std::string& name, BeliefNode* child )
:
_name(name),
_child(child)
{
}
// for convenience, the not node never actually matches
int NotNode::nextCandidateDocument() {
return MAX_INT32;
}
double NotNode::maximumBackgroundScore() {
// we just want an upper bound on the background score
// this is a poor upper bound, but it should be accurate
return log( 1.0 - exp( _child->maximumBackgroundScore() ) );
}
double NotNode::maximumScore() {
// without a true minimum score available, we don't have a
// better estimate for the max than probability = 1.0;
// and log(1) = 0.
return 0.0;
}
const greedy_vector<ScoredExtentResult>& NotNode::score( int documentID, int begin, int end, int documentLength ) {
_extents.clear();
const greedy_vector<ScoredExtentResult>& child = _child->score( documentID, begin, end, documentLength );
for( unsigned int i=0; i<child.size(); i++ ) {
_extents.push_back( ScoredExtentResult( log( 1.0 - exp(child[i].score) ), documentID, begin, end ) );
}
return _extents;
}
bool NotNode::hasMatch( int documentID ) {
return !_child->hasMatch( documentID );
}
void NotNode::annotate( Annotator& annotator, int documentID, int begin, int end ) {
annotator.add( this, documentID, begin, end );
_child->annotate( annotator, documentID, begin, end );
}
const std::string& NotNode::getName() const {
return _name;
}
| true |
ac934db597792940fad742f9652997bd6ddee51c | C++ | EvolvingMonkee/Team11_ProjectOne_01 | /main.cpp | UTF-8 | 304 | 2.8125 | 3 | [] | no_license | #include "infixEvaluator.h"
#include <iostream>
using namespace std;
int main()
{
string s("(-4 + -5) +++25");
string t("(4 >= -5) + 25");
string u("4 <= -5 + 25");
InfixEvaluator i;
cout << i.eval(s) << endl;
cout << i.eval(t) << endl;
cout << i.eval(u) << endl;
char wait = getchar();
}
| true |
bb61406f39b5c821beaff29d5a90ccc0b7192373 | C++ | ArtemKravchenko/Collision-Detection-Framework | /GeometricFramework/CollisionDetectionAlgorithms/CDParticlesCollisionDetection2DLogic.cpp | UTF-8 | 11,275 | 2.546875 | 3 | [] | no_license | #include "CDParticlesCollisionDetection2DLogic.h"
#include <cmath>
//--------------------------------------------------------------------
// Constructor and destructors
//--------------------------------------------------------------------
CDParticlesCollisionDetection2DLogic::CDParticlesCollisionDetection2DLogic(CDParticlesList *particles, int width, int height, int countOfRows, int countOfCols)
{
_countOfRows = countOfRows;
_countOfColumns = countOfCols;
_actualCountOfSubsystems = countOfRows * countOfCols; _countOfRows = countOfRows;
_width = width;
_height = height;
_subsystemWidth = width / countOfCols;
_subsystemHeight = height / countOfRows;
_eps = 0.000001;
_subsystems = new CDSubsystemsList(_actualCountOfSubsystems);
_neighborhoodOwned = new CDNeighborhoodMap();
_neighborhoodOwning = new CDNeighborhoodMap();
this->InitSubsystems(particles);
_eventsList = new CDEventsList();
this->InitListOfEvents();
_heap = new DSHeap<CDEvent*>(_eventsList, &CDEvent::compareFunction);
}
CDParticlesCollisionDetection2DLogic::~CDParticlesCollisionDetection2DLogic(void)
{
_subsystems->clear();
delete _subsystems;
_subsystems = 0;
_neighborhoodOwned->clear();
delete _neighborhoodOwned;
_neighborhoodOwned = 0;
_neighborhoodOwning->clear();
delete _neighborhoodOwning;
_neighborhoodOwning = 0;
_eventsList->clear();
delete _eventsList;
_eventsList = 0;
delete _heap;
_heap = 0;
}
//--------------------------------------------------------------------
// Private functions
//--------------------------------------------------------------------
void CDParticlesCollisionDetection2DLogic::InitSubsystems(CDParticlesList *particles)
{
int multiindexOfSystem;
unsigned long countOfParticles = particles->size();
// Init subsystems
for(int i = 0; i < countOfParticles; i++)
{
CDParticle2D *particle = particles->at(i);
multiindexOfSystem = 0; // TODO: Unexpected remove CDUtils::GetMultiIndexOfSubsystem(static_cast<int>(particle->Position->X), static_cast<int>(particle->Position->Y), _subsystemWidth, _subsystemHeight, _countOfColumns);
CDParticlesSystem *particleSystem = this->_subsystems->at(multiindexOfSystem);
if(particleSystem == NULL)
{
particleSystem = new CDParticlesSystem();
}
particleSystem->AddParticle(particle);
}
for(int i = 0; i < _actualCountOfSubsystems; i++)
{
CDParticlesSystem *particlesSystem = this->_subsystems->at(i);
if(particlesSystem == NULL)
{
particlesSystem = new CDParticlesSystem();
// Init system bounds
particlesSystem->Bounds = new CDBounds();
particlesSystem->Bounds->BottomLeftPoint = new CDVector2D(static_cast<float>(_subsystemWidth * i), static_cast<float>(_subsystemHeight * i));
particlesSystem->Bounds->TopLeftPoint = new CDVector2D(static_cast<float>(_subsystemWidth * i), static_cast<float>(_subsystemHeight * i + _subsystemHeight));
particlesSystem->Bounds->TopRightPoint = new CDVector2D(static_cast<float>(_subsystemWidth * i + _subsystemWidth), static_cast<float>(_subsystemHeight * i + _subsystemHeight));
particlesSystem->Bounds->BottomRightPoint = new CDVector2D(static_cast<float>(_subsystemWidth * i + _subsystemWidth), static_cast<float>(_subsystemHeight * i));
}
// Init owned neighborhood
this->InitNeighbors(true, i);
// Init owning neighbors
this->InitNeighbors(false, i);
}
}
void CDParticlesCollisionDetection2DLogic::InitNeighbors(bool isOwnedNeighbors, int subsystemIndex)
{
int firstNeighbor, secondNeighbor, thirdNeighbor, fourthNeighbor;
bool condition;
std::vector<int> currentNeighborhood;//= new std::vector<int>();
for(int j = 0; j < _countOfNeighborhood; j++)
{
// Init number of first neighbor
firstNeighbor = (subsystemIndex + (isOwnedNeighbors)) ? - (_countOfColumns - 1) : (_countOfColumns - 1);
condition = (isOwnedNeighbors) ? (firstNeighbor > 0 && firstNeighbor % _countOfColumns != 0) : (firstNeighbor < _actualCountOfSubsystems && (firstNeighbor + 1) % _countOfColumns != 0);
if(condition) // if number of first neighbor isn't higer than upper bound and not more right than right bound
currentNeighborhood.push_back(firstNeighbor);
// Init number of second neighbor
secondNeighbor = (subsystemIndex + (isOwnedNeighbors)) ? 1 : - 1;
condition = (isOwnedNeighbors) ? (secondNeighbor % _countOfColumns != 0) : ((firstNeighbor + 1) % _countOfColumns != 0);
if(condition) // if number of second neighbor isn't more right than right bound
currentNeighborhood.push_back(secondNeighbor);
// Init number of third neighbor
thirdNeighbor = (subsystemIndex + (isOwnedNeighbors)) ? _countOfColumns : - _countOfColumns;
condition = (isOwnedNeighbors) ? (thirdNeighbor < _actualCountOfSubsystems) : (thirdNeighbor > 0);
if(condition)
{
currentNeighborhood.push_back(thirdNeighbor);
// Init fourth neighbor
fourthNeighbor = (isOwnedNeighbors) ? thirdNeighbor + 1 : thirdNeighbor - 1;
condition = (isOwnedNeighbors) ? (fourthNeighbor % _countOfColumns != 0) : ((fourthNeighbor + 1) % _countOfColumns != 0);
if(condition)
currentNeighborhood.push_back(fourthNeighbor);
}
CDNeighborhoodPair p = CDNeighborhoodPair(subsystemIndex, currentNeighborhood);
if(isOwnedNeighbors)
_neighborhoodOwned->insert(p);
else
_neighborhoodOwning->insert(p);
}
}
void CDParticlesCollisionDetection2DLogic::InitListOfEvents()
{
unsigned long subsystemListSize = this->_subsystems->size();
unsigned long particlesListSize = -1;
std::vector<int> *currentNeighborhood;
int subsystemIndex;
CDParticlesSystem *tmpSystem;
CDParticlesSystem *tmpNeighborSystem;
CDParticle2D *tmpParticle;
// 1.) Loop through all subsystmes and determine minimal time of collision
for(unsigned int i = 0; i < subsystemListSize; i++)
{
tmpSystem = this->_subsystems->at(i);
// Loop through all particles in subsystem
particlesListSize = tmpSystem->Particles->size();
// 1.1) For each particle in current subsytem determine time :
for(unsigned int j = 0; j < particlesListSize; j++)
{
tmpParticle = tmpSystem->Particles->at(j);
// - of collision with each particles in current subsystem
this->DetectCollisionBetweenParticleAndParticlesInSystem(tmpParticle, tmpSystem, true);
// - of collision with each particles in neighbors subsystems (only owned neighbors)
currentNeighborhood = &_neighborhoodOwned->find(i)->second;
for (unsigned int j2 = 0; j2 < currentNeighborhood->size(); j2++)
{
subsystemIndex = currentNeighborhood->at(i);
tmpNeighborSystem = _subsystems->at(subsystemIndex);
this->DetectCollisionBetweenParticleAndParticlesInSystem(tmpParticle, tmpNeighborSystem, true);
}
// - when particle left current subsystem
this->DetectWhenParticleLeftSubsystem(tmpParticle, tmpSystem);
// of collision with boundaries of space (need to determine only when our subsystem is boundary)
this->DetectCollisionBetwennParticleAndBoundsOfSystem(tmpParticle, tmpSystem, true);
}
}
}
float CDParticlesCollisionDetection2DLogic::DetectCollisionBetweenTwoParticles(CDParticle2D *p1, CDParticle2D *p2)
{
return 0; // TODO: need to implement
}
float CDParticlesCollisionDetection2DLogic::DetectCollisionBetweenParticleAndBound(CDParticle2D *p, int boundOrigin, bool isVerticalBound)
{
return 0; // TODO: need to implement
}
float CDParticlesCollisionDetection2DLogic::DetectWhenParticleLeftSubsystem(CDParticle2D *p, CDParticlesSystem *subsystem)
{
return 0;
}
void inline CDParticlesCollisionDetection2DLogic::DetectCollisionBetweenParticleAndParticlesInSystem(CDParticle2D* particle, CDParticlesSystem *system, bool needToAdd)
{
unsigned long particlesListSize = system->Particles->size();
CDParticle2D *tmpSecondParticle;
float tmpTime;
for(unsigned int i = 0; i < particlesListSize; i++)
{
tmpSecondParticle = system->Particles->at(i);
if (particle != tmpSecondParticle)
{
tmpTime = this->DetectCollisionBetweenTwoParticles(particle, tmpSecondParticle);
if (needToAdd)
{
CDEvent *event = new CDEvent(CollisionBetweenTwoParticles, tmpTime, particle, tmpSecondParticle, -1, -1);
_eventsList->push_back(event);
}
}
}
}
void inline CDParticlesCollisionDetection2DLogic::DetectCollisionBetwennParticleAndBoundsOfSystem(CDParticle2D *particle, CDParticlesSystem *system, bool needToAdd)
{
float tmpTime;
if (system->Bounds->BottomLeftPoint->X == 0)
{
tmpTime = this->DetectCollisionBetweenParticleAndBound(particle, system->Bounds->BottomLeftPoint->X, false);
if (needToAdd)
{
CDEvent *event = new CDEvent(ParticleGointToLeaveSystem, tmpTime, particle, NULL, system->Bounds->BottomLeftPoint->X, -1);
_eventsList->push_back(event);
}
}
if (system->Bounds->BottomLeftPoint->Y == 0)
{
tmpTime = this->DetectCollisionBetweenParticleAndBound(particle, system->Bounds->BottomLeftPoint->Y, true);
if (needToAdd)
{
CDEvent *event = new CDEvent(ParticleGointToLeaveSystem, tmpTime, particle, NULL, -1, system->Bounds->BottomLeftPoint->Y);
_eventsList->push_back(event);
}
}
if (system->Bounds->TopRightPoint->X == _width)
{
tmpTime = this->DetectCollisionBetweenParticleAndBound(particle, system->Bounds->TopRightPoint->X, false);
if (needToAdd)
{
CDEvent *event = new CDEvent(ParticleGointToLeaveSystem, tmpTime, particle, NULL, system->Bounds->TopRightPoint->X, -1);
_eventsList->push_back(event);
}
}
if (system->Bounds->TopRightPoint->Y == _height)
{
tmpTime = this->DetectCollisionBetweenParticleAndBound(particle, system->Bounds->TopRightPoint->Y, true);
if (needToAdd)
{
CDEvent *event = new CDEvent(ParticleGointToLeaveSystem, tmpTime, particle, NULL, -1, system->Bounds->TopRightPoint->Y);
_eventsList->push_back(event);
}
}
}
void CDParticlesCollisionDetection2DLogic::ComputeMinimalTimeOfCollision(int time)
{
}
void CDParticlesCollisionDetection2DLogic::ChangeVelocityAfterTwoParticleCollision(CDParticle2D *p1, CDParticle2D *p2)
{
// TODO: need to implement
}
void CDParticlesCollisionDetection2DLogic::ChangeVelocityAfterParticlesCollisionWithBound(CDParticle2D *p, float bound)
{
// TODO: need to implement
}
//--------------------------------------------------------------------
// Public functions
//--------------------------------------------------------------------
void CDParticlesCollisionDetection2DLogic::DecectCollisionBetweenParticlesInTime(int time)
{
// If inequation is true - then make a computation
// Else - skip computation
unsigned long eventsListSize = this->_eventsList->size();
CDEvent *nextEvent; // TODO: need to implement
float timeOfNextEvent = nextEvent->TimeToEvent;
float localTime = nextEvent->Particle1->LocalTime;
if(fabs(time - (localTime + timeOfNextEvent)) < _eps)
{
}
else if(eventsListSize == 0)
{
this->ComputeMinimalTimeOfCollision(time);
}
}
| true |
164fe5b92cf169ab2de4b74c7df69ce834cb4f95 | C++ | vietduy1512/nachos-examples | /code/userprog/stable.h | UTF-8 | 833 | 2.546875 | 3 | [
"MIT-Modern-Variant"
] | permissive | #ifndef STATE_H
#define STATE_H
#include "synch.h"
#include "bitmap.h"
#include "sem.h"
#define MAX_SEMAPHORE 10
class STable
{
private:
BitMap* bm; // Quan ly slot trong.
Sem* semTab[MAX_SEMAPHORE]; // Quan ly toi da 10 doi tuong Sem.
public:
// Khoi tao size doi tuong Sem de quan ly 10 Semaphore. Gan gia tri ban dau la NULL.
// Nho khoi tao bm de su dung.
STable();
~STable(); // Huy cac doi tuong da tao.
int Create(char* name, int init); // Kiem tra Semaphore "name", neu chua ton tai thi tao Semaphore moi, nguoc lai bao loi.
int Wait(char* name); // Neu ton tai Semaphore "name" thi goi this->P() de thuc thi, nguoc lai thi bao loi.
int Signal(char* name); // Neu ton tai Semaphore "name" thi goi this->V() de thuc thi, nguoc lai thi bao loi.
int FindFreeSlot(int id); // Tim slot trong.
};
#endif
| true |
d94aafb7a0e42c4098ff530f88aaade62f4e6fe4 | C++ | Aguirregzz97/TareasFundamentosDeProgramacion | /FuncionesConCondiciones9/main.cpp | UTF-8 | 677 | 3.5625 | 4 | [] | no_license | // Andres Aguirre Gonzalez A01039656
#include <iostream>
using namespace std;
char Calculatebig(int a, int b, int c)
{
char BiggestNumber;
if(a >= b && a>= c)
{
BiggestNumber = 'a';
}
if(b >= a && b>= c)
{
BiggestNumber = 'b';
}
if(c >= a && c >= b)
{
BiggestNumber = 'c';
}
return BiggestNumber;
}
int main()
{
int a,b,c;
char BiggestNumber;
cout << "Write number a" << endl;
cin >> a;
cout << "Write number b" << endl;
cin >> b;
cout << "Write number c" << endl;
cin >> c;
BiggestNumber = Calculatebig(a,b,c);
cout << "Your biggest number is " << BiggestNumber;
return 0;
}
| true |
fb79c829c694fa74233c63bbff6d1dad42199f02 | C++ | derekzhang79/TopCoder | /151/prefix.cpp | UTF-8 | 708 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
bool prefix(string str1,string str2){
if(str2.length()<str1.length()) return 0;
int i,length = str1.length();
for(i=0;i<length;i++){
if(str1[i] != str2[i]) return 0;
}
return 1;
}
string isOne(vector<string> words){
string retval = "Yes";
int i,j,length = words.size();
for(i=0;i<length;i++){
for(j=0;j<length;j++){
if(j!=i){
if(prefix(words[i],words[j])){
retval = "No, ";
retval.push_back(i+'0');
return retval;
}
}
}
}
return retval;
}
int main(){
string curr;
vector<string> v;
while(cin>>curr) v.push_back(curr);
cout<<isOne(v)<<endl;
return 0;
}
| true |
d2cb935c3b504f75daf0a572ad8695e762791737 | C++ | bluenote10/EPI | /test/14_08.cpp | UTF-8 | 596 | 3.28125 | 3 | [] | no_license | #include "convenience.hpp"
void Blockify(vector<int>& A, int max_idx) {
if (max_idx <= 0) return;
int pivot = A[0];
A[max_idx] = A[0];
int i = 0;
int j = max_idx - 1;
int k = 1;
while (i < j) {
cout << A << " " << i << " " << j << " " << k << endl;
if (A[k] != pivot) {
swap(A[i++], A[k++]);
} else {
swap(A[j--], A[k]);
}
}
Blockify(A, j);
}
int main(int argc, char** args) {
vector<int> v = {2, 1, 2, 2, 1, 2, 1, 1};
Blockify(v, v.size()-1);
cout << v << endl;
return 0;
}
| true |
8cfc60e6c68e7d6d07a3ad07f8848a8b4d654ff9 | C++ | bmikaeli/CPP-Pool-42 | /Rush00/AAlien.class.cpp | UTF-8 | 1,010 | 2.71875 | 3 | [] | no_license | #include "AAlien.class.hpp"
#include <unistd.h>
void AAlien::takeDamage() {
this->hp -= 1;
}
AAlien::AAlien() {
}
AAlien::~AAlien() {
}
void AAlien::drawDeath(WINDOW * win) {
wattron(win, COLOR_PAIR(2));
mvwprintw(win, this->Y, this->X, "W");
mvwprintw(win, this->Y + 1, this->X - 1, "WWW");
wattron(win, COLOR_PAIR(1));
wrefresh(win);
usleep(10000);
}
void AAlien::draw(WINDOW * win) {
mvwprintw(win, this->Y, this->X, "X");
mvwprintw(win, this->Y + 1, this->X - 1, "XXX");
}
int AAlien::checkColision(int x, int y) {
if ((this->X == x && this->Y == y) || (this->X - 1 == x && this->Y == y) || (this->X + 1 == x && this->Y == y)) {
return 1;
}
else {
return 0;
}
}
AAlien &AAlien::operator=(AAlien &rhs) {
this->hp = rhs.hp;
this->scoreValue = rhs.scoreValue;
this->bulletSkin = rhs.bulletSkin;
this->X = rhs.X;
this->direction = rhs.direction;
this->size = rhs.size;
this->Y = rhs.Y;
return *this;
}
| true |
e124b2b29f3f93586855fc31ca143a79a445a45d | C++ | ymarcov/Chili | /include/Request.h | UTF-8 | 3,065 | 2.796875 | 3 | [] | no_license | #pragma once
#include "InputStream.h"
#include "Protocol.h"
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Chili {
/**
* An HTTP request.
*/
class Request {
public:
Request() = default;
Request(std::shared_ptr<InputStream> input);
~Request();
/**
* Gets the HTTP method of the request.
*/
Method GetMethod() const;
/**
* Gets the URI string of the request.
*/
std::string_view GetUri() const;
/**
* Gets the HTTP version of the request.
*/
Version GetVersion() const;
/**
* Gets the names of all headers present in the request.
*/
std::vector<std::string_view> GetHeaderNames() const;
/**
* Returns true if the request contains a header with the specified name.
*/
bool HasHeader(const std::string_view& name) const;
/**
* Tries to get a header by name, returns true if it was found.
*
* If header was found and value is not null, then value is set.
* Otherwise, value is ignored.
*/
bool GetHeader(const std::string_view& name, std::string* value) const;
/**
* Gets a header by name.
* Throws if the header does not exist.
*/
std::string_view GetHeader(const std::string_view& name) const;
/**
* Returns true if the request has a message
* body (i.e. Content-Length > 0).
*/
bool HasContent() const;
/**
* If the message has associated content, returns true if
* the content is already entirely available to be read.
*/
bool IsContentAvailable() const;
/**
* Gets the length of the associated content.
* Returns 0 if the Content-Length header is not present.
*/
std::size_t GetContentLength() const;
/**
* Gets whether the connection should be kept alive.
*/
bool KeepAlive() const;
/**
* Gets the message content, beside the header.
*/
const std::vector<char>& GetContent() const;
/**
* @internal
* Reads and parses the request.
* Returns whether the opreation is completed, and how many bytes were read.
*/
bool ConsumeHeader(std::size_t maxBytes, std::size_t& totalBytesRead);
/*
* @internal
* Read data from the request content body and advances the stream position.
* Returns whether the opreation is completed, and how many bytes were read.
*/
bool ConsumeContent(std::size_t maxBytes, std::size_t& totalBytesRead);
private:
friend class HttpParserSettings;
class HttpParserStringBuilder& GetStringBuilder();
std::vector<char> _buffer;
std::size_t _bufferPosition = 0;
std::shared_ptr<InputStream> _input;
void* _privateData;
std::size_t _headerBytesParsed = 0;
bool _parsedHeader = false;
bool _onlySentHeaderFirst = false;
std::string_view _uri;
std::vector<std::pair<std::string_view, std::string_view>> _headers;
std::vector<char> _content;
std::size_t _contentPosition = 0;
};
} // namespace Chili
| true |
b552485bb6504a6cdf3a9f94a13209892ccba9ec | C++ | GabrielOarga/cpp-workshop | /Advanced_C++_Training/advcpp_personal/15_TemplateClassesAndFunctions/15_TemplateClassesAndFunctions/main.cpp | UTF-8 | 1,098 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include "RingBuffer.h"
using namespace std;
template <typename T>
void foo(T t)
{
cout << "generic" << endl;
}
/*
template <> //if template specialisation exists, it will be called rather then the normal template
void foo(int i)
{
cout << "specialised template function for no param" << endl;
}
*/
/*
void foo(int i)
{
cout << "specific (non-template) function" << endl;
}
*/
int main()
{
RingBuffer<string> names(3);
names.add("Ion");
names.add("Mihai");
names.add("Paul");
names.add("Ionel"); // will replace "Ion" on position 0
for (RingBuffer<string>::iterator it = names.begin(); it != names.end(); ++it)
{
cout << *it << endl;
}
RingBuffer<int> numbers{ 1, 2, 3, 4 };
foo<int>(10); //calls template function because of <>
foo<>(10); // same as asbove
foo(10); // calls nnon template function || daca nu este functie non template, va fi chemata si in cazul acesta functia cucu template
getchar();
return 0;
}
| true |
b5fa8ff06c2e26b5dd1c4043231ce4198b147a15 | C++ | Stephen1993/ACM-code | /hdu2159.cpp | GB18030 | 934 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using namespace std;
const int MAX=101;
int dp[MAX][MAX];//dpʾiɱjֵֻõľֵ.
int value[MAX][MAX];
int main(){
int n,m,k,s;
while(cin>>n>>m>>k>>s){
memset(dp,0,sizeof dp);
for(int i=0;i<k;++i){
cin>>value[i][0]>>value[i][1];
}
int min=-1;
//άñ,ɱĹΪ.
for(int i=0;i<k;++i){
for(int j=value[i][1];j<=m;++j){
for(int t=1;t<=s;++t){//for(int t=s;t>=1;--t)Ҳ.
dp[j][t]=max(dp[j][t],dp[j-value[i][1]][t-1]+value[i][0]);
if(dp[j][t]>=n)min=min>(m-j)?min:(m-j);//ڻõľnʣ.
}
}
}
cout<<min<<endl;
}
return 0;
} | true |
6035ee569f68ee29864885c8eb3622e0ff1b54d3 | C++ | arilow/TallerTPGrupal | /Game/src/server_src/collisions/QuadNode.cpp | UTF-8 | 5,078 | 3.265625 | 3 | [] | no_license | #include "Quadtree.h"
#include "Collidable.h"
#include <iostream>
#include <math.h>
#include <vector>
//se creaa un nodo raiz vacio
QuadNode::QuadNode(int x_, int y_, int w_, int h_, std::string n, size_t l, int cW):
bounds(x_,y_,w_,h_), data(0)
{
cellWidth=cW;
lvl=l;
name=n;
this->NW = nullptr;
this->NE = nullptr;
this->SE = nullptr;
this->SW = nullptr;
}
QuadNode::~QuadNode(){
for(int i=0; i<data.size(); i++){
if(data[i]!=NULL){
delete data[i];
data[i]=NULL;
}
}
if (NW != nullptr) delete NW;
if (NE != nullptr) delete NE;
if (SW != nullptr) delete SW;
if (SE != nullptr) delete SE;
}
//si no fuera una hoja, ningun puntero podria ser nulo
bool QuadNode::isLeaf(){return NW==nullptr;}
bool QuadNode::insert(Collidable *point){//Método que inserta puntos en el árbol
if(!bounds.contains(*point)){
return false;
}
if(isLeaf()){ //Si es una hoja el punto se inserta en este nodo
if (data.size() < capacity){
data.push_back(point);
return true;
}
split(); //Si el nodo alcanza su capacidad máxima se divide
}
//Si no es una hoja o se divide, inserta el punto en el primer punto que le sea posible
if(NW->insert(point)){
return true;
}
if(NE->insert(point)){
return true;
}
if(SW->insert(point)){
return true;
}
if(SE->insert(point)){
return true;
}
return false;
}
void QuadNode::split(){ //método que divide el nodo en 4 subnodos
int x= bounds.getxInit();
int y= bounds.getyInit();
int w= bounds.getxEnd();
int h= bounds.getyEnd();
int dX=(w - x)/2;
int dY=(h - y)/2;
std::vector<Collidable*> aux;
if(dX%cellWidth!=0)
dX = dX - dX%cellWidth + cellWidth;
if(dY%cellWidth!=0)
dY = dY - dY%cellWidth + cellWidth;
//creacion de los 4 nodos hijos segun el limite de su respectivo cuadrante
NW= new QuadNode( x, y, x + dX, y + dY, "NW", lvl+1, cellWidth);
NE= new QuadNode( x + dX, y, w, y + dY, "NE", lvl+1, cellWidth);
SW= new QuadNode( x, y + dY, x + dX, h, "SW", lvl+1, cellWidth);
SE= new QuadNode( x + dX, y + dY, w, h, "SE", lvl+1, cellWidth);
// encuentra un hijo en el cual incluir cada punto de los que estan en data[]
for(int i = 0; i < data.size(); i++){
if(NW->insert(data[i])){
continue;
}
if(NE->insert(data[i])){
continue;
}
if(SW->insert(data[i])){
continue;
}
if(SE->insert(data[i])){
continue;
}
aux.push_back(data[i]);
}
while(data.empty()!=true)
data.pop_back();
for(size_t i=0; i<aux.size();i++){
data.push_back(aux[i]);
}
}
bool QuadNode::erase(float x, float y){
bool coll=false;
if(bounds.contains(x,y)==false){
return false;
}
for(int i=0; i<data.size(); i++){
if(data[i]->detectCollision(x, y, 0, 0)==true){
delete data[i];
data.erase(data.begin()+i);
coll=true;
}
}
if(isLeaf()==false){
coll= coll || NW->erase(x, y);
coll= coll || NE->erase(x, y);
coll= coll || SW->erase(x, y);
coll= coll || SE->erase(x, y);
}
return coll;
}
bool QuadNode::erase(circle &pPos){
// std::cout<<"erase col"<<std::endl;
bool coll=false;
if(bounds.contains(pPos)==false){
return false;
}
for(int i=0; i<data.size(); i++){
if(data[i]->detectCollision(pPos, 0, 0)==true){
// std::cout<<"eliminado"<<std::endl;
delete data[i];
data.erase(data.begin()+i);
coll=true;
}
}
if(isLeaf()==false){
coll= coll || NW->erase(pPos);
coll= coll || NE->erase(pPos);
coll= coll || SW->erase(pPos);
coll= coll || SE->erase(pPos);
}
return coll;
}
bool QuadNode::detectCollision(circle &c, float dX, float dY, std::vector<Collidable*> &col){
bool coll=false;
circle auxC={c.x+dX,c.y+dY,c.radius};
if(bounds.contains(auxC)==false){
return false;
}
for(int i=0; i<data.size(); i++){
if(data[i]->detectCollision(c, dX,dY)==true){
// std::cout<<"colision detectada"<<std::endl;
col.push_back(data[i]);
coll=true;
}
}
if(isLeaf()==false){
coll= coll || NW->detectCollision(c, dX, dY, col);
coll= coll || NE->detectCollision(c, dX, dY, col);
coll= coll || SW->detectCollision(c, dX, dY, col);
coll= coll || SE->detectCollision(c, dX, dY, col);
}
return coll;
}
std::ostream & operator<< (std::ostream &os, QuadNode &n){
os<<"name: "<<n.name<<std::endl;
os<<"lvl: "<<n.lvl<<std::endl;
os<<"bounds: "<<std::endl;
os<<n.bounds;
os<<"data: "<<std::endl;
for(int i=0;i<n.data.size(); i++){
os<<"elemento: "<<i<<std::endl;
os<<*n.data[i];
}
return os;
}
| true |
a0b27f68e712d7c6699652ee20f5dcbcf5db0aa2 | C++ | Ambition111/OJ | /exchange.cpp | GB18030 | 1,247 | 3.4375 | 3 | [] | no_license | // Ŀӣhttps://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
// һ
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
vector<int> ret(nums.size(), 0);
int i = 0, j = nums.size() - 1;
for (const auto& e : nums)
{
if (e % 2 == 1)
ret[i++] = e;
else
ret[j--] = e;
}
return ret;
}
};
//
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = -1, j = 0;
while (j < nums.size())
{
if (nums[j] % 2 == 1)
swap(nums[++i], nums[j]);
++j;
}
return nums;
}
};
//
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while(left < right)
{
if (nums[left] % 2 == 1){
++left;
continue;
}
else if (nums[right] % 2 == 0){
--right;
continue;
}
swap(nums[left++], nums[right--]);
}
return nums;
}
};
| true |
99016574bee6636cfe3d5816472578febf30e1dd | C++ | michaelmathen/pyscan | /src/TrajectoryCoreSet.cpp | UTF-8 | 24,513 | 2.53125 | 3 | [
"MIT"
] | permissive | //
// Created by mmath on 9/28/18.
//
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include "appext.h"
#include "Point.hpp"
#include "Disk.hpp"
#include "FunctionApprox.hpp"
#include "TrajectoryCoreSet.hpp"
namespace pyscan {
/*
* Compute the lower leftmost corner of a box containing these points.
*/
std::tuple<double, double, double, double> bounding_box(point_list_t::const_iterator traj_b,
point_list_t::const_iterator traj_e) {
double lx = (*traj_b)(0), ux = (*traj_b)(0), ly = (*traj_b)(1), uy = (*traj_b)(1);
for ( ; traj_b != traj_e; traj_b++) {
lx = std::min(lx, (*traj_b)(0));
ux = std::max(ux, (*traj_b)(0));
ly = std::min(ly, (*traj_b)(1));
uy = std::max(uy, (*traj_b)(1));
}
return std::make_tuple(lx, ly, ux, uy);
}
double x_to_y(double x_1, double y_1, double x_2, double y_2, double x) {
return (y_1 - y_2) / (x_1 - x_2) * (x - x_1) + y_1;
}
double y_to_x(double x_1, double y_1, double x_2, double y_2, double y) {
return (x_1 - x_2) / (y_1 - y_2) * (y - y_1) + x_1;
}
long index(double x, double y, double lx, double ly, double chord_l, long g_size) {
long i = static_cast<long>((x - lx) / chord_l);
long j = static_cast<long>((y - ly) / chord_l);
return i + g_size * j;
}
bool inside_box(double x, double y, pt2_t const& lpt, pt2_t const& rpt) {
double ux = std::max(lpt(0), rpt(0));
double lx = std::min(lpt(0), rpt(0));
double uy = std::max(lpt(1), rpt(1));
double ly = std::min(lpt(1), rpt(1));
return util::alte(x, ux) && util::alte(lx, x) && util::alte(y, uy) && util::alte(ly, y);
}
/*
* Takes a trajectory and grids it so that each grid contains points that cross the boundaries of the trajectory.
*/
std::unordered_map<long, std::vector<Point<>>> grid_traj(point_list_t::const_iterator traj_b,
point_list_t::const_iterator traj_e,
double chord_l,
double& ux, double &uy, double& lx, double& ly) {
auto last_pt = traj_b;
if (last_pt == traj_e) {
return {};
}
std::tie(lx, ly, ux, uy) = bounding_box(traj_b, traj_e);
long g_size = static_cast<long>((ux - lx) / chord_l) + 1;
std::unordered_map<long, std::vector<Point<>>> traj_points;
if (traj_e - traj_b == 1) {
//If this is a single point then we just return the point.
traj_points.emplace(0, std::vector<Point<>>(traj_b, traj_e));
return traj_points;
}
long location = index((*last_pt)(0), (*last_pt)(1), lx, ly, chord_l, g_size);
traj_points.emplace(location, std::initializer_list<Point<>>{*last_pt});
for (auto curr_pt = last_pt + 1; curr_pt != traj_e; curr_pt++) {
auto g_x = static_cast<int>(((*last_pt)(0) - lx) / chord_l);
auto g_y = static_cast<int>(((*last_pt)(1) - ly) / chord_l);
auto g_n_x = static_cast<int>(((*curr_pt)(0) - lx) / chord_l);
auto g_n_y = static_cast<int>(((*curr_pt)(1) - ly) / chord_l);
if (g_n_x < g_x) {
std::swap(g_n_x, g_x);
}
if (g_n_y < g_y) {
std::swap(g_n_y, g_y);
}
for (int i = g_x; i <= g_n_x; i++) {
double x_val = i * chord_l + lx;
double y_val = x_to_y((*last_pt)(0), (*last_pt)(1), (*curr_pt)(0), (*curr_pt)(1), x_val);
if (!inside_box(x_val, y_val, *last_pt, *curr_pt)) {
continue;
}
int j = static_cast<int>((y_val - ly) / chord_l);
auto element = traj_points.find(i + g_size * j);
if (element == traj_points.end()) {
traj_points.emplace(i + g_size * j, std::initializer_list<Point<>>{Point<>(x_val, y_val, 1.0)});
} else {
element->second.emplace_back(x_val, y_val, 1.0);
}
}
for (int j = g_y; j <= g_n_y; j++) {
double y_val = j * chord_l + ly;
double x_val = y_to_x((*last_pt)(0), (*last_pt)(1), (*curr_pt)(0), (*curr_pt)(1), y_val);
if (!inside_box(x_val, y_val, *last_pt, *curr_pt)) {
continue;
}
int i = static_cast<int>((x_val - lx) / chord_l);
auto element = traj_points.find(i + g_size * j);
if (element == traj_points.end()) {
traj_points.emplace(i + g_size * j, std::initializer_list<Point<>>{Point<>(x_val, y_val, 1.0)});
} else {
element->second.emplace_back(x_val, y_val, 1.0);
}
}
location = index((*curr_pt)(0), (*curr_pt)(1), lx, ly, chord_l, g_size);
auto element = traj_points.find(location);
if (element == traj_points.end()) {
traj_points.emplace(location, std::initializer_list<Point<>>{*curr_pt});
} else {
element->second.push_back(*curr_pt);
}
last_pt = curr_pt;
}
return traj_points;
}
/*
* This is a wrapper for grid_traj that ensures all points are in their own cells.
*/
point_list_t grid_traj(point_list_t const& traj, double grid_resoluation) {
point_list_t pts;
double ly, lx, ux, uy;
for (auto& elements : grid_traj(traj.begin(), traj.end(), grid_resoluation, ux, uy, lx, ly)) {
pts.insert(pts.end(), elements.second.begin(), elements.second.end());
}
remove_duplicates(pts);
return pts;
}
/*
* Takes a trajectory and grids it so that each grid contains a single point of a trajectory that crosses it.
* Chooses the cell to be in the center of each grid cell.
*/
point_list_t approx_traj_grid(point_list_t const& trajectory, double grid_resolution) {
auto traj_b = trajectory.begin(), traj_e = trajectory.end();
auto last_pt = traj_b;
if (last_pt == traj_e) {
return {};
}
double lx, ly, ux, uy;
std::tie(lx, ly, ux, uy) = bounding_box(traj_b, traj_e);
long g_size = static_cast<long>((ux - lx) / grid_resolution) + 1;
std::unordered_set<long> traj_labels;
long location = index((*last_pt)(0), (*last_pt)(1), lx, ly, grid_resolution, g_size);
traj_labels.emplace(location);
for (auto curr_pt = last_pt + 1; curr_pt != traj_e; curr_pt++) {
auto g_x = static_cast<int>(((*last_pt)(0) - lx) / grid_resolution);
auto g_y = static_cast<int>(((*last_pt)(1) - ly) / grid_resolution);
auto g_n_x = static_cast<int>(((*curr_pt)(0) - lx) / grid_resolution);
auto g_n_y = static_cast<int>(((*curr_pt)(1) - ly) / grid_resolution);
if (g_n_x < g_x) {
std::swap(g_n_x, g_x);
}
if (g_n_y < g_y) {
std::swap(g_n_y, g_y);
}
for (int i = g_x + 1; i <= g_n_x; i++) {
double x_val = i * grid_resolution + lx;
double y_val = x_to_y((*last_pt)(0), (*last_pt)(1), (*curr_pt)(0), (*curr_pt)(1), x_val);
if (!inside_box(x_val, y_val, *last_pt, *curr_pt)) {
continue;
}
int j = static_cast<int>((y_val - ly) / grid_resolution);
auto element = traj_labels.find(i + g_size * j);
if (element == traj_labels.end()) {
traj_labels.emplace(i + g_size * j);
}
}
for (int j = g_y + 1; j <= g_n_y; j++) {
double y_val = j * grid_resolution + ly;
double x_val = y_to_x((*last_pt)(0), (*last_pt)(1), (*curr_pt)(0), (*curr_pt)(1), y_val);
if (!inside_box(x_val, y_val, *last_pt, *curr_pt)) {
continue;
}
int i = static_cast<int>((x_val - lx) / grid_resolution);
auto element = traj_labels.find(i + g_size * j);
if (element == traj_labels.end()) {
traj_labels.emplace(i + g_size * j);
}
}
location = index((*curr_pt)(0), (*curr_pt)(1), lx, ly, grid_resolution, g_size);
auto element = traj_labels.find(location);
if (element == traj_labels.end()) {
traj_labels.emplace(location);
}
last_pt = curr_pt;
}
//Now convert the set into a set of points
point_list_t simplified_traj;
for (auto label : traj_labels) {
long i = label % g_size;
long j = label / g_size;
//std::cout << i << " " << j << std::endl;
double x_val_low = i * grid_resolution + lx;
double y_val_low = j * grid_resolution + ly;
double x_val_up = (i + 1) * grid_resolution + lx;
double y_val_up = (j + 1) * grid_resolution + ly;
simplified_traj.emplace_back((x_val_low + x_val_up) / 2.0, (y_val_up + y_val_low) / 2.0, 1.0);
}
return simplified_traj;
}
std::unordered_map<long, std::vector<Point<>>>
approximate_traj_cells(point_list_t::const_iterator traj_b,
point_list_t::const_iterator traj_e, double chord_l, double eps) {
double ux, uy, lx, ly;
auto cells = grid_traj(traj_b, traj_e, chord_l, ux, uy, lx, ly);
for (auto b = cells.begin(); b != cells.end(); b++) {
auto approx = eps_core_set(eps, [&](Vec2 const& direction) {
auto pt_max = std::max_element(b->second.begin(), b->second.end(),
[&] (Point<> const& p1, Point<> const& p2){
double mag_1 = p1(0) * direction[0] + p1(1) * direction[1];
double mag_2 = p2(0) * direction[0] + p2(1) * direction[1];
return mag_1 < mag_2;
});
return Vec2{(*pt_max)(0), (*pt_max)(1)};
});
b->second.clear();
for (auto approx_b = approx.begin(); approx_b != approx.end(); approx_b++) {
b->second.emplace_back((*approx_b)[0], (*approx_b)[1], 1.0);
}
}
return cells;
}
void approx_traj(point_list_t::const_iterator traj_b, point_list_t::const_iterator traj_e,
double chord_l, double eps, point_list_t& output) {
for (auto& elements : approximate_traj_cells(traj_b, traj_e, chord_l, eps)) {
output.insert(output.end(), elements.second.begin(), elements.second.end());
}
}
void approx_traj_labels(point_list_t::const_iterator traj_b, point_list_t::const_iterator traj_e,
double chord_l, double eps, size_t label, double weight, lpoint_list_t& output) {
for (auto& elements : approximate_traj_cells(traj_b, traj_e, chord_l, eps)) {
for (auto& pt : elements.second) {
output.emplace_back(label, weight, pt[0], pt[1], pt[2]);
}
}
remove_duplicates(output);
}
point_list_t approx_traj_kernel_grid(point_list_t const& trajectory_pts, double chord_l, double eps) {
point_list_t output;
for (auto& elements : approximate_traj_cells(trajectory_pts.begin(), trajectory_pts.end(), chord_l, eps)) {
for (auto& pt : elements.second) {
//Create a point with the desired weight and label.
output.emplace_back(pt[0], pt[1], pt[2]);
}
}
remove_duplicates(output);
return output;
}
point3_list_t kernel3d(point3_list_t const& pts, double eps) {
auto glpts = new glReal[3 * pts.size()];
for (size_t i = 0; i < pts.size(); i++) {
glpts[i * 3 ] = pts[i](0);
glpts[i * 3 + 1] = pts[i](1);
glpts[i * 3 + 2] = pts[i](2);
}
glPointSet kernel_set;
assert(pts.size() <= static_cast<size_t>(std::numeric_limits<int>::max()));
kernel_set.init(3, static_cast<int>(pts.size()), glpts);
glPointSet* p = kernel_set.getCoreSet3(static_cast<int>(2 / eps), eps / 2); // compute robust coreset
point3_list_t core_set;
// the reason why this starts at 1 is because the first point is always 0,0 for some reason.
for (int i = 1; i < p->getNum(); i++) {
glReal pt[3];
p->getPoint(i, pt);
core_set.emplace_back(pt[0], pt[1], pt[2], 1.0);
}
p->dump();
delete[] glpts;
kernel_set.dump();
free(p);
return core_set;
}
inline pt3_t lift_pt(pt2_t const& pt) {
double x = pt(0);
double y = pt(1);
return pt3_t(x, y, x * x + y * y, 1.0);
}
point_list_t lifting_coreset(point_list_t const& segments, double eps) {
point_list_t pts = grid_traj(segments, eps / 2.0);
point3_list_t lifted_set(pts.size(), pt3_t());
std::transform(pts.begin(), pts.end(), lifted_set.begin(), lift_pt);
auto pt3_set = kernel3d(lifted_set, eps);
point_list_t output_pts;
for (auto& pt : pt3_set) {
output_pts.emplace_back(pt(0), pt(1), 1.0);
}
return output_pts;
}
// This function does a Ramer-Douglas-Peucker Compression over a Trajectory
// For more info, pls refer to:
// https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
void rdp_compress(point_list_t::const_iterator begin, point_list_t::const_iterator end,
point_list_t& compressed, double eps) {
if (end - begin <= 1) {
return;
}
auto max_it = begin;
double max = 0.0;
for (auto it = begin + 1; it != end - 1; ++it) {
auto tmp_dis = it->square_dist(*begin, *(end - 1));
if (max < tmp_dis) {
max = tmp_dis;
max_it = it;
}
}
if (max > eps * eps) {
rdp_compress(begin, max_it + 1, compressed, eps);
compressed.pop_back();
rdp_compress(max_it, end, compressed, eps);
} else {
compressed.push_back(*begin);
compressed.push_back(*(end - 1));
}
}
point_list_t dp_compress(const point_list_t& trajectory, double eps) {
point_list_t simplified_traj;
rdp_compress(trajectory.begin(), trajectory.end(), simplified_traj, eps);
return simplified_traj;
}
double total_length(const point_list_t& pts) {
return trajectory_t(pts).get_length();
}
point_list_t interval_sample(const trajectory_set_t& trajectories, std::vector<double>& indices, bool take_endpoints, bool take_single) {
std::sort(indices.begin(), indices.end());
double scaling_fact = std::accumulate(trajectories.begin(), trajectories.end(), 0.0,
[&](const double& cum_weight, const trajectory_t& traj) {
return cum_weight + traj.get_length() * traj.get_weight();
});
point_list_t sample_pts;
auto idx = indices.begin();
double curr_length = 0;
for (auto& traj : trajectories) {
if (traj.empty()) {
continue;
}
auto last_pt = *(traj.begin());
bool one_taken = take_endpoints;
if (take_endpoints) {
sample_pts.push_back(last_pt);
}
for (auto traj_b = traj.begin() + 1; traj_b != traj.end(); traj_b++) {
double seg_length = (last_pt.dist(*traj_b) * traj.get_weight()) / scaling_fact;
while (idx != indices.end() && seg_length + curr_length > *idx) {
double inside_length = (*idx - curr_length) / traj.get_weight();
double alpha = inside_length * scaling_fact / last_pt.dist(*traj_b);
alpha = std::min(1.0, std::max(alpha, 0.0));
// Create a new point on this line segment scaled between the two.
one_taken = true;
sample_pts.emplace_back(last_pt.on_segment(*traj_b, alpha));
idx++;
}
if (take_endpoints) {
sample_pts.push_back(*traj_b);
}
//Increment last_pt to the current point and update the total length.
last_pt = *traj_b;
curr_length += seg_length;
}
if (!one_taken && take_single) {
sample_pts.push_back(last_pt);
}
}
return sample_pts;
}
point_list_t interval_sample_single(const point_list_t& traj, std::vector<double>& indices, bool take_endpoints, bool take_single) {
std::sort(indices.begin(), indices.end());
double scaling_fact = trajectory_t(traj).get_length();
point_list_t sample_pts;
auto idx = indices.begin();
double curr_length = 0;
if (traj.empty()) {
return sample_pts;
}
auto last_pt = *(traj.begin());
bool one_taken = take_endpoints;
if (take_endpoints) {
sample_pts.push_back(last_pt);
}
for (auto traj_b = traj.begin() + 1; traj_b != traj.end(); traj_b++) {
double seg_length = last_pt.dist(*traj_b) / scaling_fact;
while (idx != indices.end() && seg_length + curr_length > *idx) {
double inside_length = (*idx - curr_length);
double alpha = inside_length * scaling_fact / last_pt.dist(*traj_b);
alpha = std::min(1.0, std::max(alpha, 0.0));
// Create a new point on this line segment scaled between the two.
one_taken = true;
sample_pts.emplace_back(last_pt.on_segment(*traj_b, alpha));
idx++;
}
if (take_endpoints) {
sample_pts.push_back(*traj_b);
}
//Increment last_pt to the current point and update the total length.
last_pt = *traj_b;
curr_length += seg_length;
}
if (!one_taken && take_single) {
sample_pts.push_back(last_pt);
}
return sample_pts;
}
point_list_t uniform_sample(const trajectory_set_t& trajectories, size_t s, bool take_endpoints) {
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> distribution(0.0, 1.0);
std::vector<double> indices;
for (size_t i = 0; i < s; i++) {
indices.push_back(distribution(generator));
}
return interval_sample(trajectories, indices, take_endpoints, false);
}
point_list_t even_sample(const trajectory_set_t& trajectories, size_t s, bool take_endpoints) {
/*
* sample s points at 1/s distance appart.
*/
std::vector<double> indices;
for (size_t i = 0; i < s; i++) {
indices.emplace_back( (i + .5) / s);
}
return interval_sample(trajectories, indices, take_endpoints, false);
}
point_list_t block_sample(const trajectory_set_t& trajectories, size_t s, bool take_endpoints) {
/*
* Chooses a single point uniformly at random in every alpha block of length L.
*/
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> distribution(0.0, 1.0 / s);
std::vector<double> indices;
for (size_t i = 0; i < s; i++) {
indices.push_back(i / static_cast<double>(s) + distribution(generator));
}
return interval_sample(trajectories, indices, take_endpoints, false);
}
point_list_t uniform_sample_error(const point_list_t& traj, double eps, bool take_endpoints) {
double wl = total_length(traj);
assert(wl >= 0);
auto s = static_cast<size_t>(std::lround(wl / eps));
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> distribution(0.0, 1.0);
std::vector<double> indices;
for (size_t i = 0; i < s; i++) {
indices.push_back(distribution(generator));
}
return interval_sample_single(traj, indices, take_endpoints, true);
}
point_list_t even_sample_error(const point_list_t& traj, double eps, bool take_endpoints){
double wl = total_length(traj);
assert(wl >= 0);
auto s = static_cast<size_t>(std::lround(wl / eps));
std::vector<double> indices;
for (size_t i = 0; i < s; i++) {
indices.emplace_back( (i + .5) / s);
}
return interval_sample_single(traj, indices, take_endpoints, true);
}
point_list_t block_sample_error(const point_list_t& traj, double eps, bool take_endpoints) {
double wl = total_length(traj);
assert(wl >= 0);
auto s = static_cast<size_t>(std::lround(wl / eps));
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<double> distribution(0.0, 1.0 / s);
std::vector<double> indices;
for (size_t i = 0; i < s; i++) {
indices.push_back(i / static_cast<double>(s) + distribution(generator));
}
return interval_sample_single(traj, indices, take_endpoints, true);
}
std::tuple<halfspace2_t, double> error_halfplane_coreset(const trajectory_t& trajectory, const point_list_t& pts) {
halfspace2_t max_plane;
double eps = 0;
for (size_t i = 0; i < pts.size() - 1; i++) {
for (size_t j = i + 1; j < pts.size(); j++) {
halfspace2_t curr_plane(pts[i], pts[j]);
auto norm_f = [&curr_plane](pt2_t const& p1, pt2_t const& p2) {
return p1.pdot(curr_plane.get_coords()) < p2.pdot(curr_plane.get_coords());
};
auto [min_el, max_el] = std::minmax_element(trajectory.begin(), trajectory.end(), norm_f);
auto [min_aprx, max_aprx] = std::minmax_element(pts.begin(), pts.end(), norm_f);
double eps_1 = std::abs(curr_plane.get_coords().pdot(*min_el) - curr_plane.get_coords().pdot(*min_aprx));
double eps_2 = std::abs(curr_plane.get_coords().pdot(*max_el) - curr_plane.get_coords().pdot(*max_aprx));
if (eps < eps_1 || eps < eps_2) {
eps = std::max(eps_1, eps_2);
max_plane = curr_plane;
}
}
}
return std::make_tuple(max_plane, eps);
}
// std::tuple<Disk, double> error_disk_coreset(const trajectory_t& trajectory,
// double min_radius,
// double max_radius,
// const point_list_t& pts) {
// Disk max_disk;
// if (3 > pts.size()){
// return std::make_tuple(max_disk, std::numeric_limits<double>::infinity());
// }
// double eps = 0;
// for (size_t i = 0; i < pts.size() - 2; i++) {
// for (size_t j = i + 1; j < pts.size() - 1; j++) {
// for (size_t k = j + 1; k < pts.size(); k++) {
// Disk curr_disk(pts[i], pts[j], pts[k]);
// if (curr_disk.getRadius() > max_radius || min_radius > curr_disk.getRadius()) {
// continue;
// }
// auto min_dist = trajectory.point_dist(curr_disk.getOrigin());
// double error = std::abs(curr_disk.getRadius() - min_dist);
// if (eps < error) {
// eps = error;
// max_disk = curr_disk;
// }
// }
// }
// }
// return std::make_tuple(max_disk, eps);
// }
} | true |
12781b10165927a59e3fc8771ceafb6d101f2ae6 | C++ | misovi/tira | /gameoflife/life.h | UTF-8 | 704 | 2.734375 | 3 | [] | no_license | #include<vector>
#include<string>
//const int maxrow = 20, maxcol = 60; // grid dimensions
class Life {
private:
int maxrow = 20;
int maxcol = 60;
std::vector<std::vector<int>> grid;
//int grid[maxrow][maxcol]; // allows for two extra rows and columns
int neighbor_count(int row, int col);
public:
void neighbour_count(int row, int col);
void instructions();
void initialize();
void print();
void update();
bool user_says_yes();
void setUp();
//readint needs to be moved to a general utility library
int readInt();
bool characterExists(char c, std::string acceptedChars);
char readChar(std::string acceptedChars);
char readChar();
void save();
bool load();
};
| true |
687b167b3d35980e9920ee831518d20841e84c6f | C++ | giacomogaregnani/MasterProject | /SDECode/InverseProblemsTests/testParameterV2.cpp | UTF-8 | 3,372 | 2.75 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <iomanip>
#include "generateObservations.hpp"
#include "computeHomogeneous.hpp"
#include "computeEstimators.hpp"
// Remark: epsilon = p(0)
double gradV0(double x)
{
return x;
// return -x + x*x*x;
}
double V1(double x)
{
return std::cos(x);
}
double gradV1(double x)
{
return -std::sin(x);
}
double multiDrift(double x, VectorXd& p)
{
return -1.0 * (p(1) * gradV0(x) + 1 / p(0) * gradV1(x / p(0)));
}
double diffusion(double x, VectorXd &p)
{
return std::sqrt(2.0 * p(2));
}
int main(int argc, char* argv[])
{
oneDimSde sde{&multiDrift, &diffusion};
double IC = 0.0;
VectorXd param(3);
param(1) = 1.0; // True multiscale alpha
param(2) = 0.5; // True multiscale sigma
std::vector<double> epsTestSet = {0.01};
for (unsigned int i = 0; i < 19; i++) {
// epsTestSet.push_back(epsTestSet[i] * 1.2);
epsTestSet.push_back(epsTestSet[i] + 0.001);
}
std::ofstream output(DATA_PATH + std::string("testParamAvg.txt"), std::ofstream::out | std::ofstream::trunc);
std::ofstream outputSol(DATA_PATH + std::string("testParamSol.csv"), std::ofstream::out | std::ofstream::trunc);
bool flag = true;
// Compute coefficients of the homogenised equation
std::vector<double> homCoeffs = computeHomCoeffs(param, (2.0*M_PI), &V1);
output << homCoeffs[0] << "\t" << homCoeffs[1] << std::endl;
// Compute the estimators for different value of epsilon
double sigmaHat, AHat;
// Refer to the Caltech notes
double beta = 2;
double zeta = 1.3;
double gamma = 3.5;
for (auto const &it : epsTestSet) {
param(0) = it;
auto h = std::pow(it, beta);
auto N = static_cast<unsigned int>(std::round(std::pow(it, -gamma)));
auto T = h * N;
auto delta = static_cast<unsigned int>(std::round(std::pow(it, -zeta)));
std::cout << "============" << std::endl;
std::cout << "\u03B5 = " << it << std::endl;
std::cout << "N = " << N << ", T = " << T << std::endl;
std::cout << "\u03B4 = " << delta << std::endl;
auto solution = generateObservations1D(sde, IC, param, T, N, 0);
auto avg = averageSequence(solution, delta);
sigmaHat = delta * estimateSigma(avg, h);
AHat = estimateA(avg, h, &gradV0);
// AHat = estimateA3(avg, solution, h, &gradV0);
/* sigmaHat = 0.0; AHat = 0.0;
for (unsigned int j = 0; j < delta; j++) {
std::vector<double> samples = {};
for (unsigned int k = j; k < N; k += delta)
samples.push_back(solution[k]);
sigmaHat += estimateSigma(samples, h) / (delta * delta);
AHat += estimateA2(samples, solution, h, &gradV0) / delta;
} */
std::cout << "A = " << AHat << ", Sigma = " << sigmaHat << std::endl;
output << param(0) << "\t" << AHat << "\t" << sigmaHat << std::endl;
if (flag) {
std::cout << it << " " << h << std::endl;
for (auto itSol = solution.begin(); itSol < solution.end(); itSol++)
outputSol << *itSol << ",";
for (auto itSol = avg.begin(); itSol < avg.end(); itSol++)
outputSol << *itSol << ",";
flag = false;
}
}
output.close();
outputSol.close();
return 0;
} | true |
b83bb5d5434cad3e9efa12c05738dfd3f0cd2caf | C++ | BlackBlackSoul/II-UWr | /C++/zadanie10/10/funkcja.h | UTF-8 | 1,787 | 2.9375 | 3 | [] | no_license | #ifndef FUNKCJA_H
#define FUNKCJA_H
#include "symbol.h"
#include <map>
namespace kalkulator
{
class funkcja : public symbol
{
public:
//typ wyliczeniowy (dziala jak int tylko mamy wygodne nazwy)
enum rodzaj
{
// f_ dodane przed nazwa, bo czasem nazwy zachodzily na te uzywane w bibliotece
// matematycznej.
f_add = 0,
f_sub = 1,
f_mul = 2,
f_div = 3,
f_modulo = 4,
f_min = 5,
f_max = 6,
f_log = 7,
f_pow = 8,
f_abs = 9,
f_sgn = 10,
f_floor = 11,
f_ceil = 12,
f_frac = 13,
f_sin = 14,
f_cos = 15,
f_atan = 16,
f_acot = 17,
f_ln = 18,
f_exp = 19
};
// deklarujemy zmienna typu powyzszego enuma. Bedzie to rodzaj naszej funkcji
funkcja::rodzaj dzialanie;
// funkcja statyczna pobierajaca funkcje po jej symbolu
static funkcja::rodzaj pobierzFunkcje(std::string);
funkcja(rodzaj);
virtual ~funkcja();
// deklaracja implementacji metody wirtualnej wykonaj
void wykonaj();
protected:
private:
// metody pomocnicze dla funkcji jedno- i dwuargumentowych
std::pair<double, double> popTwo();
double popOne();
// mapa zawierajaca funkcje przypisane ich symbolom
static std::map<std::string, rodzaj> mapaFunkcji;
};
}
#endif // FUNKCJA_H
| true |
ce14ff7c77b1ae9218de8de53e2b5d19678c0ec1 | C++ | dqmcdonald/GardenLabMain | /Rain.ino | UTF-8 | 1,397 | 2.734375 | 3 | [] | no_license | //#include "Sensor.h"
//#define DEBUG_RAIN 1
const unsigned long int RAINFALL_COUNT_PERIOD = 20 * 1000l; // Update rainfall every 20 seconds
volatile int rainfall_count = 0; // Incremented in the interrupt function
// Tipping Bucket Rainfall Sensor
RainfallSensor::RainfallSensor( const String& id, const int& pin ) : Sensor(id), d_pin(pin)
{
}
void RainfallSensor::setup() {
pinMode(d_pin, INPUT_PULLUP);
attachInterrupt( digitalPinToInterrupt(d_pin), rainfallUpdate, FALLING );
d_update_time = millis();
}
void RainfallSensor::resetAccumulation() {
d_accumulated_rainfall = 0.0;
}
void RainfallSensor::update(bool) {
unsigned long int elapsed_time = millis() - d_update_time;
if ( elapsed_time > RAINFALL_COUNT_PERIOD ) {
detachInterrupt(digitalPinToInterrupt(d_pin));
d_accumulated_rainfall += 0.2794 * (float)rainfall_count; // Each switch closure is 0.2794mm
#ifdef DEBUG_RAIN
Serial.print("Updating rainfall - count = ");
Serial.print(rainfall_count );
Serial.print(" accumulated rainfall (mm) = ");
Serial.println( d_accumulated_rainfall );
#endif
rainfall_count = 0;
attachInterrupt( digitalPinToInterrupt(d_pin), rainfallUpdate, FALLING );
d_update_time += RAINFALL_COUNT_PERIOD;
}
}
float RainfallSensor::getValue() {
return d_accumulated_rainfall;
}
void RainfallSensor::rainfallUpdate()
{
rainfall_count++;
}
| true |
bdfdaf5b98223c2b7fab1df0ae1edd30e4c1a4a5 | C++ | gursangat22/git-test | /letusc++/unaryOOFRIEND.cpp | UTF-8 | 449 | 3.515625 | 4 | [] | no_license | #include<iostream>
using namespace std;
class item
{
int a,b;
public:
void get(int a,int b)
{
this->a=a;
this->b=b;
}
void display()
{
cout<<"a="<<a<<endl<<"b="<<b<<endl;
}
void friend operator -(item &m)
{
m.a=-m.a;
m.b=-m.b;
}
};
int main()
{
item n;
n.get(12,13);
n.display();
-n;
cout<<"after operator overloading!"<<endl;
n.display();
return 0;
}
| true |
f2d675542a2523296894810a511d20da18dc4da6 | C++ | beatriz-ag/feup-cal | /TPS/TP10/ex1.cpp | UTF-8 | 1,620 | 3.25 | 3 | [] | no_license | #include "exercises.h"
#include <vector>
#include <iostream>
#include <fstream>
void computePrefixFunction(std::string pattern, int* pi){
int m = pattern.size();
int k = -1;
pi[0] = -1;
for (int q = 1; q < m; q++){
while(k >= 0 and pattern[k+1] != pattern[q])
k = pi[k];
if (pattern[k+1] == pattern[q])
k++;
pi[q] = k;
}
}
int kmpMatcher(std::string text, std::string pattern) {
int n = text.size();
int m = pattern.size();
int q = -1;
int match = 0;
int pi[m];
computePrefixFunction(pattern, pi);
for (int i = 0; i < n; ++i){
while(q > 0 and pattern[q+1] != text[i])
q = pi[q];
if (pattern[q + 1] == text[i])
q++;
if (q == m - 1){
match ++;
q = pi[q];
}
}
return match;
}
int numStringMatching(std::string filename, std::string toSearch) {
std::ifstream reader(filename);
std::string sentence;
int total = 0;
if (!reader)
std::cout<< "Error reading file\n";
while(std::getline(reader,sentence)){
total += kmpMatcher(sentence,toSearch);
}
return total;
}
/// TESTS ///
#include <gtest/gtest.h>
TEST(TP10_Ex1, testKmpMatcher) {
EXPECT_EQ(3, kmpMatcher("aaabaabaacaabaa", "aabaa"));
EXPECT_EQ(0, kmpMatcher("", "a"));
EXPECT_EQ(1, kmpMatcher("a", "a"));
}
#define REL_PATH std::string("../TP10/") // relative path to the tests
TEST(TP10_Ex1, testNumStringMatching) {
int num1 = numStringMatching(REL_PATH + "text1.txt", "estrutura de dados");
EXPECT_EQ(3, num1);
int num2=numStringMatching(REL_PATH +"text2.txt", "estrutura de dados");
EXPECT_EQ(2,num2);
}
| true |
041b993de19ec5d02fca53d3680538dce0845be7 | C++ | danalrds/OOP | /Proiect/Repo.h | UTF-8 | 406 | 2.53125 | 3 | [] | no_license | #pragma once
#include "Classes.h"
#include <vector>
class Repo
{
private:
std::vector<Question> questions;
std::vector<Participant> participants;
public:
Repo();
~Repo() {};
std::vector<Question> getQ() const { return this->questions; }
std::vector<Participant> getP() const { return this->participants; }
void addQ(Question q);
void readFromFileQ();
void readFromFileP();
void printToFile();
}; | true |
9bb5e690900aaa62d0362cd099a5e3127d86cea5 | C++ | techyharshit123/DSA | /Data Structures/Graphs/01-Graph-representation.cpp | UTF-8 | 1,525 | 3.609375 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void printGraph(vector<int> adj[], int V) //V is number of vertices
{
for (int v = 0; v < V; ++v)
{
cout << "\n Adjacency list of vertex "
<< v << "\n head ";
for (auto x : adj[v])
cout << "-> " << x;
printf("\n");
}
}
// *******************************************ADJACENCY LIST*****************************
// Undirected graph
int main()
{
int n, m; // n is number of vertices and m is number of edges
cin >> n >> m;
vector<int> adj[n + 1];
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
}
// Directed Graph
int main()
{
int n, m; // n is number of vertices and m is number of edges
cin >> n >> m;
vector<int> adj[n + 1];
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v; // u and v are nodes
adj[u].push_back(v);
}
}
// Weighted Graph(Undirected)
int main()
{
int n, m; // n is number of vertices and m is number of edges
cin >> n >> m;
vector<pair<int, int>> adj[n + 1];
for (int i = 0; i < m; i++)
{
int u, v, wt; //wt is the weight of the ith edge
cin >> u >> v >> wt;
adj[u].push_back({v, wt});
adj[v].push_back({u, wt});
}
}
// *******************************************ADJACENCY MATRIX*****************************
int main()
{
int n, m;
cin >> n >> m;
// declare the adjacency matrix
int adj[n + 1][n + 1];
// take edges as input
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
adj[u][v] = 1;
adj[v][u] = 1;
}
} | true |
277ba9e9925e2881e4de5beb0d4c06aa6f1ced98 | C++ | dream-overflow/o3d | /src/image/imgformat.cpp | UTF-8 | 2,313 | 2.546875 | 3 | [] | no_license | /**
* @file imgformat.cpp
* @brief
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2005-10-06
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/image/precompiled.h"
#include "o3d/image/imgformat.h"
using namespace o3d;
// copy constructor
ImgFormat::ImgFormat() :
SmartCounter<ImgFormat>(),
m_state(False),
m_width(0),
m_height(0),
m_data(nullptr),
m_size(0)
{
}
// Copy constructor
ImgFormat::ImgFormat(const ImgFormat &dup) :
SmartCounter<ImgFormat>(dup),
m_state(dup.m_state),
m_width(dup.m_width),
m_height(dup.m_height),
m_data(nullptr),
m_size(dup.m_size)
{
if (dup.m_data && dup.m_state)
{
m_data = new UInt8[dup.m_size];
memcpy(m_data,dup.m_data,m_size);
m_state = True;
}
}
// Virtual destructor. Make a call to Destroy().
ImgFormat::~ImgFormat()
{
destroy();
}
// Detach its data array. The internal data member is then null.
void ImgFormat::detach()
{
m_data = nullptr;
}
// Get picture informations
void ImgFormat::getInfo(
UInt32 &sizeX_,
UInt32 &sizeY_,
UInt8 *&data_,
UInt32 &size_)
{
sizeX_ = m_width;
sizeY_ = m_height;
data_ = m_data;
size_ = m_size;
}
// destroy all
void ImgFormat::destroy()
{
if (m_state)
{
deleteArray(m_data);//m_data = nullptr;
m_size = 0;
m_state = False;
m_width = 0;
m_height = 0;
}
else
{
O3D_ASSERT(m_data == nullptr);
}
}
// is a complex picture
Bool ImgFormat::isComplex() const
{
return False;
}
// is a compressed picture
Bool ImgFormat::isCompressed() const
{
return False;
}
// Complex methods
Bool ImgFormat::isMipMap() const
{
return False;
}
Bool ImgFormat::isCubeMap() const
{
return False;
}
Bool ImgFormat::isVolumeTexture() const
{
return False;
}
UInt32 ImgFormat::getNumMipMapLvl() const
{
return 0;
}
UInt32 ImgFormat::getNumDepthLayer() const
{
return 0;
}
Bool ImgFormat::bindMipMapLvl(UInt32 lvl)
{
if (lvl == 0)
return True;
return False;
}
void ImgFormat::bindCubeMapSide(CubeMapSide side)
{
// Nothing
}
Bool ImgFormat::bindVolumeLayer(UInt32 layer)
{
if (layer == 0)
return True;
return False;
}
UInt32 ImgFormat::getCurrentMipMapLvl() const
{
return 0;
}
UInt32 ImgFormat::getCurrentCubeMapSide() const
{
return 0;
}
UInt32 ImgFormat::getCurrentDepthLayer() const
{
return 0;
}
| true |
0c2dca43f72d0e0ea863a90f54e8558ddf8bfdc2 | C++ | janpawlowskiof/aisd | /Lista 3/zad1/merge_sort.cpp | UTF-8 | 1,596 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <cmath>
#include "ex1.hpp"
void merge_sort (data* d, stats* s, int p, int q) {
int index; //Index of middle element.
if (p < q) {
index = p + (q - p) / 2; //Compute index of middle element.
merge_sort (d, s, p, index); //Resursive merge sort of left half of array.
merge_sort (d, s, index + 1, q); //Recursive merge sort on right half of array.
merge (d, s, p, index, q); //Merge sorted halfs of array (when every part of array has length 1).
}
}
void merge (data* d, stats* s, int p, int index, int q) {
int* array = d -> array;
int* temp = new int[d -> length];
std::string comparator = d -> comparator;
int i = 0; //First element of temp array.
int j = p; //First element of 'left' array.
int k = index + 1; //First element of 'right' array.
while (j <= index && k <= q) { //Compare elements until 'left' or 'right' array isn't empty.
s -> compares++;
if (compare (comparator, array[j], array[k])) { //Take smaller element and put it to temp.
s -> swaps++;
temp[i] = array[j];
j++;
} else {
s -> swaps++;
temp[i] = array[k];
k++;
}
i++;
}
//Put elements to end of sorted array.
while (j <= index) {
temp[i] = array[j];
i++;
j++;
}
while (k <= q) {
temp[i] = array[k];
i++;
k++;
}
i = 0;
for (int l = p; l <= q; l++) {
array[l] = temp[i];
i++;
}
delete [] temp;
}
| true |
e6a901e02a32c46692af6bb2159ddd0e1aa71942 | C++ | snosscire/Block-World | /Source/Engine/Sprite.cpp | UTF-8 | 1,959 | 3.109375 | 3 | [] | no_license | #include "Sprite.h"
#include "Animation.h"
#include "Engine.h"
#include <iostream>
namespace BadEngine {
Sprite::Sprite() :
m_animations(),
m_currentAnimation(NULL),
m_currentAnimationName(NULL),
leftFlipped(false)
{
}
Sprite::~Sprite()
{
map<const string, Animation*>::iterator it;
it = m_animations.begin();
for ( ; it != m_animations.end(); it++) {
Animation* animation = it->second;
delete animation;
}
}
void Sprite::addAnimation(const string& name, Animation* animation) {
m_animations[name] = animation;
}
void Sprite::playAnimation(const string& name)
{
map<const string, Animation*>::iterator it;
it = m_animations.find(name);
if (it != m_animations.end()) {
if (it->second != m_currentAnimation) {
m_currentAnimationName = &it->first;
m_currentAnimation = it->second;
m_currentAnimation->play();
} else {
m_currentAnimation->resume();
}
}
}
void Sprite::stopCurrentAnimation()
{
if (m_currentAnimation) {
m_currentAnimation->stop();
}
}
const string& Sprite::getCurrentAnimationName()
{
return *m_currentAnimationName;
}
void Sprite::update(double deltaTime)
{
if (m_currentAnimation) {
m_currentAnimation->update(deltaTime);
}
}
void Sprite::draw(Engine& engine, int x, int y)
{
if (m_currentAnimation) {
m_currentAnimation->draw(engine, x, y);
}
}
int Sprite::getWidth()
{
if (m_currentAnimation) {
return m_currentAnimation->getWidth();
}
return 0;
}
int Sprite::getHeight() {
if (m_currentAnimation) {
return m_currentAnimation->getHeight();
}
return 0;
}
void Sprite::flipImages(bool flipLeft)
{
if ((!leftFlipped && flipLeft) || (leftFlipped && !flipLeft)) {
leftFlipped = flipLeft;
map<const string, Animation*>::iterator it;
it = m_animations.begin();
for ( ; it != m_animations.end(); it++) {
Animation* animation = it->second;
animation->flipImages();
}
}
}
};
| true |
a034c02c9594097b1be9eac4397b4025b5b1fffb | C++ | yuushimizu/ufo | /ufo/rect.hpp | UTF-8 | 2,018 | 3.390625 | 3 | [] | no_license | #ifndef ufo_rect
#define ufo_rect
#include <iostream>
#include "coord.hpp"
#include "sequence/range.hpp"
namespace ufo {
template <typename T>
class rect final {
public:
constexpr rect(coord<T> origin, coord<T> size) noexcept : origin_(std::move(origin)), size_(std::move(size)) {
}
constexpr explicit rect() noexcept : origin_ {}, size_ {} {
}
coord<T> origin() const {
return origin_;
}
coord<T> size() const {
return size_;
}
constexpr auto opposite_origin() const noexcept {
return coord(origin().x() + size().x(), origin().y() + size().y());
}
template <typename CoordT>
constexpr bool contains(const coord<CoordT> &coord) noexcept {
return coord.x() >= origin().x() && coord.y() >= origin().y() && coord.x() < opposite_origin().x() && coord.y() < opposite_origin().y();
}
constexpr auto range() noexcept {
return ufo::range(origin(), origin() + size());
}
constexpr auto x_range() noexcept {
return ufo::range(origin().x(), origin().x() + size().x());
}
constexpr auto y_range() noexcept {
return ufo::range(origin().y(), origin().y() + size().y());
}
private:
coord<T> origin_;
coord<T> size_;
};
template <typename LHS, typename RHS>
constexpr bool operator==(const rect<LHS> &lhs, const rect<RHS> &rhs) noexcept {
return lhs.origin() == rhs.origin() && lhs.size() == rhs.size();
}
template <typename LHS, typename RHS>
constexpr bool operator!=(const rect<LHS> &lhs, const rect<RHS> &rhs) noexcept {
return !(lhs == rhs);
}
template <typename T>
auto &operator<<(std::ostream &o, const rect<T> &rect) {
return o << "(" << rect.origin() << ", " << rect.size() << ")";
}
}
#endif
| true |
939e6d20974e9a17f63b1f7ba0dc0fd15da4e352 | C++ | xuyunhao/LFS | /flash/flash.h | UTF-8 | 931 | 2.71875 | 3 | [] | no_license | #ifndef LFS_FLASH_FLASH_H_
#define LFS_FLASH_FLASH_H_
#include "util/defs.h"
namespace lfs {
typedef uint32_t FlashSectorNum;
//abstract Flash class
class Flash {
public:
FlashSectorNum nsector(void) const { return this->nsector_; }
uint32_t noctet_sector(void) const { return this->noctet_sector_; }
virtual bool Seek(FlashSectorNum sector) =0;
virtual bool Read(FlashSectorNum sector_count, uint8_t* buf) =0;
virtual bool Write(FlashSectorNum sector_count, const uint8_t* buf) =0;
protected:
Flash(void);
void set_nsector(FlashSectorNum value) { this->nsector_ = value; }
void set_noctet_sector(uint32_t value) { this->noctet_sector_ = value; }
private:
FlashSectorNum nsector_;
uint16_t noctet_sector_;
DISALLOW_COPY_AND_ASSIGN(Flash);
};
inline Flash::Flash(void) {
this->nsector_ = 0;
this->noctet_sector_ = 0;
}
};//namespace lfs
#endif//LFS_FLASH_FLASH_H_
| true |
711bf5f0ea2347eb2a0d91b196aaf47c431efa07 | C++ | cpecoraro18/Game | /src/TextureManager.cpp | UTF-8 | 1,180 | 2.890625 | 3 | [] | no_license | #include "TextureManager.h"
#include "SDL_image.h"
#include <stdio.h>
void TextureManager::LoadTexture(std::string filename, const char* name, SDL_Renderer* renderer) {
const char* charFilename = filename.c_str();
SDL_Surface* tempSurface = IMG_Load(charFilename);
if (tempSurface == NULL) {
printf("Unable to open texture");
exit(1); // call system to stop
}
SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, tempSurface);
if (tex != NULL) {
this->_textures[name] = tex;
}
SDL_FreeSurface(tempSurface);
}
SDL_Texture *TextureManager::GetTexture(const char* name) {
return this->_textures.at(name);
}
void TextureManager::Draw(SDL_Texture* tex, SDL_Rect src, SDL_Rect dest, SDL_Renderer* renderer) {
SDL_RenderCopy(renderer, tex, &src, &dest);
}
void TextureManager::Draw(SDL_Texture* tex, SDL_Rect src, SDL_Rect dest, SDL_Renderer* renderer, double angle) {
SDL_RenderCopyEx(renderer, tex, &src, &dest, angle, NULL, SDL_FLIP_NONE);
}
void TextureManager::DestroyTextures() {
std::map<const char*, SDL_Texture*>::iterator it;
for (it = _textures.begin(); it != _textures.end(); it++)
{
SDL_DestroyTexture(it->second);
}
_textures.clear();
} | true |
21e28aa63fcafd1d0d6c7066245d4ad80c90c512 | C++ | GarvitV957/LeetCode | /longest-palindromic-substring/longest-palindromic-substring.cpp | UTF-8 | 1,038 | 2.875 | 3 | [] | no_license | class Solution {
public:
string ans="";
string solve(string &s, int i, int j){
string temp = "";
if(i==j) return temp+s[i];
if(s[i] == s[j]){
string temp = s[i]+solve(s,i+1,j-1)+s[i];
ans = ans.length()>=temp.length() ? ans:temp;
return temp;
}
else{
return "";
}
}
string longestPalindrome(string s)
{
if (s.empty()) return "";
if (s.size() == 1) return s;
int min_start = 0, max_len = 1;
for (int i = 0; i < s.size();) {
if (s.size() - i <= max_len / 2) break;
int j = i, k = i;
while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters.
i = k+1;
while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand.
int new_len = k - j + 1;
if (new_len > max_len) { min_start = j; max_len = new_len; }
}
return s.substr(min_start, max_len);
}
}; | true |
d5bfb18ce3d7072ca393c8e4205d1f6f51db778f | C++ | wCmJ/Algorithm | /Heap.h | UTF-8 | 1,558 | 3.6875 | 4 | [] | no_license | #pragma once
template<class T>
void Heap_Maximum_Node(T *data, int i, int len) {
int max = i;
if (2 * i + 1 < len && data[2 * i + 1] > data[max]) {
max = 2 * i + 1;
}
if (2 * i + 2 < len && data[2 * i + 2] > data[max]) {
max = 2 * i + 2;
}
if (max != i) {
T tmp = data[max];
data[max] = data[i];
data[i] = tmp;
Heap_Maximum_Node(data, max,len);
}
}
template<class T>
void Heap_Maximum_Construct(T *data, size_t len) {
for (int i = len / 2; i >= 0; i--) {
Heap_Maximum_Node<T>(data, i, len);
}
}
template<class T>
void Heap_Minimum_Node(T *data, int i, int len) {
int min = i;
if (2 * i + 1 < len && data[2 * i + 1] < data[min]) {
min = 2 * i + 1;
}
if (2 * i + 2 < len && data[2 * i + 2] < data[min]) {
min = 2 * i + 2;
}
if (min != i) {
T tmp = data[min];
data[min] = data[i];
data[i] = tmp;
Heap_Minimum_Node(data, min, len);
}
}
template<class T>
void Heap_Minimum_Construct(T *data, size_t len) {
for (int i = len / 2; i >= 0; i--) {
Heap_Minimum_Node<T>(data, i, len);
}
}
template<class T>
void Heap_Ascend_Sort(T *data, int len) {
Heap_Maximum_Construct(data, len);
for (int i = len - 1; i >0;i--) {
T tmp = data[0];
data[0] = data[i];
data[i] = tmp;
Heap_Maximum_Node(data, 0, i);
}
}
template<class T>
void Heap_Descend_Sort(T *data, int len) {
Heap_Minimum_Construct(data, len);
for (int i = len - 1; i > 0; i--) {
T tmp = data[0];
data[0] = data[i];
data[i] = tmp;
Heap_Minimum_Node(data, 0, i);
}
}
//construct heap
//swap the first and the last element
//maintain heap
| true |
ff6216ed80cde232df9dc2840c951b20b97b6509 | C++ | necromaner/C- | /c-primer/Chapter Four/4.1.2/4.2/main.cpp | UTF-8 | 295 | 2.90625 | 3 | [] | no_license | //4.2 根据4.12节中的标,在下述表达式的合理位置添加括号,使得添加括号后运算对象的组合顺序与添加括号前一致。
//(a) *vec.begin() (b) *vec.begin() + 1
//(a) *(vec.begin()) (b) *(vec.begin()) + 1
#include <iostream>
int main() {
return 0;
} | true |
1801a39c5f0bf1fba8e19fc458998af6ff90e0c0 | C++ | D1egood/CompetitiveProgramming | /coj/3800.cpp | UTF-8 | 837 | 2.609375 | 3 | [] | no_license | # include <bits/stdc++.h>
using namespace std;
size_t m = size_t(1e9+7);
size_t fast_exp(size_t b, size_t p)
{
size_t r = size_t(1);
for(size_t i = (size_t(1) << 60); i; i >>= 1)
{
r *= r;
r %= m;
if(p & i){
r *= b;
r %= m;
}
}
return r;
}
size_t sol(size_t b, size_t p)
{
if(p == 0)
return size_t(1);
if(p & 1){
size_t v = sol(b, p / 2);
return (( v * fast_exp(b, p / 2 + 1)) % m + v) % m;
}
return ((sol(b, p - 1) * b) % m + 1) % m;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
size_t n,k;
cin>> n >> k;
size_t r = 0, c = 0;
for(int i = 1; i <= k; ++i){
size_t l;
cin >> l;
if(i & 1)
c += l;
else
r = (r + (l * sol(n, c - 1)) % m) % m;
}
cout << r << endl;
return 0;
}
| true |
9f4112b63b505c6f290014ee71ff5c5794e2b474 | C++ | RiyaMathew-11/hacktoberfest-1 | /STLs/vector_implementation.cpp | UTF-8 | 2,581 | 4.4375 | 4 | [
"MIT"
] | permissive | // Self implementation of
// the Vector Class in C++
#include <bits/stdc++.h>
using namespace std;
class vectorClass {
// arr is the integer pointer
// which stores the address of our vector
int* arr;
// capacity is the total storage
// capacity of the vector
int capacity;
// current is the number of elements
// currently present in the vector
int current;
public:
// Default constructor to initialise
// an initial capacity of 1 element and
// allocating storage using dynamic allocation
vectorClass()
{
arr = new int[1];
capacity = 1;
current = 0;
}
// Function to add an element at the last
void push(int data)
{
// if the number of elements is equal to the capacity,
// that means we don't have space
// to accommodate more elements.
// We need to double the capacity
if (current == capacity) {
int* temp = new int[2 * capacity];
// copying old array elements to new array
for (int i = 0; i < capacity; i++) {
temp[i] = arr[i];
}
// deleting previous array
delete[] arr;
capacity *= 2;
arr = temp;
}
// Inserting data
arr[current] = data;
current++;
}
// function to add element at any index
void push(int data, int index)
{
// if index is equal to capacity then this
// function is same as push defined above
if (index == capacity)
push(data);
else
arr[index] = data;
}
// function to extract element at any index
int get(int index)
{
// if index is within the range
if (index < current)
return arr[index];
}
// function to delete last element
void pop()
{
current--;
}
// function to get size of the vector
int size()
{
return current;
}
// function to get capacity of the vector
int getcapacity()
{
return capacity;
}
// function to print array elements
void print()
{
for (int i = 0; i < current; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
// Driver code
int main()
{
vectorClass v;
v.push(100);
v.push(200);
v.push(300);
v.push(400);
v.push(500);
cout << "Vector size : "
<< v.size() << endl;
cout << "Vector capacity : "
<< v.getcapacity() << endl;
cout << "Vector elements : ";
v.print();
v.push(1000, 1);
cout << "\nAfter updating 1st index"
<< endl;
cout << "Vector elements : ";
v.print();
cout << "Element at 1st index : "
<< v.get(1) << endl;
v.pop();
cout << "\nAfter deleting last element"
<< endl;
cout << "Vector size : "
<< v.size() << endl;
cout << "Vector capacity : "
<< v.getcapacity() << endl;
cout << "Vector elements : ";
v.print();
return 0;
}
| true |
4e4788c4c5f3f995b347dd29be82ffaab383d667 | C++ | ttiimm2214/leetcode | /23_Merge_k_Sorted_Lists/23_M_K_S_L.cpp | UTF-8 | 1,811 | 3.296875 | 3 | [
"MIT"
] | permissive | /*
* Leetcode 23_Merge_k_Sorted_Lists
*
* Compile: g++ 23_M_K_S_L.cpp -o result
* Execute: ./result
*/
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
*/
#include <iostream>
#include <vector>
using namespace std;
struct Listnode {
int val;
Listnode *next;
};
int main(){
//test case 1 -> 4 -> 5
Listnode *head0 = new Listnode;
Listnode *temp = new Listnode;
temp = head0;
head0 -> val = 1;
head0 -> next =NULL;
temp -> next = new Listnode;
temp = temp -> next;
temp -> val = 4;
temp -> next =NULL;
temp -> next = new Listnode;
temp = temp -> next;
temp -> val = 5;
temp -> next =NULL;
//test case 1 -> 3 -> 4
Listnode *head1 = new Listnode;
Listnode *temp1 = new Listnode;
temp1 = head1;
head1 -> val = 1;
head1 -> next =NULL;
temp1 -> next = new Listnode;
temp1 = temp1 -> next;
temp1 -> val = 3;
temp1 -> next =NULL;
temp1 -> next = new Listnode;
temp1 = temp1 -> next;
temp1 -> val = 4;
temp1 -> next =NULL;
//test case 2 -> 6
Listnode *head2 = new Listnode;
Listnode *temp2 = new Listnode;
temp2 = head2;
head2 -> val = 2;
head2 -> next =NULL;
temp2 -> next = new Listnode;
temp2 = temp2 -> next;
temp2 -> val = 6;
temp2 -> next =NULL;
//將test case 推進 vector
vector<Listnode> lists;
lists.push_back(*head0);
lists.push_back(*head1);
lists.push_back(*head2);
//solution
//corner case 當vector沒有list or 只有一個list
//
// Listnode *try1 = &lists[0];
// while (try1 != NULL){
// try1 = try1 -> next;
// }
// print the list
Listnode *print = new Listnode;
print = &lists[0];
while(true){
cout << print -> val << endl;
print = print -> next;
if (print == NULL){
break;
}
}
} | true |
b11bf1d0b36af87a81d551c4761f7e01e0906c1e | C++ | abaran803/DSA-by-Narsimha | /Graph/Topological Sort.cpp | UTF-8 | 1,172 | 3.421875 | 3 | [] | no_license | #include<iostream>
#include<stack>
#include<queue>
#include<vector>
using namespace std;
struct Graph
{
int V;
int E;
vector<int> *Adj;
};
queue<int> q;
vector<int> indegree;
Graph* CreateNewNode()
{
Graph* G = new Graph();
if(!G)
{
cout << "Memory not Allocated" << endl;
return NULL;
}
cin >> G->V >> G->E;
G->Adj = new vector<int>[G->V];
if(!G->Adj)
{
cout << "Memory not Allocated";
return NULL;
}
for(int i=0;i<G->V;i++)
for(int j=0;j<G->V;j++)
G->Adj[i].push_back(0);
int u,v;
for(int i=0;i<G->V;i++)
indegree.push_back(-1);
for(int i=0;i<G->E;i++)
{
cin >> u >> v;
G->Adj[u][v] = 1;
if(indegree[u] == -1)
indegree[u] = 0;
if(indegree[v] == -1)
indegree[v] = 1;
else
indegree[v]++;
}
return G;
}
void Topological(Graph* G)
{
while(1)
{
for(int i=0;i<G->V;i++)
{
if(indegree[i] == 0)
{
indegree[i]--;
q.push(i);
}
}
if(q.empty())
return;
while(!q.empty())
{
int temp = q.front();
q.pop();
cout << temp << " ";
for(int i=0;i<G->V;i++)
if(G->Adj[temp][i] == 1)
indegree[i]--;
}
}
}
int main()
{
Graph* G = CreateNewNode();
Topological(G);
return 0;
} | true |
105912a327d83d62cfdea4ae9342e08906aace21 | C++ | buzyaba/SimEngine | /Tests/src/SmartThingScheduleTest.cpp | UTF-8 | 2,965 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include "gtest/gtest.h"
#include "SimEngine/common.h"
#include "SimEngine/SmartThing.h"
#include "SimEngine/SmartThingSchedule.hpp"
class DummyActuator: public TActuator {
public:
DummyActuator(std::string _name) : TActuator(_name) {}
virtual void SetDataPacket(TDataPacket* packet)
{
for (int i = 0; i < objects.size(); i++)
{
if (objects[i] != nullptr)
{
switch (static_cast<int>(packet->GetData<double>()[i])) {
case 0:
objects[i]->SetProperty({{"Property", 0}}, "Property");
break;
case 1:
objects[i]->SetProperty({{"Property", 1}}, "Property");
break;
case 2:
objects[i]->SetProperty({{"Property", 2}}, "Property");
break;
}
}
}
}
};
class DummySensor: public TSensor {
public:
DummySensor(std::string _name) : TSensor(_name) {}
};
class DummyThing : public TSmartThing {
public:
DummyThing(std::string name) : TSmartThing(name, { new DummySensor("DummySensor") }, { new DummyActuator("DummyActuator") }) {}
TSmartThing* Clone() { return new DummyThing("DummyThing"); };
std::string ClassName() override { return std::string("DummyThing"); }
};
class DummyObject : public TObjectOfObservation {
public:
DummyObject(std::string name) : TObjectOfObservation(name) {
properties.insert(
{"Property", new TProperties({{"Property", 2}}, false, "Property")});
}
};
TEST(SmartThingScheduleTest, Can_Create) {
std::vector<TObjectOfObservation*> objects(15);
std::generate(objects.begin(), objects.end(), [] {static int a = 1; return new DummyObject("DummyObject"+std::to_string(a++));} );
std::vector<TSmartThing*> things(15);
std::generate(things.begin(), things.end(), [&] {
static int a = 1;
auto Thing = new DummyThing("DummyThing"+std::to_string(a));
Thing->AddObject(objects[a-1]);
a++;
return Thing;
} );
ASSERT_NO_THROW(TSmartThingSchedule(things, getPath("/Tests/common/things.xml")));
}
TEST(SmartThingScheduleTest, UpdateThingsProperties) {
std::vector<TObjectOfObservation*> objects(15);
std::generate(objects.begin(), objects.end(), [] {static int a = 1; return new DummyObject("DummyObject"+std::to_string(a++));} );
std::vector<TSmartThing*> things(15);
std::generate(things.begin(), things.end(), [&] {
static int a = 1;
auto Thing = new DummyThing("DummyThing"+std::to_string(a));
Thing->AddObject(objects[a-1]);
a++;
return Thing;
} );
TSmartThingSchedule thingsSchedule(things, getPath("/Tests/common/things.xml"));
thingsSchedule.UpdateThingsProperties(0ull);
ASSERT_DOUBLE_EQ(objects[0]->GetProperty("Property").GetValue("Property"), 0.0);
thingsSchedule.UpdateThingsProperties(500ull);
ASSERT_DOUBLE_EQ(objects[0]->GetProperty("Property").GetValue("Property"), 0.0);
} | true |
6e5baf0b2ae2bdaf4d197a849d7bd3e1fcf06bd6 | C++ | himamsuvavil/NCRworks | /CPP_Assignment1/swap_9/Source.cpp | UTF-8 | 587 | 3.8125 | 4 | [] | no_license | #include<iostream>
using namespace std;
void swap_reference(int &a, int &b)
{
int t = a;
a = b;
b = t;
cout << "after swapping:" << a << " " << b;
}
void swap_value(int a, int b)
{
int t = a;
a = b;
b = t;
cout << "after swapping:" << a << " " << b;
}
int main()
{
int a,b;
cout << "Enter a,b:";
cin >> a >> b;
cout << "Swap numbers by:" << endl << "1.call by reference\n2.call by value\n";
int n;
cin >> n;
switch (n)
{
case 1:swap_reference(a, b);
break;
case 2:swap_value(a, b);
break;
default:cout << "Invalid choice\n";
}
system("pause");
return 0;
}
| true |
a1800e1c21c306bf3bfe22e816ea53fe43c557f7 | C++ | dlswer23/cpp | /C++/함수 템플릿.cpp | WINDOWS-1252 | 402 | 3.328125 | 3 | [] | no_license | #include<iostream>
template <typename T>
T TestFunc(T a) {
std::cout << "Ű a : " << a << std::endl;
return a;
}
int main() {
std::cout << "int \t" << TestFunc(3) << std::endl;
std::cout << "double \t" << TestFunc(3.3) << std::endl;
std::cout << "char \t" << TestFunc('A') << std::endl;
std::cout << "char* \t" << TestFunc("TestString") << std::endl;
return 0;
} | true |
a91cbeac70c6e000e29ef50323ffabdce7a63563 | C++ | bill20509/leetcode-practice | /cpp/array/easy/1752. Check if Array Is Sorted and Rotated.cpp | UTF-8 | 494 | 2.71875 | 3 | [] | no_license | class Solution {
public:
bool check(vector<int>& nums) {
for(int j = 0; j < nums.size(); j++){
bool f = true;
int temp = nums[j];
for(int i = 0; i < nums.size(); i++){
if(temp > nums[(j + i) % nums.size()]){
f = false;
break;
}
temp = nums[(j + i) % nums.size()];
}
if(f) return true;
}
return false;
}
}; | true |
58ceb6418062370fc10c60de173503fcca52dcb9 | C++ | claytongreen/Compiler | /Source/Compiler/loop_node.cpp | UTF-8 | 418 | 2.78125 | 3 | [] | no_license | // Author: Clayton Green (kgreen1@unbc.ca)
//
//
#include "ast_node.h"
LoopNode::LoopNode(StatementNode *statement) {
statements_ = statement;
}
LoopNode::~LoopNode() {
delete statements_;
}
void LoopNode::Accept(ASTNodeVisitor *visitor) {
visitor->Visit(*this);
}
void LoopNode::set_statements(StatementNode *statement) {
statements_ = statement;
}
StatementNode *LoopNode::statements() const {
return statements_;
} | true |
2ac952f55edb175ff5a88078360325f8e1edbcb8 | C++ | rgrig/rgrig-hp | /static/programs/spoj/ascirc.cpp | UTF-8 | 1,965 | 2.640625 | 3 | [] | no_license | #define verbose 0 \
#define foreach(i,c) for(typeof((c) .begin() ) i= (c) .begin() ;i!=(c) .end() ;++i) \
#define in(e,c) ((c) .find(e) !=(c) .end() ) \
/*2:*/
#line 37 "./ascirc.w"
#include <map>
#include <set>
#include <queue>
#include <stdio.h>
#include <assert.h>
using namespace std;
/*7:*/
#line 113 "./ascirc.w"
struct Node{
char op;
Node*left;
Node*right;
Node(char op,Node*left,Node*right)
:op(op),left(left),right(right){}
bool operator<(const Node&o)const{
if(op!=o.op)return op<o.op;
if(left!=o.left)return left<o.left;
return right<o.right;
}
};
map<Node,Node*> hashcons;
Node*mk_node(char op,Node*left,Node*right){
Node*r= new Node(op,left,right);
map<Node,Node*> ::iterator it= hashcons.find(*r);
if(it!=hashcons.end()){
delete r;
return it->second;
}
return hashcons[*r]= r;
}
/*:7*/
#line 46 "./ascirc.w"
int main(){
/*3:*/
#line 59 "./ascirc.w"
int tests;
scanf("%d",&tests);
while(tests--){
foreach(n,hashcons)delete n->second;
hashcons.clear();
Node*out[256];
for(char c= 'a';c<='z';++c)out[c]= mk_node(c,NULL,NULL);
int assignments;
scanf("%d",&assignments);
while(assignments--)/*4:*/
#line 76 "./ascirc.w"
{
char asg[5];
scanf("%s",asg);
out[asg[3]]= mk_node(asg[0],out[asg[1]],out[asg[2]]);
}
/*:4*/
#line 69 "./ascirc.w"
;
/*5:*/
#line 86 "./ascirc.w"
set<Node*> internal_nodes;
queue<Node*> q;
for(char c= 'a';c<='z';++c)if(out[c]->left!=NULL){
if(!in(out[c],internal_nodes))
q.push(out[c]);
internal_nodes.insert(out[c]);
}
while(!q.empty()){
Node*n= q.front();q.pop();
Node*nn= n->left;
/*6:*/
#line 104 "./ascirc.w"
if(nn->left!=NULL&&!in(nn,internal_nodes)){
q.push(nn);
internal_nodes.insert(nn);
}
/*:6*/
#line 97 "./ascirc.w"
;
nn= n->right;
/*6:*/
#line 104 "./ascirc.w"
if(nn->left!=NULL&&!in(nn,internal_nodes)){
q.push(nn);
internal_nodes.insert(nn);
}
/*:6*/
#line 99 "./ascirc.w"
;
}
printf("%d\n",internal_nodes.size());
/*:5*/
#line 70 "./ascirc.w"
;
}
/*:3*/
#line 49 "./ascirc.w"
;
}
/*:2*/
| true |
e98b600122fca8ff469aabd23edffa81200dfe3c | C++ | chiha8888/Code | /Confusing Date Format.cpp | UTF-8 | 749 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int A[3];
int answer;
int D[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int main(){
int n;
char c;
scanf("%d",&n);
for(int i=1;i<=n;i++){
answer=0;
scanf("%d-%d-%d",&A[0],&A[1],&A[2]);
if(A[0]==4&&A[1]==5&&A[2]==1){
printf("Case #%d: %d\n",i,1);
continue;
}
sort(A,A+3);
do{
if(A[1]<1||A[1]>12)
continue;
if(A[1]==2)
{
if(A[0]%4==0&&A[0]!=0) //leap year
{
if(A[2]>=1&&A[2]<=29)
answer++;
}
else //NOT LEAP YEAR
{
if(A[2]>=1&&A[2]<=28)
answer++;
}
continue;
}
else if(A[2]>=1&&A[2]<=D[A[1]])
answer++;
}while(next_permutation(A,A+3));
printf("Case #%d: %d\n",i,answer);
}
return 0;
}
| true |
9c159f1df8fe360f6c7e2a1b8f20075de92c2c2e | C++ | lmh760008522/ProgrammingExercises | /王道/159-1.cpp | UTF-8 | 192 | 2.625 | 3 | [] | no_license | #include<cstdio>
int main(){
int n;
scanf("%d",&n);
int a[21];
a[0]=0;
a[1]=1;
a[2]=2;
for(int i=3;i<=n;i++){
a[i]=a[i-1]+a[i-2];
}
printf("%d\n",a[n]);
return 0;
}
| true |
69a11108ad6ef8c0b928623a2ab4521d9077658a | C++ | Qrisno/UniProjects-CPP | /RestaurantManagment/Base.h | UTF-8 | 888 | 3.203125 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
class Employee {
protected:
int employee_id;
char employee_position;
int employee_salary;
int emp_profit_share;
string employee_name;
public:
int getEmpID();
char getPosition();
int getWage();
int getProfShare();
string getEmpName();
void dispEmp();
virtual double calculate_salary(double bonusAmount) = 0;
};
class Owner : public Employee {
public:
Owner(string name);
double calculate_salary(double bonusAmount);
void dispEmp();
};
class Chef : public Employee {
private:
string cuisineType;
public:
Chef(string name, string cuisine);
double calculate_salary(double bonusAmount);
string getCuisineType();
void dispEmp();
};
class Waiter : public Employee {
private:
int expYears;
public:
Waiter(string name, int years);
double calculate_salary(double bonusAmount);
int getExpYears();
void dispEmp();
}; | true |
9cd7f6a0caadd057fa9a43ec9a7d37441c828f0b | C++ | qianfei11/ACEveryday | /Data Structure/Double Linked List.cpp | GB18030 | 1,812 | 3.4375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
typedef struct doublelinked
{
int val;
struct doublelinked *pre;
struct doublelinked *next;
}db, *pdb;
int size = 0;
pdb init()
{
int n;
pdb head, p, q;
scanf("%d", &n);
size = n;
head = (pdb)malloc(sizeof(db));
if(head == NULL)
{
printf("Memory allocation failed!\n");
exit(0);
}
head->val = 0;
head->next = NULL;
head->pre = NULL;
q = head;
for(int i = 0; i < n; i++)
{
p = (pdb)malloc(sizeof(db));
if(p == NULL)
{
printf("Memory allocation failed!\n");
exit(0);
}
scanf("%d", &p->val);
q->next = p;
p->pre = q;
p->next = NULL;
q = p;
}
head->pre = p;
q->next = head;
return head;
}
int insert(pdb head, int pos, int x)//ǰ
{
if(pos < 0 || pos > size)
{
printf("Your pos is wrong!\n");
return 0;
}
pdb t = head;
for(int i = 0; i < pos; i++)
t = t->next;
pdb p = (pdb)malloc(sizeof(db));
p->val = x;
p->pre = t->pre;
p->next = t;
t->pre->next = p;//ԭt֮ǰĽڵĺָpһɵ˳
t->pre = p;//ʹtǰָpһɵ˳
printf("Successful insert %d at pos %d!\n", x, pos);
size++;
return 1;
}
int del(pdb head, int pos, int *x)
{
if(pos < 0 || pos > size)
{
printf("Your pos is wrong!\n");
return 0;
}
pdb p = head;
for(int i = 0; i < pos; i++)
p = p->next;
p->pre->next = p->next;
p->next->pre = p->pre;
printf("%d has been deleted at pos %d successfully!\n", p->val, pos);
free(p);
size--;
return 1;
}
void print(pdb head)
{
pdb p;
p = head->next;
while(p != head)
{
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
int main()
{
// pdb head;
// head = init();
// print(head);
//
// int *x;
// del(head, 3, x);
// print(head);
//
// insert(head, 2, 100);
// print(head);
return 0;
} | true |