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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
69cc4d5e655fa012668db8c61cf89b30462159ae | C++ | myumoon/bishrpg | /bishrpg/Source/bishrpg/Battle/BattleCellSelector.cpp | UTF-8 | 20,485 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | // Copyright © 2018 nekoatsume_atsuko. All rights reserved.
#include "BattleCellSelector.h"
#include "BattleData.h"
#include "BattleBoardUtil.h"
#include "BattleBoardDef.h"
#include "BattleSystem.h"
#include "bishrpg.h"
namespace {
class FilterBase {
public:
FilterBase(const FBattleParty* party) : TargetParty(party)
{
}
virtual ~FilterBase() = default;
bool operator()(int32 pos) const
{
if(!TargetParty) {
return false;
}
if(!UBattleBoardUtil::IsValidCellNo(pos)) {
return false;
}
if(!TargetParty->ExistsPos(pos)) {
return false;
}
return FilterCell(BattleCell(pos), *TargetParty);
}
protected:
virtual bool FilterCell(const BattleCell& cell, const FBattleParty& party) const = 0;
private:
const FBattleParty* TargetParty = nullptr;
};
// 全セルをフィルタリング
class FilterAll : public FilterBase {
using FilterBase::FilterBase;
protected:
bool FilterCell(const BattleCell& cell, const FBattleParty& party) const override
{
return true;
}
};
// 生きているオブジェクトをフィルタリング
class FilterAlive : public FilterBase {
using FilterBase::FilterBase;
protected:
bool FilterCell(const BattleCell& cell, const FBattleParty& party) const override
{
return party.GetCharacterByCell(cell)->IsAlive();
}
};
struct SortCompNearDistance {
BattleCell BasePos = 0;
SortCompNearDistance(int32 actorPos) : BasePos(actorPos)
{
}
bool operator()(const BattleCell& lhs, const BattleCell& rhs) const
{
if(rhs.GetRow() < lhs.GetRow()) {
return true;
}
const int32 facedColL = UBattleBoardUtil::GetFacedCol(lhs.GetIndex());
const int32 facedColR = UBattleBoardUtil::GetFacedCol(rhs.GetIndex());
const int32 distL = FMath::Abs(UBattleBoardUtil::GetCol(BasePos.GetIndex()) - facedColL);
const int32 distR = FMath::Abs(UBattleBoardUtil::GetCol(BasePos.GetIndex()) - facedColR);
return (distL < distR);
}
};
struct SortCompFarDistance {
SortCompNearDistance NearDistComp;
SortCompFarDistance(int32 actorPos) : NearDistComp(actorPos)
{
}
bool operator()(const BattleCell lhs, const BattleCell rhs) const
{
return NearDistComp(lhs, rhs);
}
};
struct SortCompContainer {
std::function<bool(BattleCell, BattleCell)> Comp;
SortCompContainer(std::function<bool(BattleCell, BattleCell)> comp) {
Comp = comp;
}
bool operator()(const BattleCell lhs, const BattleCell rhs) const
{
return Comp(lhs, rhs);
}
};
}
/*
BattleCellSelector::BattleCellSelector(const FBattleSystem* battleSystem)
{
Initialize(battleSystem);
}
*/
BattleCellSelector::BattleCellSelector(const FBattleParty* party)
{
Initialize(party);
}
void BattleCellSelector::Initialize(const FBattleParty* party)
{
//SelectedCells.Init(false, UBattleBoardUtil::CELL_NUM);
ResultCells.Reserve(Battle::Def::MAX_BOARD_CELLS);
SelectedParty = party;
}
// 位置追加
void BattleCellSelector::AddPos(const BattleCell& posIndex)
{
if(posIndex.IsValid()) {
if(!ResultCells.Contains(posIndex)) {
ResultCells.Add(posIndex);
}
}
}
// ----- セル選択 -----
void BattleCellSelector::SelectTarget(BattleCell actorPos, EBattleSelectMethod selectMethod)
{
SelectFunc selectMethodFunc[] = {
&BattleCellSelector::SelectDummy,
&BattleCellSelector::SelectTop1,
&BattleCellSelector::SelectTop2,
&BattleCellSelector::SelectTop3,
&BattleCellSelector::SelectTop4,
&BattleCellSelector::SelectTop5,
&BattleCellSelector::SelectTop6,
&BattleCellSelector::SelectFacedTop1,
&BattleCellSelector::SelectAhead1,
&BattleCellSelector::SelectAhead4,
&BattleCellSelector::SelectAttackTop1,
&BattleCellSelector::SelectDeffenceTop1,
&BattleCellSelector::SelectRockTop1,
&BattleCellSelector::SelectRockBack1,
&BattleCellSelector::SelectSingTop1,
&BattleCellSelector::SelectSingBack1,
&BattleCellSelector::SelectHurmorTop1,
&BattleCellSelector::SelectHurmorBack1,
&BattleCellSelector::SelectCell_0_Faced,
&BattleCellSelector::SelectCell_0_Right,
&BattleCellSelector::SelectCell_0_Center,
&BattleCellSelector::SelectCell_0_Left,
&BattleCellSelector::SelectCell_1_Right,
&BattleCellSelector::SelectCell_1_Center,
&BattleCellSelector::SelectCell_1_Left,
&BattleCellSelector::SelectCell_2_Right,
&BattleCellSelector::SelectCell_2_Center,
&BattleCellSelector::SelectCell_2_Left,
&BattleCellSelector::SelectCell_3_Right,
&BattleCellSelector::SelectCell_3_Center,
&BattleCellSelector::SelectCell_3_Left,
&BattleCellSelector::SelectAllCells,
&BattleCellSelector::SelectRandom1,
&BattleCellSelector::SelectRandom2,
&BattleCellSelector::SelectRandom3,
&BattleCellSelector::SelectRandom4,
&BattleCellSelector::SelectRandom5,
&BattleCellSelector::SelectRandom6,
&BattleCellSelector::SelectRandom7,
&BattleCellSelector::SelectRandom8,
&BattleCellSelector::SelectRandom9,
&BattleCellSelector::SelectRandom10,
&BattleCellSelector::SelectRandom11,
&BattleCellSelector::SelectRandom12,
&BattleCellSelector::SelectMyself_P,
&BattleCellSelector::SelectFront1_P,
&BattleCellSelector::SelectTop1_P,
&BattleCellSelector::SelectBack1_P,
&BattleCellSelector::SelectAll_P,
};
static_assert(UE_ARRAY_COUNT(selectMethodFunc) == static_cast<int32>(EBattleSelectMethod::Max), "Invalid array size : selectMethodFunc");
const int32 selectMethodIndex = static_cast<int32>(selectMethod);
(this->*selectMethodFunc[selectMethodIndex])(actorPos.GetIndex());
// 選択済みセルとして記憶して拡張時に使用する
SelectedCells = ResultCells;
}
void BattleCellSelector::SortResult(std::function<bool(BattleCell, BattleCell)> posComp)
{
if(posComp != nullptr) {
ResultCells.Sort(SortCompContainer(posComp));
/*
SelectedCells.Init(false, Battle:Def::MAX_BOARD_CELLS);
for(const auto& cell : ResultCells) {
if(cell.IsValid()) {
SelectedCells[cell.GetIndex()] = true;
}
}
*/
}
}
void BattleCellSelector::FilterResult(std::function<bool(int32)> posFilter)
{
for(int i = 0; i < Battle::Def::MAX_BOARD_CELLS; ++i) {
if(posFilter(i)) {
AddPos(BattleCell(i));
}
}
}
void BattleCellSelector::ShurinkResultTo(int32 size)
{
if((0 <= size) && (size < ResultCells.Num())) {
ResultCells.SetNum(size, false);
}
}
void BattleCellSelector::SelectTop(int32 actorPos, int32 index)
{
FilterResult(FilterAlive(SelectedParty));
SortResult(SortCompNearDistance(actorPos));
if(ResultCells.Num() == 0) {
return;
}
const int32 selectedIndex = FMath::Clamp(index, 0, ResultCells.Num() - 1);
ensure(0 <= selectedIndex && selectedIndex < ResultCells.Num());
const BattleCell selectedCell = ResultCells[selectedIndex];
ResultCells.SetNum(1, false);
ResultCells[0] = selectedCell;
}
void BattleCellSelector::SelectTop1(int32 actorPos)
{
SelectTop(actorPos, 0);
}
void BattleCellSelector::SelectTop2(int32 actorPos)
{
SelectTop(actorPos, 1);
}
void BattleCellSelector::SelectTop3(int32 actorPos)
{
SelectTop(actorPos, 2);
}
void BattleCellSelector::SelectTop4(int32 actorPos)
{
SelectTop(actorPos, 3);
}
void BattleCellSelector::SelectTop5(int32 actorPos)
{
SelectTop(actorPos, 4);
}
void BattleCellSelector::SelectTop6(int32 actorPos)
{
SelectTop(actorPos, 5);
}
void BattleCellSelector::SelectFacedTop1(int32 actorPos)
{
FilterResult([=](int32 pos) { return UBattleBoardUtil::GetCol(pos) == UBattleBoardUtil::GetFacedCol(actorPos);});
SortResult(SortCompNearDistance(actorPos));
ShurinkResultTo(1);
}
void BattleCellSelector::SelectAhead1(int32 actorPos)
{
FilterResult([=](int32 pos) { return UBattleBoardUtil::GetCol(pos) == UBattleBoardUtil::GetFacedCol(actorPos);});
SortResult(SortCompNearDistance(actorPos));
ShurinkResultTo(1);
}
void BattleCellSelector::SelectAhead4(int32 actorPos)
{
FilterResult([=](int32 pos) { return UBattleBoardUtil::GetCol(pos) == UBattleBoardUtil::GetFacedCol(actorPos);});
SortResult(SortCompFarDistance(actorPos));
ShurinkResultTo(1);
}
void BattleCellSelector::SelectAttackTop1(int32 actorPos)
{
FilterResult(FilterAlive(SelectedParty));
SortResult([&](BattleCell lhs, BattleCell rhs) {
const auto* charL = SelectedParty->GetCharacterByPos(lhs.GetIndex());
const auto* charR = SelectedParty->GetCharacterByPos(rhs.GetIndex());
return (charL->Attack < charR->Attack);
});
ShurinkResultTo(1);
}
void BattleCellSelector::SelectDeffenceTop1(int32 actorPos)
{
FilterResult(FilterAlive(SelectedParty));
SortResult([&](BattleCell lhs, BattleCell rhs) {
const auto* charL = SelectedParty->GetCharacterByPos(lhs.GetIndex());
const auto* charR = SelectedParty->GetCharacterByPos(rhs.GetIndex());
return (charL->Deffence < charR->Deffence);
});
ShurinkResultTo(1);
}
void BattleCellSelector::SelectType(EBattleStyle style, int32 actorPos, bool top)
{
FilterResult([=](int32 pos) {
return (SelectedParty->GetCharacterByPos(pos)->Style == style);
});
if(top) {
SortResult(SortCompNearDistance(actorPos));
}
else {
SortResult(SortCompFarDistance(actorPos));
}
ShurinkResultTo(1);
}
void BattleCellSelector::SelectRockTop1(int32 actorPos)
{
SelectType(EBattleStyle::Rock, actorPos, true);
}
void BattleCellSelector::SelectRockBack1(int32 actorPos)
{
SelectType(EBattleStyle::Rock, actorPos, false);
}
void BattleCellSelector::SelectSingTop1(int32 actorPos)
{
SelectType(EBattleStyle::Sing, actorPos, true);
}
void BattleCellSelector::SelectSingBack1(int32 actorPos)
{
SelectType(EBattleStyle::Sing, actorPos, false);
}
void BattleCellSelector::SelectHurmorTop1(int32 actorPos)
{
SelectType(EBattleStyle::Humor, actorPos, true);
}
void BattleCellSelector::SelectHurmorBack1(int32 actorPos)
{
SelectType(EBattleStyle::Humor, actorPos, false);
}
void BattleCellSelector::SelectCellFaced(int32 actorPos, int32 row)
{
FilterResult([=](int32 pos) {
bool valid = (UBattleBoardUtil::GetCol(pos) == UBattleBoardUtil::GetFacedCol(actorPos));
valid &= (UBattleBoardUtil::GetRow(pos) == row);
return valid;
});
}
void BattleCellSelector::SelectCell(int32 row, int32 col)
{
ResultCells.Reset();
ResultCells.Add(BattleCell(row, col));
}
void BattleCellSelector::SelectCell_0_Faced(int32 actorPos)
{
SelectCellFaced(actorPos, 0);
}
void BattleCellSelector::SelectCell_0_Right(int32 actorPos)
{
SelectCell(0, 2);
}
void BattleCellSelector::SelectCell_0_Center(int32 actorPos)
{
SelectCell(0, 1);
}
void BattleCellSelector::SelectCell_0_Left(int32 actorPos)
{
SelectCell(0, 0);
}
void BattleCellSelector::SelectCell_1_Right(int32 actorPos)
{
SelectCell(1, 2);
}
void BattleCellSelector::SelectCell_1_Center(int32 actorPos)
{
SelectCell(1, 1);
}
void BattleCellSelector::SelectCell_1_Left(int32 actorPos)
{
SelectCell(1, 0);
}
void BattleCellSelector::SelectCell_2_Right(int32 actorPos)
{
SelectCell(2, 2);
}
void BattleCellSelector::SelectCell_2_Center(int32 actorPos)
{
SelectCell(2, 1);
}
void BattleCellSelector::SelectCell_2_Left(int32 actorPos)
{
SelectCell(2, 0);
}
void BattleCellSelector::SelectCell_3_Right(int32 actorPos)
{
SelectCell(3, 2);
}
void BattleCellSelector::SelectCell_3_Center(int32 actorPos)
{
SelectCell(3, 1);
}
void BattleCellSelector::SelectCell_3_Left(int32 actorPos)
{
SelectCell(3, 0);
}
void BattleCellSelector::SelectAllCells(int32 actorPos)
{
for(int32 i = 0; i < Battle::Def::MAX_BOARD_CELLS; ++i) {
ResultCells.Add(BattleCell(i));
}
}
void BattleCellSelector::SelectRandom(int32 selectNum)
{
TArray<int32> cellList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
for(int32 i = 0; i < selectNum && 0 < cellList.Num(); ++i) {
const int32 selectedIdx = UBattleSystem::GetRandStream().RandHelper(cellList.Num() - 1);
const int32 selectedCell = cellList[selectedIdx];
cellList.RemoveAt(selectedIdx);
AddPos(BattleCell(selectedCell));
}
}
void BattleCellSelector::SelectRandom1(int32 actorPos)
{
SelectRandom(1);
}
void BattleCellSelector::SelectRandom2(int32 actorPos)
{
SelectRandom(2);
}
void BattleCellSelector::SelectRandom3(int32 actorPos)
{
SelectRandom(3);
}
void BattleCellSelector::SelectRandom4(int32 actorPos)
{
SelectRandom(4);
}
void BattleCellSelector::SelectRandom5(int32 actorPos)
{
SelectRandom(5);
}
void BattleCellSelector::SelectRandom6(int32 actorPos)
{
SelectRandom(6);
}
void BattleCellSelector::SelectRandom7(int32 actorPos)
{
SelectRandom(7);
}
void BattleCellSelector::SelectRandom8(int32 actorPos)
{
SelectRandom(8);
}
void BattleCellSelector::SelectRandom9(int32 actorPos)
{
SelectRandom(9);
}
void BattleCellSelector::SelectRandom10(int32 actorPos)
{
SelectRandom(10);
}
void BattleCellSelector::SelectRandom11(int32 actorPos)
{
SelectRandom(11);
}
void BattleCellSelector::SelectRandom12(int32 actorPos)
{
SelectRandom(12);
}
void BattleCellSelector::SelectMyself_P(int32 actorPos)
{
GAME_ERROR("未実装 : SelectMyself_P");
}
void BattleCellSelector::SelectFront1_P(int32 actorPos)
{
GAME_ERROR("未実装 : SelectFront1_P");
}
void BattleCellSelector::SelectTop1_P(int32 actorPos)
{
GAME_ERROR("未実装 : SelectTop1_P");
}
void BattleCellSelector::SelectBack1_P(int32 actorPos)
{
GAME_ERROR("未実装 : SelectBack1_P");
}
void BattleCellSelector::SelectAll_P(int32 actorPos)
{
GAME_ERROR("未実装 : SelectAll_P");
}
// ----- セル拡張 -----
void BattleCellSelector::ExpandCell(EBattleSelectRange range)
{
RangeFunc rangeFuncTbl[] = {
&BattleCellSelector::ExpandRangeSingle,
&BattleCellSelector::ExpandRangeCol,
&BattleCellSelector::ExpandRangeRow,
&BattleCellSelector::ExpandRangeSide,
&BattleCellSelector::ExpandRangeFrontBack,
&BattleCellSelector::ExpandRangeAroundPlus4,
&BattleCellSelector::ExpandRangeAroundCross4,
&BattleCellSelector::ExpandRangeAround9,
&BattleCellSelector::ExpandRangeBack1,
&BattleCellSelector::ExpandRangeBack2,
&BattleCellSelector::ExpandRangeBack3,
&BattleCellSelector::ExpandRangeBack4,
};
static_assert(UE_ARRAY_COUNT(rangeFuncTbl) == static_cast<int32>(EBattleSelectRange::Max), "Invalid array size : rangeFuncTbl");
const int32 rangeFuncIndex = (int)range;
ensure(0 <= rangeFuncIndex && range < EBattleSelectRange::Max);
(this->*rangeFuncTbl[rangeFuncIndex])();
}
// 範囲選択
void BattleCellSelector::ExpandRangeSingle_Based(const BattleCell& basePos)
{
// そのまま返す
AddPos(basePos);
}
// 縦方向選択
void BattleCellSelector::ExpandRangeCol_Based(const BattleCell& basePos)
{
const int32 col = UBattleBoardUtil::GetCol(basePos.GetIndex());
//int32 base = col;
//AddPos(BattleCell(base));
for(int32 i = 0; i < UBattleBoardUtil::GetBoardRow(); ++i) {
AddPos(BattleCell(i, col));
//const int32 nextPos = UBattleBoardUtil::GetPosForward(base);
//if(base != nextPos) {
// AddPos(BattleCell(nextPos));
// base = nextPos;
//}
}
}
// 横方向選択
void BattleCellSelector::ExpandRangeRow_Based(const BattleCell& basePos)
{
const int32 row = UBattleBoardUtil::GetRow(basePos.GetIndex());
//int32 base = row;
//AddPos(BattleCell(base));
for(int32 i = 0; i < UBattleBoardUtil::GetBoardCol(); ++i) {
AddPos(BattleCell(row, i));
//const int32 nextPos = UBattleBoardUtil::GetPosRight(base);
//if(base != nextPos) {
// AddPos(nextPos);
// base = nextPos;
//}
}
}
// 左右選択
void BattleCellSelector::ExpandRangeSide_Based(const BattleCell& basePos)
{
AddPos(BattleCell(basePos.GetRow(), basePos.GetCol() + 1));
AddPos(BattleCell(basePos.GetRow(), basePos.GetCol() - 1));
#if 0
const int32 left = UBattleBoardUtil::GetPosLeft(basePos.GetIndex());
const int32 right = UBattleBoardUtil::GetPosRight(basePos.GetIndex());
//AddPos(basePos);
if(left != basePos.GetIndex()) {
AddPos(left);
}
if(right != basePos.GetIndex()) {
AddPos(right);
}
#endif
}
// 上下選択
void BattleCellSelector::ExpandRangeFrontBack_Based(const BattleCell& basePos)
{
AddPos(BattleCell(basePos.GetRow() + 1, basePos.GetCol()));
AddPos(BattleCell(basePos.GetRow() - 1, basePos.GetCol()));
#if 0
const int32 forward = UBattleBoardUtil::GetPosForward(basePos.GetIndex());
const int32 back = UBattleBoardUtil::GetPosBack(basePos.GetIndex());
//AddPos(basePos);
if(forward != basePos.GetIndex()) {
AddPos(forward);
}
if(back != basePos.GetIndex()) {
AddPos(back);
}
#endif
}
// 上下左右選択
void BattleCellSelector::ExpandRangeAroundPlus4_Based(const BattleCell& basePos)
{
ExpandRangeSide_Based(basePos);
ExpandRangeFrontBack_Based(basePos);
}
// 斜め4方向選択
void BattleCellSelector::ExpandRangeAroundCross4_Based(const BattleCell& basePos)
{
AddPos(BattleCell(basePos.GetRow() + 1, basePos.GetCol() + 1));
AddPos(BattleCell(basePos.GetRow() + 1, basePos.GetCol() - 1));
AddPos(BattleCell(basePos.GetRow() - 1, basePos.GetCol() + 1));
AddPos(BattleCell(basePos.GetRow() - 1, basePos.GetCol() - 1));
#if 0
auto addPosOf = [&](bool left, bool forward) {
const int32 sidePos = left ? UBattleBoardUtil::GetPosLeft(basePos.GetIndex()) : UBattleBoardUtil::GetPosRight(basePos.GetIndex());
if(sidePos == basePos.GetIndex()) {
return;
}
const int32 finalPos = left ? UBattleBoardUtil::GetPosLeft(sidePos) : UBattleBoardUtil::GetPosRight(sidePos);
if(finalPos == sidePos) {
return;
}
AddPos(finalPos);
};
addPosOf(true, true);
addPosOf(true, false);
addPosOf(false, true);
addPosOf(false, false);
#endif
}
// 周囲選択
void BattleCellSelector::ExpandRangeAround9_Based(const BattleCell& basePos)
{
ExpandRangeAroundPlus4_Based(basePos);
ExpandRangeAroundCross4_Based(basePos);
}
// 後ろ選択
void BattleCellSelector::ExpandRangeBack_Based(const BattleCell& basePos, int32 count)
{
int32 base = basePos.GetIndex();
int32 back = 0;
for(int32 i = 0; i < count; ++i) {
back = UBattleBoardUtil::GetPosBack(base);
if(back == base) {
return;
}
AddPos(back);
base = back;
}
}
//----- 複数選択 -----
void BattleCellSelector::ForeachSelectedCells(TFunction<void(const BattleCell&)> expandFunc)
{
TArray<BattleCell> selectedCells = SelectedCells;
for(const auto& cell : selectedCells) {
expandFunc(cell);
}
}
void BattleCellSelector::ExpandRangeSingle()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeSingle_Based(cell);
});
}
void BattleCellSelector::ExpandRangeCol()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeCol_Based(cell);
});
}
void BattleCellSelector::ExpandRangeRow()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeRow_Based(cell);
});
}
void BattleCellSelector::ExpandRangeSide()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeSide_Based(cell);
});
}
void BattleCellSelector::ExpandRangeFrontBack()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeFrontBack_Based(cell);
});
}
void BattleCellSelector::ExpandRangeAroundPlus4()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeAroundPlus4_Based(cell);
});
}
void BattleCellSelector::ExpandRangeAroundCross4()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeAroundCross4_Based(cell);
});
}
void BattleCellSelector::ExpandRangeAround9()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeAround9_Based(cell);
});
}
void BattleCellSelector::ExpandRangeBack1()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeBack_Based(cell, 1);
});
}
void BattleCellSelector::ExpandRangeBack2()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeBack_Based(cell, 2);
});
}
void BattleCellSelector::ExpandRangeBack3()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeBack_Based(cell, 3);
});
}
void BattleCellSelector::ExpandRangeBack4()
{
ForeachSelectedCells([this](const BattleCell& cell) {
ExpandRangeBack_Based(cell, 4);
});
}
| true |
9bfb728563e541793b121659d88b728c9479df93 | C++ | hophacker/algorithm_coding | /POJ/3094/6942148_AC_0MS_196K.cpp | UTF-8 | 355 | 3 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
using namespace std;
inline int cton(char c)
{
if (c == ' ') return 0;
else return c - 'A' + 1;
}
int main()
{
//freopen("in.txt", "r", stdin);
string s;
while (getline(cin, s), s != "#")
{
int t = 0;
for (int i = 0; i < s.length(); i++)
t += (i+1)*cton(s[i]);
cout << t << endl;
}
}
| true |
cb58e7145630ae2a590ad929b5698c6f2c85dd0d | C++ | Nikhilbhateja22/Love-Babbar-450 | /02_matrix/10_common_ele_in_all_rows.cpp | UTF-8 | 881 | 3.578125 | 4 | [] | no_license | /*
link: https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/
*/
// ----------------------------------------------------------------------------------------------------------------------- //
void common_ele(int mat[M][N], int n, int m) {
map<int, int> mp;
// store 1st row in map with 1 occurence
for (int j = 0;j < m;j++) {
mp[mat[0][j]] = 1;
}
// for every row
for (int i = 1;i < n;i++) {
for (int j = 0;j < m;j++) {
// if the count of ele. is i (means till now it is present in every row) then update with current row count.
if (mp[mat[i][j]] == i) {
mp[mat[i][j]] = i + 1;
}
// if it is last row and count of the current ele. is n then print it.
if (i == n - 1 && mp[mat[i][j]] == n) cout << mat[i][j] << " ";
}
}
} | true |
c0a7d6fb03665ab8b4fcde03e5a156f5e1c0ae4b | C++ | KangboLu/Data-Structure-and-Algorithms | /Algorithms Techniques/1. Sorting and Selection/quick-sort/quickSortHoare.cpp | UTF-8 | 1,389 | 4.3125 | 4 | [] | no_license | // Hoare partition scheme Quick Sort
#include <iostream>
#include <vector>
using namespace std;
// swap function
void swap(int* num1, int* num2) {
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}
// Lomuto partition scheme
int partition(vector<int>& array, int left, int right) {
int pivot = array[(left+right)/2]; // choose rightmost element for comparison
// swap elements < pivot with current element in a loop
while (left <= right) {
while (array[left] < pivot) left++; // left element should be on the right
while (array[right] > pivot) right--; // right element should be on the left
// swap elements and move left and right indices
if (left <= right)
swap(array[left++], array[right--]);
}
return left;
}
// divide the array and sort it
void quickSort(vector<int>& array, int left, int right) {
if (left < right) {
int pivot = partition(array, left, right);
quickSort(array, left, pivot-1);
quickSort(array, pivot+1, right);
}
}
int main() {
cout << "Hoare partition scheme------\n";
cout << "Quick sort O(nlogn) algorithm\n";
vector<int> array{5,4,3,2,1};
cout << "Before sorting: ";
for (auto num: array)
cout << num << " ";
cout << endl;
// run quicksort algorithm
quickSort(array, 0, array.size()-1);
cout << "After sorting: ";
for (auto num: array)
cout << num << " ";
cout << endl;
} | true |
086a793b85091ab1fec6456695c2451befffa403 | C++ | yuchen-ecnu/VTree | /compator/road/bound.cc | UTF-8 | 1,757 | 2.921875 | 3 | [
"MIT"
] | permissive | /* ----------------------------------------------------------------------------
Author: Ken C. K. Lee
Email: cklee@cse.psu.edu
Web: http://www.cse.psu.edu/~cklee
Date: Nov, 2008
---------------------------------------------------------------------------- */
#include "bound.h"
#include <math.h>
// constructor/destructor
Bound::Bound(const Point& a_lower, const Point& a_upper):
m_lower(a_lower), m_upper(a_upper)
{}
Bound::~Bound()
{}
// search
int Bound::dimen() const
{
return m_lower.m_dimen;
}
Point Bound::center() const
{
return Point::midpoint(m_lower, m_upper);
}
// is this bound containing another (in param)
bool Bound::contain(const Bound& a_bound) const
{
for (int i=0; i<dimen(); i++)
{
if (m_lower[i] > a_bound.m_lower[i]) return false;
if (m_upper[i] < a_bound.m_upper[i]) return false;
}
return true;
}
// is this bound containing another (in param)
bool Bound::contain(const Point& a_pt) const
{
for (int i=0; i<dimen(); i++)
{
if (m_lower[i] > a_pt[i]) return false;
if (m_upper[i] < a_pt[i]) return false;
}
return true;
}
bool Bound::equal(const Bound& a_bd) const
{
for (int i=0; i<dimen(); i++)
{
if (m_lower[i] != a_bd.m_lower[i]) return false;
if (m_upper[i] != a_bd.m_upper[i]) return false;
}
return true;
}
float Bound::mindist(const Point& a_pt) const
{
float dist=0;
for (int i=0; i<dimen(); i++)
{
float d = 0;
if (a_pt[i] < m_lower[i])
d = m_lower[i] - a_pt[i];
else if (a_pt[i] > m_upper[i])
d = a_pt[i] - m_upper[i];
dist += d*d;
}
return sqrt(dist);
}
// info
int Bound::size(const int a_dimen)
{
return Point::size(a_dimen)*2;
}
| true |
ff07a087cacabe57b8d86a1b9ba49a7576a52591 | C++ | gmatesunny/CPPC | /CPP/derivedRotateString.cpp | UTF-8 | 823 | 3.484375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <thread>
using namespace std;
bool extraSpaceCheck(string in, string out) {
if ((in + in).find(out) != string::npos) {
return true;
}
return false;
}
bool checkRotate(string in, string out) {
for (unsigned int i = 0; i < in.length(); ++i) {
rotate(begin(in), begin(in) + 1, end(in));
if (out == in) {
return true;
}
}
return false;
}
int main() {
string in = "sunny";
string out = "nnysu";
if ((in.length() == out.length()) && extraSpaceCheck(in, out)) {
cout << "extraSpaceCheck: Yes, they are rotating substring." << endl;
} else {
cout << "extraSpaceCheck: No, they are not rotating substring." << endl;
}
return 0;
}
| true |
3b2794c332cba79e0215c4511dd68b3fe30ead74 | C++ | AMINALJALLAD/Eight-Minutes-Empire | /BidingFacility/BidingFacility.cpp | UTF-8 | 365 | 2.703125 | 3 | [] | no_license | #include "BidingFacility.h"
#include <iostream>
BidingFacility::BidingFacility() {
bidCoin = new int(-1);
}
BidingFacility::~BidingFacility() {
delete bidCoin;
}
BidingFacility::BidingFacility(int bidCoin) {
this->bidCoin = new int(bidCoin);
}
void BidingFacility::show() {
std::cout << getBid()<<"\n";
}
int BidingFacility::getBid(){
return *bidCoin;
}
| true |
49ad6787e001d93c7264093468eaf2f5c437e296 | C++ | priyanka1234-ops/studypod-2.0 | /point.cpp | UTF-8 | 671 | 3.8125 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std ;
class point
{
int x , y ;
public:
point(int a , int b){
x = a ;
y = b;
}
void displypoint(){
cout<<"The point is ("<<x<<" , "<<y<<")"<<endl ;
}
friend double distance (point , point);
};
double distance(point p1 , point p2){
double res = sqrt(pow(p1.x - p2.x , 2) + pow(p1.y - p2.y , 2));
return res ;
}
int main(){
point P(1,1); //IMPLICIT CALL
P.displypoint() ;
point Q = point(2,2) ; //EXPLICIT CALL
Q.displypoint() ;
double result = distance(P,Q);
cout<<"Distance between P and Q is"<<result ;
return 0 ;
} | true |
f5138ac2ae08a4169743e6ba804ee37288d66f54 | C++ | Jastry/Practice | /pointToOffer/38_StrToInt.cpp | UTF-8 | 674 | 3.421875 | 3 | [] | no_license | #include <iostream>
/* 实现 atoi 函数*/
class Solution {
public:
int StrToInt(std::string str) {
int i = 0;
int ret = 0;
while (isspace(str[i])) i++;
bool sign = 0;
if (str[i] == '-' || str[i] == '+') {
sign = (str[i] == '-');
++i;
}
for (; i < str.size(); ++i) {
if (!isdigit(str[i])) return 0;
int unit = str[i] - '0';
if (!sign) {
if (ret > (INT_MAX - unit) / 10)
return INT_MAX;
}
else {
if (-ret < (INT_MIN + unit) / 10)
return INT_MIN;
}
ret = ret * 10 + unit;
}
return sign ? -ret : ret;
}
};
int main()
{
std::string str = "+12345a67";
Solution so;
int res = so.StrToInt(str);
return 0;
}
| true |
49325352cd67b1f7fb54d1cf62eddf31fd21be5c | C++ | f20500909/study_note | /cpp/string/write_a_word.cpp | UTF-8 | 2,432 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <assert.h>
#include <string>
#include <sstream>
#include <chrono>
#include <iomanip>
using namespace std;
class Timer {
public:
Timer() = default;
std::chrono::steady_clock::time_point now() const {
return std::chrono::steady_clock::now();
}
std::chrono::steady_clock::time_point start() {
return start_time = std::chrono::steady_clock::now();
}
std::chrono::steady_clock::time_point stop() {
return end_time = std::chrono::steady_clock::now();
}
template <class T = double>
T elapsed() const {
return std::chrono::duration_cast<std::chrono::duration<T>>(
end_time - start_time)
.count();
}
template <typename F, typename... Args>
static double profile(F func, Args &&... args) {
Timer timer;
timer.start();
func(std::forward<Args>(args)...);
timer.stop();
return timer.elapsed();
};
private:
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
};
std::string EOS = "</s>";
bool readWord(std::stringstream& in, std::string& word) {
int c;
std::streambuf& sb = *in.rdbuf();
word.clear();
while ((c = sb.sbumpc()) != EOF) {
if (c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '\v' ||
c == '\f' || c == '\0') {
if (word.empty()) {
if (c == '\n') {
word += EOS;
return true;
}
continue;
}
else {
if (c == '\n')
sb.sungetc();
return true;
}
}
word.push_back(c);
}
// trigger eofbit
in.get();
return !word.empty();
}
void myFun(int lineNum) {
stringstream in;
for (size_t i = 0; i < lineNum; i++) {
in<<"dsf dsf \n sdfdsf dsfdsg fdgdf gfdsgf gdfs gfg f \r\n sdfdsf dsfdsg \r gfdsgf gdfs gfg f \r\n ";
}
string word;
while (readWord(in, word)) {
//cout << word << endl;
}
}
void readWithIn(int lineNum) {
stringstream in;
for (size_t i = 0; i < lineNum; i++) {
in << "dsf dsf \n sdfdsf dsfdsg fdgdf gfdsgf gdfs gfg f \r\n sdfdsf dsfdsg \r gfdsgf gdfs gfg f \r\n ";
}
string word;
while (in)
{
in >> word;
}
}
int main()
{
Timer timer;
timer.start();
myFun(1e5);
timer.stop();
cout << "使用readWord 读取完成.... 用时: " <<std::setprecision(3) << timer.elapsed()<< endl;
Timer timer2;
timer2.start();
readWithIn(1e5);
timer2.stop();
cout << "使用in 读取完成.... 用时: " << std::setprecision(3) << timer2.elapsed() << endl;
cin.get();
return 0;
} | true |
608b992f593cb811001207cffb66f36c3acca472 | C++ | mjenrungrot/competitive_programming | /UVa Online Judge/v6/626.cpp | UTF-8 | 1,078 | 2.671875 | 3 | [
"MIT"
] | permissive | /*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 626.cpp
# Description: UVa Online Judge - 626
=============================================================================*/
#include <cstdio>
#include <cstring>
int A[105][105], N;
int main() {
// freopen("in","r",stdin);
while (scanf("%d", &N) == 1) {
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++) scanf("%d", &A[i][j]);
int ans = 0;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
for (int k = 1; k <= N; k++)
if (A[i][j] and A[j][k] and A[k][i]) {
if (i == j or i == k or j == k) continue;
if (i < j and j > k) continue;
if (i > j and j < k) continue;
printf("%d %d %d\n", i, j, k);
ans++;
}
printf("total:%d\n\n", ans);
}
return 0;
} | true |
f2169fa31014bba150cce0b25c92fd11eec40946 | C++ | akashiitj/dsaprogram | /codechef/april lc 14/li.cpp | UTF-8 | 821 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
typedef long long ll;
#define FOR(i,n) for(ll i=0;i<n;i++)
#define FILL(a,b) memset(a,b,sizeof(a))
using namespace std;
inline ll read(ll &x){
x=0;int sign,ch;
while((ch<'0'||ch>'9')&&ch!='-'&&ch!=EOF) ch=getchar();
if (ch=='-')
sign=-1,ch=getchar();
else sign=1;
do
x=(x<<3)+(x<<1)+ch-'0';
while((ch=getchar())>='0' && ch<='9');
x*=sign;
return 1;
}
int main()
{
int n1;
cin>>n1;
ll a[n1];
ll hash[1000];
FILL(hash,0);
FOR(i,n1) {read(a[i]); hash[a[i]]++;}
FOR(i,n1-1)
{
read(a[i]);
hash[a[i]]--;
}
FOR(i,n1)
{
if(hash[a[i]]==1) { cout<<a[i];break;}
else hash[a[i]]++;
}
FOR(i,n1-2)
{
read(a[i]);
hash[a[i]]--;
}
FOR(i,n1-1)
{
if(hash[a[i]]==1) cout<<a[i];break;
}
}
| true |
50ae7ce3d4ba91c8d411215f15879a43fc978994 | C++ | winek353/GamepadController | /Source/MouseMover.cpp | UTF-8 | 1,083 | 2.6875 | 3 | [] | no_license | #include "MouseMover.hpp"
MouseMover::MouseMover(ISystemController& p_sysController,
IConfigStore& p_configStore,
ButtonsAndAxisStateKeeper& p_stateKeeper) :
sysController(p_sysController),
configStore(p_configStore),
stateKeeper(p_stateKeeper)
{
speedX = speedY = 0;
moveX = moveX = 0;
}
void MouseMover::moveMouse()
{
sysController.moveMouse(speedX,speedY);
}
void MouseMover::changeXAxisValues(int axisValue)
{
speedX = calculateSpeedFromAxisPosition(axisValue);
}
void MouseMover::changeYAxisValues(int axisValue)
{
speedY = calculateSpeedFromAxisPosition(axisValue);
}
int MouseMover::calculateSpeedFromAxisPosition(int axisValue)
{
if (axisValue >= configStore.getMouseDeadZoneSize())
return (axisValue - configStore.getMouseDeadZoneSize()) / configStore.getReversedMouseSpeed();
else if(axisValue <= -configStore.getMouseDeadZoneSize())
return (axisValue + configStore.getMouseDeadZoneSize()) / configStore.getReversedMouseSpeed();
else return 0;
}
| true |
2a4262e6701f66027b29da77edd82774acc13fa3 | C++ | dpenguin22/arduino_greenhouse | /libraries/Greenhouse/timer.cpp | UTF-8 | 1,340 | 3.75 | 4 | [] | no_license | /*
Purpose:
Timer class methods used to increment a timer and determine when it
has expired.
Dependencies:
None
Assumptions/Limitations:
Designed for a recurring timer that triggers at a data driven frequency
Modification History:
10/2015 - Initial version
*/
#include "timer.h"
// Constructor. Initialize to zero
Timer::Timer() {
value = 0;
threshold = 0;
increment = 0;
frequency = 0;
}
// increment_timer will add the increment to the timer value
void Timer::increment_timer(unsigned long increment) {
value = value + increment;
}
// Determine the threshold for triggering the timer
void Timer::set_threshold(float timerFreq) {
// The input frequency is in Hz, the increment must be in ms
threshold = (unsigned long) (1.0 / timerFreq) * 1000;
}
// reset_timer will reset the timer to zero
void Timer::reset_timer() {
value = 0;
}
// get value will return the timer value
unsigned long Timer::get_value() {
return value;
}
// evaluate_timer will check the current value of the timer versus the threshold and
// return whether it has been met. It will also reset the timer value
bool Timer::evaluate_timer() {
if (value >= threshold) {
reset_timer();
return true;
} else {
return false;
}
}
| true |
bc2210aae3ffd2dc4e5dcf4dbc441c501c88b8fd | C++ | marcelegii/Projekt_PK3 | /PK3_sem3_projekt/PK3_sem3_projekt/PK3_sem3_projekt/Rest.hpp | UTF-8 | 363 | 2.53125 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<string>
using namespace std;
class Rest
{
protected:
string name;
int day_start;
int month_start;
int yead_start;
public:
Rest();
Rest(string n, int d, int m, int y) : name(n), day_start(d), month_start(m), yead_start(y) {}
virtual ~Rest();
protected:
void readFromFile();
};
| true |
0e5d108635652681d88d9386e1c880512d53a84f | C++ | mihaiscornea99/Info221Scornea | /rege sah.cpp | UTF-8 | 2,784 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int afisareTabel(int tabla[8][8]);
int gasireRege(int tabla[8][8],int *pozVertical, int* pozOrizontal);
int backtrackingRege(int tabla[8][8],int pozVertical, int pozOrizontal, int contor);
int verificareRege(int tabla[8][8],int pozVertical, int pozOrizontal, int *pozNouV, int*pozNouO);
int gasireRege(int tabla[8][8],int *pozVertical, int* pozOrizontal){
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
if(tabla[i][j]==1){
*pozVertical=i;
*pozOrizontal=j;
return 1;
}
return 0;}
int verificareRege(int tabla[8][8],int pozVertical, int pozOrizontal, int *pozNouV, int*pozNouO){
for(int i=pozVertical-1;i<pozVertical+2;i++)
for(int j=pozOrizontal-1;j<pozOrizontal+2;j++)
if((i!=pozVertical||j!=pozOrizontal)&&i>=0&&i<9&&j>=0&&j<9){
if(tabla[i][j]==0)
*pozNouV=i;
*pozNouO=j;
return 1;}
return 0;
}
int wrapperBacktrackingRege(int tabla[8][8], int pozVertical, int pozOrizontal){
backtrackingRege(tabla,pozVertical,pozOrizontal,64);
}
int backtrackingRege(int tabla[8][8],int pozVertical, int pozOrizontal, int contor){
if(contor==0)
return 1;
//int poz2V, poz2O;
tabla[pozVertical][pozOrizontal]=65-contor;
printf("\n");
afisareTabel(tabla);
for(int i=pozVertical-1;i<pozVertical+2;i++)
for(int j=pozOrizontal-1;j<pozOrizontal+2;j++){
//printf("\n%d,%d",i,j);
if((i!=pozVertical||j!=pozOrizontal)&&i>=0&&i<8&&j>=0&&j<8)
if(tabla[i][j]==0)
if(!backtrackingRege(tabla, i, j, contor-1))
tabla[i][j]=0;
else
return 1;
}
return 0;}
int afisareTabel(int tabla[8][8]){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++)
printf("%6d ",tabla[i][j]);
printf("\n");
}
return 0;
}
int main(){
int tabla2[8][8],tabla[8][8]={{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{1,0,0,0,0,0,0,0}};
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
tabla2[i][j]=0;
int pozVertical,pozOrizontal;
if(gasireRege(tabla,&pozVertical,&pozOrizontal)==0)
printf("Nu exista regele pe tabla de sah");
else{
wrapperBacktrackingRege(tabla2,pozVertical,pozOrizontal);
printf("\n");
afisareTabel(tabla2);
}
return 0;}
| true |
2070631400e5b24cc162a0f26d63dfd7f12ffcbc | C++ | peder82/cpp_v2014 | /f7_polymorfi_abstrakte_klasser/abstrakt_interface.cpp | UTF-8 | 766 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include "class_fileFormatValidator.h"
using namespace std;
class privateFileFormatValidator : public fileFormatValidator{
string fileType;
string filename;
public:
privateFileFormatValidator(string _filename):
filename(_filename),fileType(){/*...*/};
};
enum HTML_version{HTML2_0,HTML3_2,HTML4_0,HTML4_1,HTML5,XHTML};
class HTMLvalidator : public privateFileFormatValidator{
public:
HTMLvalidator(string filename,HTML_version)
: privateFileFormatValidator(filename){/*...*/}
bool valid() override {cout << "Probably not. "; return false;}
};
int main(){
HTMLvalidator validator("index.html",HTML5);
cout << "Valid HTML5: " << validator.valid() << endl;
//fileFormatValidator v("myFile.ext"); //ERROR: Abstract!
}
| true |
6ce4ce2ac9b9bcbe68c15cb942f0d2f8e78e02b3 | C++ | hzhou/usaco | /18open/demo/sort_platinum.cpp | UTF-8 | 1,266 | 2.703125 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cstdio>
#include <algorithm>
int *A;
long long count = 0;
int main(int argc, char** argv)
{
int i_max;
int n;
FILE* In = fopen("sort.in", "r");
if (!In) {
fprintf(stderr, "Can't open In\n");
exit(-1);
}
int N;
fscanf(In, " %d" ,&N);
A = new int[N];
for (int i = 0; i<N; i++) {
fscanf(In, " %d" ,&A[i]);
}
fclose(In);
int P[N];
for (int i = 0; i<N; i++) {
P[i] = i;
}
std::sort(P, P+N, [&](int a, int b){
if (A[a] == A[b]) {
return a < b;
} else {
return A[a] < A[b];
}
} );
int Q[N];
i_max = 0;
for (int i = 0; i<N; i++) {
if (i_max < P[i]) {
i_max = P[i];
}
Q[i] = i_max - i;
}
for (int i = 0; i<N; i++) {
n = 0;
if (n < Q[i]) {
n = Q[i];
}
if (i > 0) {
if (n < Q[i-1]) {
n = Q[i-1];
}
}
if (n == 0 && N > 1) {
n++;
}
count += n;
}
std::cout<<"count="<<count<<'\n';
FILE* Out = fopen("sort.out", "w");
fprintf(Out, "%lld\n", count);
fclose(Out);
return 0;
}
| true |
652c56075cf00e01fbbacd89d47b38cc5ee767c1 | C++ | yuanyangwangTJ/RSA | /RSA.cpp | UTF-8 | 11,695 | 2.921875 | 3 | [
"MIT"
] | permissive | /************************************
* ClassName: RSAUser
* Function: 实现 RSA 加密使用者的类对象
* *********************************/
#include "RSA.h"
#include "Random.h"
#include "AES.h"
#include <iostream>
#include <fstream>
#include <ctime>
#include <cstring>
#include <NTL/ZZ.h>
#include <NTL/ZZ_p.h>
#include <algorithm>
using namespace std;
using namespace NTL;
// _getch() 函数的系统移植问题解决
#ifdef _WIN32
#include <conio.h>
#elif __linux__
char _getch();
#endif
void printChoose() {
cout << "Please choose the length of random prime: \n";
cout << "1. 512 bits\n";
cout << "2. 1024 bits\n";
}
RSAUser::RSAUser() {
cout << "Create RSA user..." << endl;
}
void RSAUser::GenerateKey() {
// 选择 RSA 素数的比特长度
int m = 0;
printChoose();
do {
char ch = _getch();
switch(ch) {
case '1': m = 8; break;
case '2': m = 16; break;
default: m = 0;
}
} while (m == 0);
PrimeGen G(m);
cout << "public key and private key are generating...\n";
// 生成私钥的随机素数 p, q
do {
sk.p = G.GeneratePrime();
sk.q = G.GeneratePrime();
} while (sk.p == sk.q);
// 生成公钥 n
pk.n = sk.p * sk.q;
ZZ Euler = (sk.p - 1) * (sk.q - 1); // 欧拉函数数值
do {
pk.b = G.GenerateRandom() % Euler;
} while(GCD(pk.b, Euler) != 1);
// 使用 NTL 库中的求逆函数 InvModStatus()
InvModStatus(sk.a, pk.b, Euler);
cout << "All keys have been generated !\n";
// 钥匙查看
viewKey(m * 64);
}
// 发送 RSA 公钥
void RSAUser::SendPublicKey(RSAUser &B) {
B.pk = this->pk;
}
// 创建临时密钥
void RSAUser::createTempKey() {
PRNG G(2);
k = G.GenerateRandom();
cout << "Temp key has been created.\n";
cout << "Do you want to view temp key, y/n ?\n";
char ch = _getch();
switch (ch) {
case 'Y':
case 'y':
cout << "temp key\n";
printKey(k, 128);
break;
default:
break;
}
}
// 加密信息,使用 CBC 模式
void RSAUser::EncryptMessage() {
// 生成临时密钥
createTempKey();
// 利用公钥加密 k 得到 c1,此处使用 ZZ_p 类计算
ZZ_p::init(pk.n);
ZZ_p k_p = to_ZZ_p(k);
M.c1 = rep(power(k_p, pk.b));
// 将临时密钥 k 转化为 128 比特形式
bitset<128> key(to_ulong(k));
// 以此创建 AES 加密系统
AES E(key);
// 需要加密的文件路径输入
string fileName, newfileName;
cout << "Please input the file path: \n";
cin >> fileName;
_getch(); // 接收回车符
// 密文存储为 源文件名 + ".cipher"
newfileName = fileName + ".cipher";
// 文件名作为信息传输
M.fileName = fileName;
// 打开文件
ifstream fin(fileName, ios::binary);
if (!fin) {
cerr << "open file error.\n";
exit(-1);
}
ofstream fout(newfileName, ios::binary);
if (!fout) {
cerr << "open file error.\n";
exit(-1);
}
// 因为逐字符读取文件比较慢,使用缓存区的方式一次性读取 16*1024 字节
bitset<128> buffer[512];
// CBC 模式
// former 记录密文 y(i-1) ,初始化为一个随机数
PRNG G(2);
M.IV = G.GenerateRandom();
bitset<128> former(to_ulong(M.IV));
// 将 IV 通过 RSA 加密发送
ZZ_p IV_p = to_ZZ_p(M.IV);
M.IV = rep(power(IV_p, pk.b));
bitset<128> cipher; // 密文
// 开始读取需要加密的文件
while (fin && !fin.eof()) {
// 一次性读取最多 16*1024 字节的内容
fin.read((char*)&buffer, 16*512);
streamsize readNum = fin.gcount();
streamsize i;
for (i = 0; i < readNum / 16; i++) {
cipher = E.AESEncrypt(former ^ buffer[i]);
former = cipher;
// 写入密文至文件中
fout.write((char*)&cipher, 16);
}
streamsize end = readNum % 16;
// 文件读取结束操作,使用 PKCS7Padding 处理末尾
if (fin.eof()) {
// 末尾填充的数字
bitset<128> pkcs(16 - end);
pkcs = pkcs << 120;
for (streamsize j = 16; j > end; j--) {
streamsize k = j - end - 1;
buffer[i] = ((buffer[i] << k*8) ^ pkcs) >> k*8;
}
cipher = E.AESEncrypt(former ^ buffer[i]);
fout.write((char*)&cipher, 16);
}
}
cout << "File encryption finished.\n";
cout << "Encrypted file is located at " << newfileName << endl;
// 关闭文件
fin.close();
fout.close();
}
// 解密信息
void RSAUser::DecryptMessage() {
// 利用密钥来解密 c1,得到临时密钥 k
ZZ_p::init(pk.n);
ZZ_p c1_p = to_ZZ_p(M.c1);
k = rep(power(c1_p, sk.a));
// 解密得到 IV
ZZ_p IV_p = to_ZZ_p(M.IV);
M.IV = rep(power(IV_p, sk.a));
// 查看临时密钥
cout << "Temp key has been decrypted.\n";
cout << "Do you want to view temp key, y/n ?\n";
char ch = _getch();
switch (ch) {
case 'Y':
case 'y':
cout << "temp key\n";
printKey(k, 128);
break;
default:
break;
}
// 使用密钥 k 解密
bitset<128> key(to_ulong(k));
// 创建 AES 加密解密系统
AES D(key);
// 密文文件
string fileName = M.fileName + ".cipher";
// 查找文件的名称中的 '\' 或者 '/' 最后出现位置
int pos = M.fileName.length() - 1;
for (; pos >= 0; pos--) {
if (M.fileName[pos] == '/' || M.fileName[pos] == '\\')
break;
}
// 解密文件位置
string newfileName = M.fileName.insert(pos + 1, "new_");
// 打开文件
ifstream fin(fileName, ios::binary);
if (!fin) {
cerr << "open file error.\n";
exit(-1);
}
ofstream fout(newfileName, ios::binary);
if (!fout) {
cerr << "open file error.\n";
exit(-1);
}
// buffer 缓冲区读取
bitset<128> buffer[512];
// former 记录密文 C(i-1),初始化为 M.IV
bitset<128> former(to_ulong(M.IV));
bitset<128> plain; // 明文
// 开始读取解密文件
while (fin && !fin.eof()) {
fin.read((char*)&buffer, 16*512);
streamsize readNum = fin.gcount();
bool flag = false; // 判断是否结束的标志
if (fin.eof() || fin.peek() == EOF) {
flag = true;
}
streamsize i, bufferMax = readNum / 16;
// 使用 end 记录需要解密的缓冲区最大编号
if (flag) bufferMax--;
for (i = 0; i < bufferMax; i++) {
plain = D.AESDecrypt(buffer[i]) ^ former;
former = buffer[i];
// 写入解密文件
fout.write((char*)&plain, 16);
}
// 处理 PKCS7Padding 结尾
if (flag) {
// end 表示额外填充的字节数
// 最后一次解密
plain = D.AESDecrypt(buffer[i]) ^ former;
streamsize end = (plain >> 120).to_ulong();
for (streamsize j = 16; j > end; j--) {
// 最后的字节处理
bitset<8> text((plain << (j-1)*8 >> 120).to_ulong());
fout.write((char*)&text, 1);
}
}
}
cout << "File decryption finished.\n";
cout << "Decrypted file is located at " << newfileName << endl;
fin.close();
fout.close();
}
// 发送信息
void RSAUser::SendMessage(RSAUser& A) {
A.M = this->M;
}
// PEM 格式打印输出
void RSAUser::PrintInPEM(const string s) {
string res = "";
size_t len = s.length() / 8; // 比特串转化为字节的长度
size_t i;
unsigned char triBytes[3]; // 存储三个字节
for (i = 0; i+3 <= len; i += 3) {
for (int j = 0; j < 3; j++) {
bitset<8> tmp(s.substr(8*i + 8*j, 8));
triBytes[j] = tmp.to_ulong();
}
res += Base64Map[triBytes[0] >> 2];
res += Base64Map[((triBytes[0]<<4) & 0x30) | (triBytes[1] >> 4)];
res += Base64Map[((triBytes[1]<<2) & 0x3c) | (triBytes[2] >> 6)];
res += Base64Map[triBytes[2] & 0x3f];
}
if (i < len) {
if (len - i == 1) {
bitset<8> tmp(s.substr(8*i, 8));
triBytes[0] = tmp.to_ulong();
res += Base64Map[triBytes[0] >> 2];
res += Base64Map[(triBytes[0]<<4) & 0x30];
res += "==";
} else {
for (int j = 0; j < 2; j++) {
bitset<8> tmp(s.substr(8*i + 8*j, 8));
triBytes[j] = tmp.to_ulong();
}
res += Base64Map[triBytes[0] >> 2];
res += Base64Map[((triBytes[0]<<4) & 0x30) | (triBytes[1] >> 4)];
res += Base64Map[(triBytes[1]<<2) & 0x3c];
res += "=";
}
}
cout << res << endl;
}
// DER(十六进制)格式打印
void RSAUser::PrintInDER(const string s) {
cout << "modulus:";
string pairstr = "";
for (size_t i = 0; i < s.length(); i += 4) {
int index = 0;
for (size_t j = i; j < i + 4; j++) {
index = index << 1;
if (s[j] == '1') {
index += 1;
}
}
pairstr += HexTable[index];
if (pairstr.length() == 2) {
cout << pairstr;
if (i + 4 < s.length()) {
cout << ":";
}
pairstr = "";
}
if (i % 120 == 0) {
cout << endl << '\t';
}
}
cout << endl;
}
// ZZ 类型转化为 Bits
string RSAUser::ZZToBits(ZZ num, const size_t n) {
string s = "";
ZZ last;
while (num != 0) {
last = num % 2;
if (last == 1) {
s += '1';
} else {
s += '0';
}
num /= 2;
}
for (size_t i = s.length(); i < n; i++) {
s += '0';
}
reverse(s.begin(), s.end());
return s;
}
// 选择输出格式打印
void printFormat() {
cout << "Please choose the format to print key :\n";
cout << "1. DER (hexadecimal)\n";
cout << "2. PEM\n";
}
// 查看钥匙,n 为 p,q 的比特位数
void RSAUser::viewKey(const size_t n) {
// 查看公钥
cout << "Do you want to view public key, y/n ?\n";
char ch = _getch();
switch(ch) {
case 'Y':
case 'y': {
cout << "Public key\n";
cout << "Print n in public key :\n";
printKey(pk.n, n*2);
cout << "Print b in public key :\n";
printKey(pk.b, n*2);
break;
}
default: break;
}
// 查看私钥
cout << "Do you want to view private key, y/n ?\n";
ch = _getch();
if (ch == 'y' || ch == 'Y') {
cout << "Attention, please not reveal this information !!!\n";
cout << "Read the warning, continue, y/n ?\n";
ch = _getch();
switch(ch) {
case 'Y':
case 'y': {
cout << "Private key\n";
cout << "Print p in private key :\n";
printKey(sk.p, n);
cout << "Print q in private key :\n";
printKey(sk.q, n);
cout << "Print a in private key :\n";
printKey(sk.a, n*2);
break;
}
default: break;
}
}
}
// 打印每一个钥匙
void RSAUser::printKey(ZZ num, const size_t n) {
string s = ZZToBits(num, n);
printFormat();
bool flag = false;
while (!flag) {
char ch = _getch();
switch(ch) {
case '1': {
PrintInDER(s);
flag = true;
break;
}
case '2': {
PrintInPEM(s);
flag = true;
break;
}
default: break;
}
}
} | true |
f61354d607048cfba74e5d2c4d78bb88582bb168 | C++ | z-sector/otus_algo_homework | /02_Array/PriorityQueueMain.cpp | UTF-8 | 749 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include "PriorityQueue.h"
int main() {
PriorityQueue<int> pq;
pq.enqueue(0, 1000);
pq.enqueue(1, 100);
pq.enqueue(1, 101);
if (pq.dequeue() != 100) {
std::cerr << "Fail";
return (EXIT_FAILURE);
}
pq.enqueue(-1, -1000);
pq.enqueue(100, 1);
if (pq.dequeue() != 1) {
std::cerr << "Fail";
return (EXIT_FAILURE);
}
if (pq.dequeue() != 101) {
std::cerr << "Fail";
return (EXIT_FAILURE);
}
if (pq.dequeue() != 1000) {
std::cerr << "Fail";
return (EXIT_FAILURE);
}
if (pq.dequeue() != -1000) {
std::cerr << "Fail";
return (EXIT_FAILURE);
}
std::cout << "OK";
return (EXIT_SUCCESS);
} | true |
82c826c329f2e2bf2d019851a0180e8e794e3602 | C++ | sletsen1452/taller3 | /punto16/punto16.cpp | UTF-8 | 472 | 3.203125 | 3 | [] | no_license | /*
* Programa : suma de numero primos del 1 al 50
* Fecha : 19/08/18
* Autor: Sletsen Duque Vargas
*/
#include <iostream>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int suma=0,div=1,cont, n=1;
while(n<=50)
{
while(div<=n)
{
if(n%div==0)
{
cont++;
}
div++;
}
if(cont==2)
{
suma = suma +n;
}
n++;
cont = 0;
div = 0;
}
printf("la suma de los numero primos (del 1 al 50)es: %d",suma);
return 0;
}
| true |
b65359d43d99d86eecc4cb2b7bd1ee1634b7db13 | C++ | selinahsu/derivative-of-a-polynomial | /Polynomial Derivatives.cpp | UTF-8 | 792 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
#include <sstream>
using namespace std;
int main () {
string input = "";
cout << "Enter a term to derive with respect to x, with no spaces or brackets: " << endl;
cin >> input;
int length = input.size();
// separate coefficient
string coeffStr = input.substr(0, input.find("^")); // turn coefficient to string
int digits = coeffStr.size();
stringstream coeffToInt(coeffStr);
int coeff = 0;
coeffToInt >> coeff;
// separate exponent
string expStr = input.substr(length-1, length-1);
stringstream expToInt(expStr);
int exp = 0;
expToInt >> exp;
coeff = coeff*exp;
exp--;
cout << coeff << "^" << exp << endl;
system("PAUSE");
return 0;
}
| true |
c4eeb367b9b75084aa57f03a8e242392cec815c7 | C++ | cmspv/OOP_Tut10_Project_18-19 | /Tut10_main_Q4d.cpp | UTF-8 | 1,900 | 3.734375 | 4 | [] | no_license | ////////////////////////////////////////////////////////////////////////
// OOP Tutorial 10: More on Classes and Instances (Question 4d)
////////////////////////////////////////////////////////////////////////
//--------include libraries
#include <iostream>
#include <string>
using namespace std;
//Question 4d: return references and const references
class Score {
public:
Score();
Score(int a);
~Score();
Score(const Score& s);
int getAmount() const;
void setAmount(int a);
//...
private:
int amount_;
};
Score::Score() : amount_(0) {
cout << "\nScore() called";
}
Score::Score(int a) : amount_(a) {
cout << "\nScore( int a) called";
}
Score::Score(const Score& s) : amount_(s.amount_) {
cout << "\nScore( const Score&) called";
}
Score::~Score() {
cout << "\n~Score() called";
}
int Score::getAmount() const {
return amount_;
}
void Score::setAmount(int a) {
amount_ = a;
}
class Player {
public:
Player();
Player(const Score& score, const string& name);
const Score& getScore() const;
//...
private:
Score score_;
string name_;
};
Player::Player() : score_(0)
{
cout << "\nPlayer() called";
}
Player::Player(const Score& score, const string& name) : score_(score), name_(name)
{
cout << "\nPlayer( Score score, string name) called";
}
const Score& Player::getScore() const
{
return score_;
}
int main()
{
//Question 4d
cout << "\n\n\nCreating a Score and a Player... ";
cout << "\n\nScore s;";
Score s(12);
cout << "\n\nPlayer p( s, \"Fred\");";
Player p(s, "Fred");
cout << "\n\nShowing score of player... p.getScore().getAmount();";
cout << "\nFred score is: " << p.getScore().getAmount();
cout << "\n\nTrying to change score of player... p.getScore() = 2;";
//p.getScore() = 2;
cout << "\n\nShowing score of player... p.getScore().getAmount();";
cout << "\nFred score is: " << p.getScore().getAmount();
cout << "\n\n";
system("pause");
return 0;
}
| true |
afe6027875c77afded2a11cc99225a84a3e53462 | C++ | KotNaKiske/HLK-SW16_ESP32 | /Server/Button.cpp | UTF-8 | 4,509 | 2.625 | 3 | [] | no_license | /////////////////////////////////////////////////////////////////
/*
Button.cpp - Arduino Library to simplify working with buttons.
Created by Lennart Hennigs.
*/
/////////////////////////////////////////////////////////////////
#include "Arduino.h"
#include "Button.h"
/////////////////////////////////////////////////////////////////
Button::Button(byte attachTo, byte buttonMode) {
pin = attachTo;
setDebounceTime(50);
pinMode(attachTo, buttonMode);
//if ((pin == 0) || (pin == 2) || (pin == 4) || (pin == 15) || (pin == 12) || (pin == 13) || (pin == 14) || (pin == 27) || (pin == 33) || (pin == 32)) {
/*if ( (pin == 32)) {
capa = touchRead(pin);
state = capa < CAPACITIVE_TOUCH_THRESHOLD ? LOW : HIGH;
} else {
state = digitalRead(pin);
}/**/
state = digitalRead(pin);
}
/////////////////////////////////////////////////////////////////
bool Button::operator==(Button &rhs) {
return (this == &rhs);
}
/////////////////////////////////////////////////////////////////
void Button::setDebounceTime(unsigned int ms) {
debounce_time_ms = ms;
}
/////////////////////////////////////////////////////////////////
void Button::setChangedHandler(CallbackFunction f) {
change_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button::setPressedHandler(CallbackFunction f) {
pressed_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button::setReleasedHandler(CallbackFunction f) {
released_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button::setClickHandler(CallbackFunction f) {
click_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button::setTapHandler(CallbackFunction f) {
tap_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button::setLongClickHandler(CallbackFunction f) {
long_cb = f;
}
/////////////////////////////////////////////////////////////////
void Button::setDoubleClickHandler(CallbackFunction f) {
double_cb = f;
}
/////////////////////////////////////////////////////////////////
unsigned int Button::wasPressedFor() const {
return down_time_ms;
}
/////////////////////////////////////////////////////////////////
boolean Button::isPressed() const {
return (state != pressed);
}
/////////////////////////////////////////////////////////////////
boolean Button::isPressedRaw() const {
return (digitalRead(pin) == pressed);
}
/////////////////////////////////////////////////////////////////
byte Button::getNumberOfClicks() const {
return click_count;
}
/////////////////////////////////////////////////////////////////
byte Button::getClickType() const {
return last_click_type;
}
/////////////////////////////////////////////////////////////////
byte Button::getPin() const {
return pin;
}
/////////////////////////////////////////////////////////////////
void Button::loop() {
prev_state = state;
//if (!capacitive) {
//} else {
//#if defined(ARDUINO_ARCH_ESP32)
//if ((pin == 0) || (pin == 2) || (pin == 4) || (pin == 15) || (pin == 12) || (pin == 13) || (pin == 14) || (pin == 27) || (pin == 33) || (pin == 32)) {
//if (pin == 32) {
capa = digitalRead(pin);
//capa = touchRead(pin);
if (prev_state != (capa)) {
if (down_ms == 0) {
down_ms = millis();
} else if (millis() - down_ms > 50) {
down_ms = 0;
state = capa ;
}
} else
down_ms = 0;
//} else {
// state = digitalRead(pin);
//}/**/
//state = digitalRead(pin);
if (prev_state != state)
if (state == pressed) {
if (tap_cb != NULL) tap_cb (*this);
//prev_click = millis();
if (pressed_cb != NULL) pressed_cb (*this);
} else {
//down_time_ms = millis() - down_ms;
if (tap_cb != NULL) tap_cb (*this);
//down_ms = millis();
//prev_click = millis();
}
}
/////////////////////////////////////////////////////////////////
void Button::reset() {
click_count = 0;
last_click_type = 0;
down_time_ms = 0;
pressed_triggered = false;
longclick_detected = false;
pressed_cb = NULL;
released_cb = NULL;
change_cb = NULL;
tap_cb = NULL;
click_cb = NULL;
long_cb = NULL;
double_cb = NULL;
triple_cb = NULL;
}
/////////////////////////////////////////////////////////////////
| true |
c4832fd2d83c81172c5344db8a3eb7889c5e0b34 | C++ | ooooo-youwillsee/leetcode | /1501-2000/1649-Create Sorted Array through Instructions/cpp_1649/Solution2.h | UTF-8 | 1,239 | 3.09375 | 3 | [
"MIT"
] | permissive | /**
* @author ooooo
* @date 2021/3/20 18:52
*/
#ifndef CPP_1649__SOLUTION2_H_
#define CPP_1649__SOLUTION2_H_
#include <iostream>
#include <vector>
using namespace std;
// 树状数组
class Solution {
public:
struct BIT {
vector<int> data, tree;
BIT(vector<int> data) : data(data.size()), tree(data.size() + 1) {
for (int i = 0; i < data.size(); ++i) {
this->data[i] = data[i];
}
for (int i = 0; i < data.size(); ++i) {
set(i, data[i]);
}
}
void set(int i, int v) {
i++;
while (i < tree.size()) {
tree[i] += v;
i += lowBit(i);
}
}
int query(int i) {
i++;
int sum = 0;
while (i >= 1) {
sum += tree[i];
i -= lowBit(i);
}
return sum;
}
int lowBit(int x) {
return x & -x;
}
};
static constexpr int MOD = 1e9 + 7;
int createSortedArray(vector<int> &instructions) {
vector<int> nums(1e5 + 1);
BIT tree(nums);
long long ans = 0;
for (int i = 0; i < instructions.size(); ++i) {
int less = tree.query(instructions[i] - 1);
int greater = i - nums[instructions[i]] - less;
ans = (ans + min(less, greater)) % MOD;
nums[instructions[i]]++;
tree.set(instructions[i], 1);
}
return ans;
}
}
#endif //CPP_1649__SOLUTION2_H_
| true |
9d54313b7864b6e6384b2d7bf81be960b8058747 | C++ | Dasister/mysql-cpp-api-wrapper | /src/mysql_api.cpp | UTF-8 | 2,585 | 2.71875 | 3 | [] | no_license | #include "mysql_api.h"
MySQL::MySQL()
{
mysql_init(&_mysql);
_host = "localhost";
_user = "root";
_password = "";
_port = 3306;
_db = "";
}
MySQL::MySQL(std::string host, std::string user, std::string password, std::string db = NULL, int port = 3306)
{
mysql_init(&_mysql);
_host = host;
_user = user;
_password = password;
_db = db;
_port = port;
}
MySQL::~MySQL()
{
disconnect();
}
bool MySQL::connect()
{
if (!mysql_real_connect(&_mysql, _host.c_str(), _user.c_str(), _password.c_str(), _db.c_str(), _port, NULL, 0))
{
return false;
}
return true;
}
bool MySQL::connect(std::string host, std::string user, std::string password, std::string db = NULL, int port = 3306)
{
if (!mysql_real_connect(&_mysql, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, NULL, 0))
{
return false;
}
return true;
}
void MySQL::setCharacterSet(std::string characterSet)
{
mysql_options(&_mysql, MYSQL_SET_CHARSET_NAME, characterSet.c_str());
}
void MySQL::disconnect()
{
if (isConnected())
{
mysql_close(&_mysql);
}
}
/* Error reporting */
unsigned int MySQL::getErrorCode()
{
return mysql_errno(&_mysql);
}
std::string MySQL::getErrorString()
{
return (const char *)mysql_error(&_mysql);
}
/* Error reporting */
bool MySQL::isConnected()
{
return (mysql_ping(&_mysql) == 0);
}
bool MySQL::setecltDB(std::string db)
{
return (mysql_select_db(&_mysql, db.c_str()) == 0);
}
std::string MySQL::escapeString(std::string what)
{
if (!isConnected())
return what;
char *to = new char[(what.size() * 2) + 1];
mysql_real_escape_string(&_mysql, to, what.c_str(), what.size());
return (const char*)to;
}
bool MySQL::query(std::string query)
{
if (mysql_real_query(&_mysql, query.c_str(), query.size()))
return false;
if (mysql_field_count(&_mysql)) // This is SELECT-like statement. We need to store result.
{
_result = MySQL_Query(mysql_store_result(&_mysql));
}
else
{
_result = MySQL_Query();
}
return true;
}
bool MySQL::transaction()
{
return (mysql_autocommit(&_mysql, 0) == 0);
}
bool MySQL::commit()
{
if (mysql_commit(&_mysql))
return false;
if (mysql_autocommit(&_mysql, 1))
return false;
return true;
}
bool MySQL::rollback()
{
if (mysql_rollback(&_mysql))
return false;
if (mysql_autocommit(&_mysql, 1))
return false;
return true;
}
MySQL_Query MySQL::getResult()
{
return _result;
}
| true |
b1b7c952eb94efca8f5f5586647512f90d444b12 | C++ | marcinjosinski/pl0-interpreter | /src/scope.hpp | UTF-8 | 1,383 | 2.875 | 3 | [
"Unlicense"
] | permissive | #ifndef PL0_SCOPE_HPP
#define PL0_SCOPE_HPP
#include <memory>
#include <string_view>
#include <unordered_map>
#include "identifier_info.hpp"
#include "utils.hpp"
namespace pl0::scope {
using symbol_table = std::unordered_map<std::string_view, ident_info_ptr>;
class scope {
public:
scope &operator=(const scope &) = default;
scope(const scope &) = default;
scope(std::string_view name = "",
std::shared_ptr<scope> enclosing_scope = nullptr)
: name_{std::move(name)}, enclosing_scope_{std::move(enclosing_scope)},
level_(enclosing_scope_ ? enclosing_scope_->level_ + 1 : 0) {}
std::string_view get_scope_name() const { return name_; }
std::shared_ptr<scope> get_enclosing_scope() { return enclosing_scope_; }
void define(ident_info_ptr symbol) {
auto result = memory_.emplace(symbol->get_name(), std::move(symbol));
if (!result.second)
throw utils::error{"Fail define symbol"};
}
identifier_info::ident_info *resolve(std::string_view name) {
auto iter = memory_.find(name);
if (iter == memory_.end()) {
return enclosing_scope_ ? enclosing_scope_->resolve(name) : nullptr;
}
return iter->second.get();
}
int get_level() const { return level_; }
public:
symbol_table memory_;
std::string_view name_;
std::shared_ptr<scope> enclosing_scope_;
int level_;
};
} // namespace pl0::scope
#endif | true |
5797b274654184e6be898f14217ab409c91af1e9 | C++ | joshsonola/Select-Projects | /Othello/player.h | UTF-8 | 659 | 2.53125 | 3 | [] | no_license | #ifndef __PLAYER_H__
#define __PLAYER_H__
#include <iostream>
#include <vector>
#include "common.h"
#include "board.h"
using namespace std;
class Player {
public:
Player(Side side);
~Player();
Board * curr_board;
Side curr_side;
Move *doMove(Move *opponentsMove, int msLeft);
Move * Heuristic(std::vector<Move *> possible_moves, Side side, Board * board);
int HeuristicValue(Move * move, Side side, Board * board);
Move * MiniMax(std::vector<Move *> possible_moves);
int MiniMaxValue(Move * curr_move);
// Flag to tell if the player is running within the test_minimax context
bool testingMinimax;
};
#endif
| true |
bf4a091b383873a5fd62b250caff2e02084d7be7 | C++ | user114145/computergraphics | /raytracer/scene.cpp | UTF-8 | 3,616 | 2.796875 | 3 | [] | no_license | //
// Framework for a raytracer
// File: scene.cpp
//
// Created for the Computer Science course "Introduction Computer Graphics"
// taught at the University of Groningen by Tobias Isenberg.
//
// Authors:
// Maarten Everts
// Jasper van de Gronde
//
// This framework is inspired by and uses code of the raytracer framework of
// Bert Freudenberg that can be found at
// http://isgwww.cs.uni-magdeburg.de/graphik/lehre/cg2/projekt/rtprojekt.html
//
#include "scene.h"
#include "material.h"
Color Scene::trace(const Ray &ray)
{
// Find hit object and distance
Hit min_hit(std::numeric_limits<double>::infinity(),Vector());
Object *obj = NULL;
for (unsigned int i = 0; i < objects.size(); ++i) {
Hit hit(objects[i]->intersect(ray));
if (hit.t<min_hit.t) {
min_hit = hit;
obj = objects[i];
}
}
// No hit? Return background color.
if (!obj) return Color(0.0, 0.0, 0.0);
Material *material = obj->material; //the hit objects material
Point hit = ray.at(min_hit.t); //the hit point
Vector N = min_hit.N; //the normal at hit point
Vector V = -ray.D; //the view vector
switch (mode) {
case PHONG:
return renderPhong(material, hit, N, V);
case ZBUFFER:
return renderZBuffer(hit);
case NORMAL:
return renderNormal(N);
}
return Color(0.0, 0.0, 0.0);
}
Color Scene::renderPhong(Material *m, Point hit, Vector N, Vector V)
{
Color color;
Vector L, R;
for (std::vector<Light*>::iterator it=lights.begin(); it!=lights.end(); ++it) {
// Ambient
color += (*it)->color * m->color * m->ka;
// Diffusion
L = (*it)->position - hit;
L.normalize();
if (N.dot(L) < 0.0)
continue;
color += N.dot(L) * (*it)->color * m->color * m->kd;
// Specular
R = 2 * N.dot(L) * N - L;
if (R.dot(V) < 0) continue;
R.normalize();
color += pow(V.dot(R), m->n) * (*it)->color * m->ks;
}
return color;
}
Color Scene::renderZBuffer(Point hit)
{
return Color(hit.z, hit.z, hit.z);
}
Color Scene::renderNormal(Vector N)
{
Vector C = N.normalized();
C = (C + 1) * .5;
return Color(C.x, C.y, C.z);
}
void Scene::render(Image &img)
{
int w = img.width();
int h = img.height();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
Point pixel(x+0.5, h-1-y+0.5, 0);
Ray ray(eye, (pixel-eye).normalized());
Color col = trace(ray);
img(x,y) = col;
}
}
if (mode == ZBUFFER) {
double min=pow(2,32), max=0, scale, c;
for (int y=0; y<h; ++y) {
for (int x=0; x<w; ++x) {
min = (img(x,y).r < min) ? img(x,y).r : min;
max = (img(x,y).r > max) ? img(x,y).r : max;
}
}
scale = 1 / (max-min);
for (int y=0; y<h; ++y) {
for (int x=0; x<w; ++x) {
c = (img(x,y).r - min) * scale;
img(x,y) = Color(c, c, c);
}
}
}
// Make sure the colors are not out of range
Color col;
for (int y=0; y<h; ++y) {
for (int x=0; x<w; ++x) {
col = img(x,y);
col.clamp();
img(x,y) = col;
}
}
}
void Scene::addObject(Object *o)
{
objects.push_back(o);
}
void Scene::addLight(Light *l)
{
lights.push_back(l);
}
void Scene::setEye(Triple e)
{
eye = e;
}
void Scene::setMode(RENDER_MODE m)
{
mode = m;
}
| true |
8e01749d8445f816ce5019d3b709132bd873de10 | C++ | meeio/leetcode | /data_struct/LRU&LFU/146.lru-缓存机制-std.cpp | UTF-8 | 1,811 | 3.5 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=146 lang=cpp
*
* [146] LRU 缓存机制
*/
// @lc code=start
#include <algorithm>
#include <list>
#include <unordered_map>
typedef std::pair<int, int> node;
class LRUCache
{
public:
LRUCache(int capacity)
: cap(0)
, max_cap(capacity)
{
}
int get(int key)
{
if ( auto it = key_to_it.find(key); it != key_to_it.end() )
{
auto node_it = it->second;
int key = node_it -> first;
int val = node_it -> second;
list.erase(node_it);
list.emplace_front(key, val);
key_to_it[key] = list.begin();
return val;
}
else
{
return -1;
}
}
void put(int key, int value)
{
if ( auto it = key_to_it.find(key); it != key_to_it.end() )
{
auto node_it = it->second;
list.erase(node_it);
list.emplace_front(key, value);
key_to_it[key] = list.begin();
}
else
{
if ( cap == max_cap )
{
node to_remove = list.back();
key_to_it.erase(to_remove.first);
list.pop_back();
}
else
{
cap++;
}
list.emplace_front(key, value);
key_to_it[key] = list.begin();
}
}
private:
int cap, max_cap;
std::list<node> list;
std::unordered_map<int, std::list<node>::iterator> key_to_it;
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
// @lc code=end
| true |
8742baf54bf69e49b45c779407c0e9cd26d1224a | C++ | sysu-wuzhihui/leetcode-lcof | /剑指 Offer 46. 把数字翻译成字符串.cpp | GB18030 | 1,539 | 3.765625 | 4 | [] | no_license | //ָ Offer 46. ַַ
//̬滮
class Solution {
public:
int translateNum(int num) {
return helper(to_string(num));
}
int helper(string str)
{
vector<int> dp(str.size() + 1);
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= str.size(); ++i)
{
if (str[i - 2] == '0' || str[i - 2] > '2' || str[i - 2] == '2' && str[i - 1] > '5')
dp[i] = dp[i - 1];
else
dp[i] = dp[i - 1] + dp[i - 2];
//cout << dp[i] << endl;
}
return dp[str.size()];
}
};
//̬滮ֻʹǰӽ
class Solution {
public:
int translateNum(int num) {
return helper(to_string(num));
}
int helper(string str)
{
int a = 1, b = 1, res = 1;
for (int i = 2; i <= str.size(); ++i)
{
if (str[i - 2] == '0' || str[i - 2] > '2' || str[i - 2] == '2' && str[i - 1] > '5')
res = b;
else
res = a + b;
a = b;
b = res;
//cout << dp[i] << endl;
}
return res;
}
};
//ݹ
class Solution {
public:
int translateNum(int num) {
if (num < 10)
return 1;
if (num % 100 >= 10 && num % 100 <= 25)
return translateNum(num / 10) + translateNum(num / 100);
else
return translateNum(num / 10);
}
};
| true |
a263a66339621a2e4f07cc751ee4a9a2b67e13a9 | C++ | zethuman/PP1 | /Lab/lab9/L.cpp | UTF-8 | 896 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int n, x,y;
vector<int> v;
cin >> n;
pair <int, int> a[n];
for(int i = 0; i < n; i++)
{
cin >> x >> y;
a[i] = make_pair(x,y);
//cin>>P[i].first>>P[i].second;
}
int sum = 0;
for(int i = 0; i < n; i++)
{
sum = a[i].first + a[i].second;
v.push_back(sum);
}
if(v.size() == n)
{
vector<pair<int,int>> V;
for(int i = 0; i < v.size(); i++)
{
pair<int,int> P=make_pair(v[i],i + 1);
V.push_back(P);
}
sort(V.begin(),V.end());
for(int i = 0; i < v.size(); i++)
cout<< V[i].second << " " ;
}
} | true |
3eb5e807a9f9ddbecc31efe084933f5b4a36ffba | C++ | hongwei-dong/hongwei-dong.github.io | /ds/stu_array2.cpp | GB18030 | 634 | 3.15625 | 3 | [] | no_license | // copyright by hongwei dong (hwdong.com)
#include "cstring"
#include "malloc.h"
#include "cstdio"
typedef struct{
char name[30];
float score;
} student;
void In_student(student &s){
scanf("%s",s.name);
scanf("%f",&(s.score));
}
void Out_student(const student s){
printf("name:%s score:%3.2f\n",
s.name, s.score);
}
int main(){
student stus[100];
int i = 0,j = 0,k=0 ;
do{
printf("ѧͷ\n");
In_student(stus[i]);
if(stus[i].score>=60) j++;
}while(stus[i++].score>=0);
i--;
for(k=0;k<i;k++)
Out_student(stus[k]);
printf("num of passed: %d\n",j);
}
| true |
5b292ab9c4cc3f261697a671431739d534968515 | C++ | Guillermo794/portafolio | /Programas c++/programa 35.cpp | UTF-8 | 683 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <locale.h>
#include <string.h>
#include <math.h>
using namespace std;
float media(float y,float x);
float cubo(float r);
void saludo();
int main(){
float x,y,p,m;
saludo();
cout<<"ingresa x"<<endl;
cin>>x;
cout<<"ingresa y "<<endl;
cin>>y;
m=media(x,y);
p=cubo(x);
cout<<"media de tus valores es: "<<m<<endl;
cout<< "cubo de x: "<<x<<" es :"<<p<<endl;
system("PAUSE");
return 0;
}
float media(float x, float y)
{
float c=(x+y)/2;
return c;
}
float cubo(float r)
{
float d=pow(r,3);
return d;
}
void saludo()
{
cout<<"hola blienvenido al sistema"<<endl;
}
| true |
3ffd5fce98d706fb784631a8c90bde70d66de113 | C++ | IcEiE/ADS | /ADS3/InsertionSort.cpp | UTF-8 | 1,596 | 3.671875 | 4 | [
"Apache-2.0"
] | permissive | #include "pch.h"
#include "InsertionSort.h"
InsertionSort::InsertionSort()
{
std::cout << "\nWelcome to InsertionSort \n\n1: Create list \n2: Random list \n\nI choose:";
bool keepLoop = true;
while (keepLoop) {
std::cin >> choice;
switch (choice)
{
case 1:
createUserList();
keepLoop = false;
break;
case 2:
int elements;
std::cout << "\nNumber of elements: ";
std::cin >> elements;
getRandomList(elements);
keepLoop = false;
break;
default:
std::cout << "\nThat is not a valid number! Choose a new one: ";
break;
}
}
std::cout << "\nYour list is: ";
printList();
insertionSort();
std::cout << "\nYour sorted list is: ";
printList();
}
InsertionSort::~InsertionSort()
{
}
void InsertionSort::getRandomList(int elements) {
for (int i = 0; i < elements; ++i) {
linkedL.push_back(rand() % 1000);
}
}
void InsertionSort::insertionSort() {
for (std::list<int>::iterator current = linkedL.begin(); current != linkedL.end(); current = std::next(current)) {
if (current != linkedL.begin()) {
if (*current < *std::prev(current)) {
std::list<int>::iterator temp = std::prev(current);
std::swap(*current, *std::prev(current));
if (prev(current) != linkedL.begin()) {
current = std::prev(std::prev(current));
}
}
}
}
}
void InsertionSort::createUserList()
{
int userNbr;
std::cout << "Write the number you want on list, when done write a letter.\n";
while (std::cin >> userNbr) {
linkedL.push_back(userNbr);
}
}
void InsertionSort::printList() {
for (auto v : linkedL) {
std::cout << v << ", ";
}
} | true |
6ed142ca6dd7b647018d4cf9413a9b3f9bb82312 | C++ | lukaszgryglicki/my_legacy_stuff | /cyg_jelly/point3d.hxx | UTF-8 | 724 | 2.90625 | 3 | [] | no_license | #ifndef __POINT_H__MDBMA__
#define __POINT_H__MDBMA__
#include "defs.hxx"
#include "obj3d.hxx"
#include "vec3d.hxx"
class point3 : public object, public vector3 /* punkt 3d */
{
vector3 my_Normal;
real my_U;
real my_V;
public:
point3(double v = 0.0f) : vector3(v) {};
point3(double x,double y,double z) : vector3(x, y, z) {};
~point3() {};
vector3& get_normal(void) { return my_Normal; };
real& get_u(void) { return my_U; };
real& get_v(void) { return my_V; };
void set_params(real u, real v) { my_U = u; my_V = v; };
point3& operator =(const point3& pt)
{
my_U = pt.my_U; my_V = pt.my_V;
my_Normal = pt.my_Normal;
vector3::operator =(pt);
return *this;
};
};
#endif
| true |
8854e9937bc6a5147d160e81dbd40f0edb28116a | C++ | petiaccja/Inline-BaseLibrary | /test/Test_StringUtil.cpp | UTF-8 | 4,990 | 3.125 | 3 | [] | no_license | #include <InlineLib/StringUtil.hpp>
#include <Catch2/catch.hpp>
#include <string>
using namespace inl;
TEST_CASE("Tokenize, no trim, cstring", "[StringUtil]") {
auto tokens = Tokenize("the day i learn to fly", " ", false);
std::vector<std::string_view> expectedTokens = {
"the", "day", "i", "learn", "to", "fly"
};
REQUIRE(tokens == expectedTokens);
}
TEST_CASE("Tokenize, no trim, mixed view", "[StringUtil]") {
std::string_view str("i'm never coming down");
auto tokens = Tokenize(str, " '", false);
std::vector<std::string_view> expectedTokens = {
"i", "m", "never", "coming", "down"
};
REQUIRE(tokens == expectedTokens);
}
TEST_CASE("Tokenize, no trim, mixed string", "[StringUtil]") {
std::string str("on perfect wings i'll rise");
auto tokens = Tokenize(str, " '", false);
std::vector<std::string_view> expectedTokens = {
"on", "perfect", "", "wings", "i", "ll", "rise"
};
REQUIRE(tokens == expectedTokens);
}
TEST_CASE("Tokenize, trim", "[StringUtil]") {
auto tokens = Tokenize("through the \tlayers \r\nof the clouds", " \t\r\n", true);
std::vector<std::string_view> expectedTokens = {
"through", "the", "layers", "of", "the", "clouds"
};
REQUIRE(tokens == expectedTokens);
}
TEST_CASE("Trim, simple", "[StringUtil]") {
std::string str = " \t asd ";
auto trimmed = Trim(str, " \t\n");
REQUIRE(trimmed == "asd");
}
TEST_CASE("Trim, already trimmed", "[StringUtil]") {
std::string str = "asd";
auto trimmed = Trim(str, " \t\n");
REQUIRE(trimmed == "asd");
}
TEST_CASE("Trim, empty", "[StringUtil]") {
std::string str = "";
auto trimmed = Trim(str, " \t\n");
REQUIRE(trimmed == "");
}
TEST_CASE("Encode UCS4->UTF-8 character", "[StringEncode]") {
// Examples from wikipedia: https://en.wikipedia.org/wiki/UTF-8
char32_t c1 = char32_t(0x0024);
char32_t c2 = char32_t(0x00A2);
char32_t c3 = char32_t(0x20AC);
char32_t c4 = char32_t(0x10348);
std::array<char, 4> u1exp = { (char)0x24, (char)0, (char)0, (char)0 };
std::array<char, 4> u2exp = { (char)0xC2, (char)0xA2, (char)0, (char)0 };
std::array<char, 4> u3exp = { (char)0xE2, (char)0x82, (char)0xAC, (char)0 };
std::array<char, 4> u4exp = { (char)0xF0, (char)0x90, (char)0x8D, (char)0x88 };
auto u1 = inl::impl::EncodeProduce(c1, char());
auto u2 = inl::impl::EncodeProduce(c2, char());
auto u3 = inl::impl::EncodeProduce(c3, char());
auto u4 = inl::impl::EncodeProduce(c4, char());
REQUIRE(u1exp == u1);
REQUIRE(u2exp == u2);
REQUIRE(u3exp == u3);
REQUIRE(u4exp == u4);
}
TEST_CASE("Encode UCS4->UTF-16 character", "[StringEncode]") {
// Examples from wikipedia: https://en.wikipedia.org/wiki/UTF-16
char32_t c1 = 0x20AC;
char32_t c2 = 0x24B62;
std::array<char16_t, 2> u1exp = { 0x20AC, 0 };
std::array<char16_t, 2> u2exp = { 0xD852, 0xDF62 };
auto u1 = inl::impl::EncodeProduce(c1, char16_t());
auto u2 = inl::impl::EncodeProduce(c2, char16_t());
REQUIRE(u1exp == u1);
REQUIRE(u2exp == u2);
}
TEST_CASE("Decode UTF-16->UCS4 character", "[StringEncode]") {
std::array<char16_t, 2> u1in = { 0x20AC, 0 };
std::array<char16_t, 2> u2in = { 0xD852, 0xDF62 };
auto [c1, end1] = impl::EncodeConsume(u1in.data(), u1in.data() + u1in.size());
auto [c2, end2] = impl::EncodeConsume(u2in.data(), u2in.data() + u2in.size());
REQUIRE(c1 == 0x20AC);
REQUIRE(c2 == 0x24B62);
}
TEST_CASE("Decode UTF-8->UCS4 character", "[StringEncode]") {
// Examples from wikipedia: https://en.wikipedia.org/wiki/UTF-8
std::array<char, 4> u1in = { char(0x24), char(0), char(0), char(0) };
std::array<char, 4> u2in = { char(0xC2), char(0xA2), char(0), char(0) };
std::array<char, 4> u3in = { char(0xE2), char(0x82), char(0xAC), char(0) };
std::array<char, 4> u4in = { char(0xF0), char(0x90), char(0x8D), char(0x88) };
auto [c1, end1] = impl::EncodeConsume(u1in.data(), u1in.data() + u1in.size());
auto [c2, end2] = impl::EncodeConsume(u2in.data(), u2in.data() + u2in.size());
auto [c3, end3] = impl::EncodeConsume(u3in.data(), u3in.data() + u3in.size());
auto [c4, end4] = impl::EncodeConsume(u4in.data(), u4in.data() + u4in.size());
REQUIRE(c1 == 0x0024);
REQUIRE(c2 == 0x00A2);
REQUIRE(c3 == 0x20AC);
REQUIRE(c4 == 0x10348);
}
TEST_CASE("Transcode string UTF-8 -> UTF-32 -> UTF-8", "[StringEncode]") {
using namespace std::string_literals;
std::string original = (const char*)u8"На берегу пустынных волн";
std::u32string interm = EncodeString<char32_t>(original);
std::string recoded = EncodeString<char>(interm);
REQUIRE(original == recoded);
}
TEST_CASE("Transcode string UTF-16 -> UTF-32 -> UTF-16", "[StringEncode]") {
std::u16string original = u"На берегу пустынных волн";
std::u32string interm = EncodeString<char32_t>(original);
std::u16string recoded = EncodeString<char16_t>(interm);
REQUIRE(original == recoded);
} | true |
13d208e93bf63a8dc97234860b33704f68fa92d2 | C++ | liangZ97/LCoffer | /LC 二叉树 112 路径总和/LC 二叉树 112 路径总和.cpp | UTF-8 | 2,746 | 3.65625 | 4 | [] | no_license | #include<iostream>
#include<queue>
using namespace std;
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) {}
};
/*
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,
这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例: 给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
*/
//DFS
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root)
return false;
if (!root->left && !root->right)
return sum - root->val == 0;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
class Solution {
bool dfs(TreeNode* root, int sum) {
if (!root)
return false;
if (!root->left && !root->right)
return sum - root->val == 0;
return dfs(root->left, sum - root->val) || dfs(root->right, sum - root->val);
}
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root)
return false;
//if (!root->left && !root->right)
// return sum - root->val == 0;
//return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
return dfs(root, sum);
}
};
//BFS
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root)
return false;
queue<TreeNode*> quTree;
queue<int> quSum;
quTree.push(root);
quSum.push(root->val);
while (!quTree.empty()) {
auto cur = quTree.front();
quTree.pop();
auto curSum = quSum.front();
quSum.pop();
if (!cur->left && !cur->right) {
//return sum == curSum; //这样碰到第一个分支直接返回了
if (sum == curSum)
return true;
continue;
}
if (cur->left) {
quTree.push(cur->left);
quSum.push(cur->left->val + curSum);
}
if (cur->right) {
quTree.push(cur->right);
quSum.push(cur->right->val + curSum);
}
}
return false;
}
}; | true |
53785960ab10621902afe78ca64451a54b0c719f | C++ | DecimatorMind/Leetcode-CPP-Answers | /Leetcode CPP Answers/Matrix_Diagonal_Sum.cpp | UTF-8 | 590 | 3.078125 | 3 | [] | no_license | //
// Matrix_Diagonal_Sum.cpp
// Leetcode CPP Answers
//
// Created by Pranjal Bhardwaj on 22/09/20.
// Copyright © 2020 Pranjal Bhardwaj. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int matrix_diagonal_sum(){
vector<vector<int>> mat {{}};
int result {};
for(int i = 0;i < mat.size();i++){
for(int j = 0;j < mat[i].size();j++){
if(i == j){
result += mat[i][j];
} else if(i+j == mat.size()-1){
result += mat[i][j];
}
}
}
cout << result << endl;
return 0;
}
| true |
4a8bb1e18f1eab930aef23169f735ec741fd982f | C++ | MMrFalcon/ProgramowanieGrafiki | /GraphicProgramSolution/InverseMatrix/InverseMatrixApp.cpp | WINDOWS-1250 | 6,249 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int endProgram() {
char end = 'p';
cout <<endl<< "q aby zakonczyc" << endl;
while (true) {
cin >> end;
if (end == 'q')
break;
else
continue;
}
return 0;
}
vector<float> buildMatrix(int size) {
vector<float> matrix(size*size);
int counter = 0;
int index = 0;
cout << "Budowa macierzy " << size << "x" << size << endl;
cout << "q aby przerwac" << endl;
while (counter < size) {
int column = 1;
while (column < size + 1) {
float input;
cout << "podaj " << column << " liczbe " << counter + 1 << " wiersza macierzy" << endl;
cin >> input;
if (cin.fail()) {
cin.clear();
break;
}
matrix[index] = input;
++index;
++column;
}
++counter;
}
return matrix;
}
vector <float> inverseMatrix2(vector <float> matrix) {
float determinant;
determinant = (matrix[0] - matrix[3]) * (matrix[1] - matrix[2]);
if (determinant == 0) {
cout << "wyznacznik rowny 0 nie mozna policzyc macierzy odwrotnej" << endl;
endProgram();
}
vector <float> matrixComplements(matrix.size());
int index = matrix.size() - 1; //ostatni index macierzy jako pierwszy wyznacznik
for (size_t i = 0; i < matrixComplements.size(); i++) {
i % 2 == 0 ? matrixComplements[i] = matrix[index] * 1 : matrixComplements[i] = matrix[index] * -1;
--index;
}
vector <float> matrixTranspozition(matrix.size());
matrixTranspozition[0] = matrixComplements[0];
matrixTranspozition[1] = matrixComplements[2];
matrixTranspozition[2] = matrixComplements[1];
matrixTranspozition[3] = matrixComplements[3];
vector <float> inversedMatrix(matrix.size());
for (size_t i = 0; i < matrix.size(); i++)
inversedMatrix[i] = matrixTranspozition[i] / determinant;
return inversedMatrix;
}
vector <float> inverseMatrix3(vector <float> matrix, int numberOfItemInRow) {
float determinant;
float leftSide = 0; //najpierw z lewej strony dodawanie
float rightSide = 0; //potem z prawej strony dodawanie
//metoda Sarrusa
vector<float> additionalMatrix(matrix.size() + 6);
for (size_t i = 0; i < matrix.size(); i++) {
additionalMatrix[i] = matrix[i];
}
int index = 0;
for (size_t i = matrix.size(); i < additionalMatrix.size(); i++) {
additionalMatrix[i] = matrix[index];
++index;
}
cout << "Dodatkowa macierz do metody Sarrusa" << endl << endl;
int breakLine = 1;
for (size_t i = 0; i < additionalMatrix.size(); i++) {
if (breakLine % 3 == 0)
cout << "\n";
cout << additionalMatrix[i] << " ";
++breakLine;
}
//liczymy z lewej strony po przekatnych dlatego skoki o 3
for (size_t i = 0; i < matrix.size(); i= i + 3) { //ograniczenie macierzy podstawowej poniewa ostatni indeks pobierany jest z niej
leftSide += (additionalMatrix[i] * additionalMatrix[i + 4] * additionalMatrix[i + 8]);
}
for (size_t i = 2; i < matrix.size(); i = i + 3) {
rightSide += (additionalMatrix[i] * additionalMatrix[i + 2] * additionalMatrix[i + 4]);
}
determinant = leftSide - rightSide;
if (determinant == 0) {
cout << "wyznacznik rowny 0 nie mozna policzyc macierzy odwrotnej" << endl;
endProgram();
}
cout << endl << "wyznacznik " << determinant << endl << endl;
vector <float> matrixComplements(matrix.size());
//obliczanie dopelnien za pomoca minorow
matrixComplements[0] = 1 * (matrix[4] * matrix[8] - matrix[5] * matrix[7]);
matrixComplements[1] = -1 * (matrix[3] * matrix[8] - matrix[5] * matrix[6]);
matrixComplements[2] = 1 * (matrix[3] * matrix[7] - matrix[4] * matrix[6]);
matrixComplements[3] = -1 * (matrix[1] * matrix[8] - matrix[2] * matrix[7]);
matrixComplements[4] = 1 * (matrix[0] * matrix[8] - matrix[2] * matrix[6]);
matrixComplements[5] = -1 * (matrix[0] * matrix[7] - matrix[1] * matrix[6]);
matrixComplements[6] = 1 * (matrix[1] * matrix[5] - matrix[2] * matrix[4]);
matrixComplements[7] = -1 * (matrix[0] * matrix[5] - matrix[2] * matrix[3]);
matrixComplements[8] = 1 * (matrix[0] * matrix[4] - matrix[1] * matrix[3]);
cout << "macierz dopelnien:" << endl;
breakLine = 0;
for (size_t i = 0; i < matrixComplements.size(); i++) {
if (breakLine % 3 == 0)
cout << "\n";
cout << matrixComplements[i] << " ";
++breakLine;
}
//transponowanie
vector <float> matrixTranspozition(matrix.size());
matrixTranspozition[0] = matrixComplements[0];
matrixTranspozition[1] = matrixComplements[3];
matrixTranspozition[2] = matrixComplements[6];
matrixTranspozition[3] = matrixComplements[1];
matrixTranspozition[4] = matrixComplements[4];
matrixTranspozition[5] = matrixComplements[7];
matrixTranspozition[6] = matrixComplements[2];
matrixTranspozition[7] = matrixComplements[5];
matrixTranspozition[8] = matrixComplements[8];
cout << endl << "macierz transponowana:" << endl;
breakLine = 1;
for (size_t i = 0; i < matrixTranspozition.size(); i++) {
if (breakLine % 3 == 0) {
cout << "\n";
}
cout << matrixTranspozition[i] << " ";
++breakLine
}
//macierz odwrotna
vector <float> inversedMatrix(matrix.size());
for (size_t i = 0; i < matrix.size(); i++) {
inversedMatrix[i] = matrixTranspozition[i] / determinant;
}
return inversedMatrix;
}
int main() {
int matrixSize;
cout << "Podaj rozmiar macierzy, mozliwa jedynie kwadratowa q konczy program" << endl;
cin >> matrixSize;
if (cin.fail()) {
cin.clear();
}
vector <float> matrix(matrixSize*matrixSize);
matrix = buildMatrix(matrixSize);
int breakPoint = 1;
for (int i = 0; i < matrixSize * matrixSize; i++) {
cout << matrix[i] << " ";
if (breakPoint == matrixSize)
{
cout << endl;
breakPoint = 0;
}
++breakPoint;
}
if (matrixSize == 1) {
cout << matrix[1] << endl;
endProgram();
}
if (matrixSize == 2) {
matrix = inverseMatrix2(matrix);
int breakLine = 1;
for (size_t i = 0; i < matrix.size(); i++) {
if (breakLine % 2 == 0)
cout << endl;
cout << matrix[i] << " ";
++breakLine;
}
endProgram();
}
else if(matrixSize == 3) {
matrix = inverseMatrix3(matrix, matrixSize);
int breakLine = 1;
for (size_t i = 0; i < matrix.size(); i++) {
if (breakLine % 2 == 0)
cout << endl;
cout << matrix[i] << " ";
++breakLine;
}
endProgram();
}
else {
endProgram();
}
return 0;
}
| true |
4abe26b610718a5a0585304344a404e99ebda3d7 | C++ | nimaPostanchi/project-midi-visualization | /midi-visualization/readLenghtInteger.cpp | UTF-8 | 393 | 3.03125 | 3 | [] | no_license | #include "io.h"
uint32_t read_variable_length_integer(std::istream& in)
{
uint8_t byte = read_byte(in);
uint8_t msb = byte >> 7;
uint8_t msb_remover = 0x7f;
uint32_t result = byte & msb_remover;
while (msb == 1) {
uint8_t next_byte = read_byte(in);
msb = next_byte >> 7;
next_byte = next_byte & msb_remover;
result = (result << 7) | next_byte;
}
return result;
} | true |
4f523aeb85ab38cb4d8f4c8634b6482c79c0edc5 | C++ | lulu920819/PracticeCode | /BookPrint/Book.h | UTF-8 | 935 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include<sstream>
using namespace std;
class Book
{
public:
Book(string format)
{
this->book_format = format;
setPageStyle(book_format);
this->FirstLineChar = '=';
this->cur_line = 0;
this->isNewPage=this->isNewLine = true;
};
~Book(){};
void Print_book(ifstream &input,ofstream &output);
private:
string book_format;
int line_max;
int width_max;
int cur_line;
char FirstLineChar;
bool isNewPage;
bool isNewLine;
//output page first line
void print_Page1stLine(ofstream &output);
//output empty line
void print_EmptyLine(ofstream &output);
// set page style A4 A3
void setPageStyle(string book_format );
void readLine(ofstream &output,string line);
void print_Line(ofstream &output,string s);
string RemovePreAndLastSpace(string str);
void string_replace(string&s1,const string&s2,const string&s3);
int Book::find_split(string str);
};
| true |
0f605dc23ccc1faa8b99194b101fde35248ba515 | C++ | Michael-Nath-HS/MKS21X | /ccc/clion/algo/grading_students.cpp | UTF-8 | 860 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> gradingStudents(vector<int> grades) {
vector<int> newGrades;
for (int i = 0; i < grades.size(); i++) {
if (grades[i] < 38) newGrades.push_back(grades[i]);
else {
int nextMult = ceil(grades[i] / 5.0) * 5;
if (fabs(nextMult - grades[i]) < 3) newGrades.push_back(nextMult);
else newGrades.push_back(grades[i]);
}
}
return newGrades;
}
int main() {
vector<int> inpt;
inpt.push_back(73);
inpt.push_back(67);
inpt.push_back(38);
inpt.push_back(33);
cout << ceil(73.0 / 5) << endl;
for (int x : inpt) {
cout << x << " ";
}
cout << endl;
vector<int> ans = gradingStudents(inpt);
for (int x : ans) {
cout << x << " ";
}
cout << endl;
} | true |
20607d2ecf561bd9dcb03c8a32df82af135c9dbc | C++ | manaccac/Piscine_CPP | /Day04/ex01/Bouftou.cpp | UTF-8 | 579 | 2.96875 | 3 | [] | no_license | #include "Bouftou.hpp"
bouftou::bouftou() : Enemy(50, "Bouftou lvl 6 ")
{
std::cout << "Bouftou lvl 6 appears in your zone " << std::endl;
}
bouftou::bouftou(bouftou const &s_bouftou) : Enemy(s_bouftou.getHP(), s_bouftou.getType())
{
std::cout << "Bouftou lvl 6 appears in your zone " << std::endl;
}
bouftou &bouftou::operator=(bouftou const &s_bouftou)
{
Enemy::operator=(s_bouftou);
std::cout << "Bouftou lvl 6 appears in your zone " << std::endl;
return (*this);
}
bouftou::~bouftou()
{
std::cout << "You killed the bouftou lvl 6 you gain a level " << std::endl;
}
| true |
9bf3ccf11a8b3631464a658681ed34124ea84422 | C++ | Scorbutics/Wallhack | /src/WallhackCPP/HWNDStack.cpp | UTF-8 | 896 | 3.28125 | 3 | [] | no_license | #include <cstdlib>
#include "HWNDStack.h"
HWNDStack* hwndStack = NULL;
int stackLength = 0;
HWNDStack* CreateWindowTransparencyElement(HWND hwnd, int opacity)
{
HWNDStack* result = (HWNDStack*) calloc(1, sizeof(HWNDStack));
result->hwnd = hwnd;
result->next = NULL;
result->opacity = opacity;
return result;
}
HWNDStack* PushWindowTransparencyStack(HWNDStack** stack, HWND hwnd, int opacity)
{
HWNDStack* el = CreateWindowTransparencyElement(hwnd, opacity);
el->next = (*stack) ;
*stack = el;
stackLength++;
return (*stack);
}
HWNDStack* PopWindowTransparencyStack(HWNDStack** stack)
{
if(*stack == NULL)
{
return NULL;
}
HWNDStack* nextEl = (*stack)->next;
free(*stack);
*stack = nextEl;
return *stack;
}
void ClearWindowTransparencyStack(HWNDStack ** stack)
{
while(PopWindowTransparencyStack(stack));
}
| true |
52e619d52cd7f2acb627c2e6ff8fb6a6610d210c | C++ | s3rvac/talks | /2017-03-07-Introduction-to-Python/examples/06-duck-typing.cpp | UTF-8 | 588 | 3.734375 | 4 | [
"BSD-3-Clause"
] | permissive | // In C++, templates provide a duck-typing-like behavior.
//
// Based on https://en.wikipedia.org/wiki/Duck_typing#In_C.2B.2B
//
// $ g++ 06-duck-typing.cpp -o 06-duck-typing
// $ ./06-duck-typing
#include <iostream>
class Duck {
public:
void quack() { std::cout << "quack quack\n"; }
};
class Person {
public:
void quack() { std::cout << "faked quack quack\n"; }
};
template<typename T>
void in_the_forest(T& duck) {
duck.quack();
}
int main() {
Duck duck;
Person person;
in_the_forest(duck); // prints "quack quack"
in_the_forest(person); // prints "faked quack quack"
}
| true |
fffa1e369099a5b7c2f5b9d1463262b3c675cbb6 | C++ | AlinCioabla/SQLSystem | /SQLSystem/SQLSystem/ASTNode.h | UTF-8 | 715 | 2.921875 | 3 | [] | no_license | #pragma once
#include "IToken.h"
class Visitor;
class AstNode;
using AstNodePtr = shared_ptr<AstNode>;
class AstNode
{
public:
AstNode(TokenPtr & aToken)
: mToken(move(aToken))
{
}
AstNode() = default;
// Returns the left child
AstNodePtr & GetLeft() { return mLeft; };
// Returns the right child
AstNodePtr & GetRight() { return mRight; };
// Returns the token
IToken * GetToken() const { return mToken.get(); };
void SetToken(TokenPtr & aToken);
void SetLeft(const AstNodePtr & aLeft);
void SetRight(const AstNodePtr & aRight);
virtual void Accept(Visitor & aVisitor) = 0;
virtual ~AstNode();
private:
TokenPtr mToken;
AstNodePtr mLeft;
AstNodePtr mRight;
};
| true |
92da01665214264f49ecc3c9f20a8a4901d86f66 | C++ | bollu/competitive | /codeforces/466c/main.cpp | UTF-8 | 1,747 | 2.984375 | 3 | [] | no_license | //http://codeforces.com/problemset/problem/466/C
#include <iostream>
#include <assert.h>
#include <map>
using namespace std;
#define endl '\n'
// ~10^8 operations allowed for TLE
static const int MAX_LEN = 5 * 100000;
int n;
long as[MAX_LEN + 1];
long partial_sums[MAX_LEN + 1];
long reverse_partial_sums[MAX_LEN + 1];
long sum_23_ahead[MAX_LEN + 1];
long sum(int a, int b) {
assert (a >= 0 && b >= 0);
assert(a <= n && b <= n);
assert(b >= a);
return partial_sums[b] - partial_sums[a - 1];
}
template<typename T>
void print_arr(T *arr, size_t len, const char *name="") {
cout<<"\n"<<name<<"[";
for(int i = 0; i < len; i++) {
cout<<arr[i]<<" ";
}
cout<<"]";
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cin>>n;
for(int i = 1; i <= n; i++) {
cin>>as[i];
partial_sums[i] = partial_sums[i - 1] + as[i];
}
partial_sums[n] = partial_sums[n - 1] + as[n];
const long total = partial_sums[n];
//cout<<"\ntotal: "<<total;
reverse_partial_sums[n] = as[n];
for(int i = n - 1; i >= 1; i--) {
reverse_partial_sums[i] = reverse_partial_sums[i + 1] + as[i];
}
//print_arr(partial_sums, n + 1, "partial sums");
sum_23_ahead[n] = 0;
for(int i = n - 1; i >= 1; i--) {
bool is_23 = partial_sums[i] * 3 == (total * 2);
//cout<<"\nis_23: "<<partial_sums[i]<<" : "<<is_23;
sum_23_ahead[i] = sum_23_ahead[i + 1] + (is_23 ? 1 : 0);
}
//print_arr(sum_23_ahead, n + 1, "sum 2/3 ahead");
long long count = 0;
for(int i = 1; i <= n - 2; i++) {
if (partial_sums[i] * 3 == total) {
count += sum_23_ahead[i + 1];
}
}
cout<<count;
return 0;
}
| true |
93c5ee7bf6d7776b1b78d241e0549e29454c76cb | C++ | KlimaVand/Nitroscape | /trunk/FieldOperations/Route_3A/src/layerClass.h | UTF-8 | 2,297 | 2.96875 | 3 | [] | no_license | // Class: layerClass //ANSI C++
#include <common.h>
#include <clonlist.h>
#ifndef __LAYERCLASS_H //Required for current class
#define __LAYERCLASS_H
#ifndef __IOSTREAM_H //Required for cin and cout
#include <iostream.h>
#endif
//! Describes a single layer in the soil
class layerClass
{
private:
protected:
//! Depth below the soil surface of the lower boundary of the layer (millimetres)
double z_lower;
//! Plant-available water content of the layer at field capacity
double fieldCapacity;
//! Thickness of the layer (millimetres)
double thickness;
public:
//!Default constructor
layerClass () {};
//! Copy constructor for this class
/*!
\param alayerClass pointer to the instance that should be copied
*/
// constructor
layerClass::layerClass(const layerClass& alayerClass) ;
//!Read the parameters associated with a single layer
/*!
\param afile pointer to the input file
\param z_upper depth below the soil surface of the upper boundary of the layer
*/
void ReadParameters (fstream * afile, double z_upper) ;
//! Initialise an instance of this class
void Initialise () ;
//!Destructor
~ layerClass ( ); //Destructor - Delete any pointer data members that used new in constructors
//!Get accessor function for non-static attribute data member
double getz_lower() const { return z_lower;}
//!Get accessor function for non-static attribute data member
double getfieldCapacity() const { return fieldCapacity;}
//!Get accessor function for non-static attribute data member
double getthickness() const { return thickness;}
//!Set accessor function for non-static attribute data member
void setz_lower (double az_lower) { z_lower = az_lower;}
//!Set accessor function for non-static attribute data member
void setfieldCapacity (double afieldCapacity) { fieldCapacity = afieldCapacity;}
//!Set accessor function for non-static attribute data member
void setthickness (double athickness) { thickness = athickness;}
};
#endif
| true |
ecf52e89aad57086585594073fe93d29bed8e5e2 | C++ | khokhlov/mlib | /mlib/mlib_ops.h | UTF-8 | 4,988 | 2.515625 | 3 | [] | no_license | /*
* Author: Nikolay Khokhlov <k_h@inbox.ru>, (C) 2012
*/
#ifndef MLIB_OPS_H
#define MLIB_OPS_H
#include <cmath>
#include "mlib_core.h"
#ifdef USE_LAPACK
extern "C" {
extern void sgeev_(char* jobvl, char* jobvr, int* n, float* a,
int* lda, float* wr, float* wi, float* vl, int* ldvl,
float* vr, int* ldvr, float* work, int* lwork, int* info);
extern void dgeev_(char* jobvl, char* jobvr, int* n, double* a,
int* lda, double* wr, double* wi, double* vl, int* ldvl,
double* vr, int* ldvr, double* work, int* lwork, int* info);
extern void dgetrf_(int* M, int *N, double* A, int* lda, int* IPIV, int* INFO);
extern void dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO);
};
#endif
namespace mlib_ops {
/*
* x = y.
*/
template <int size, typename T>
inline void copy(T *x, const T *y) { for (int i = 0; i < size; i++) x[i] = y[i]; }
/*
* x[i] = v.
*/
template <int size, typename T>
inline void set(T *x, const T v) { for (int i = 0; i < size; i++) x[i] = v; }
/*
* x[i] = 0.0.
*/
template <int size, typename T>
inline void zero(T *x) { set<size, T>(x, 0); }
/*
* x = a * x.
*/
template <int size, typename T>
inline void scale(T *x, const T a) { for (int i = 0; i < size; i++) x[i] *= a; }
/*
* x = x / a.
*/
template <int size, typename T>
inline void iscale(T *x, const T a) { for (int i = 0; i < size; i++) x[i] /= a; }
/*
* (x, y).
*/
template <int size, typename T>
inline T dot(const T *x, const T *y) { T t = 0; for (int i = 0; i < size; i++) t += x[i] * y[i]; return t; }
/*
* |x|^2.
*/
template <int size, typename T>
inline T normsq(const T *x) { return dot<size, T>(x, x); }
/*
* |x|.
*/
template <int size, typename T>
inline T norm(const T *x) { return std::sqrt(normsq<size, T>(x)); }
/*
* x += y.
*/
template <int size, typename T>
inline void add(T *x, const T *y) { for (int i = 0; i < size; i++) x[i] += y[i]; }
/*
* x -= y.
*/
template <int size, typename T>
inline void sub(T *x, const T *y) { for (int i = 0; i < size; i++) x[i] -= y[i]; }
/*
* x *= y.
*/
template <int size, typename T>
inline void mul(T *x, const T *y) { for (int i = 0; i < size; i++) x[i] *= y[i]; }
/*
* x /= y.
*/
template <int size, typename T>
inline void div(T *x, const T *y) { for (int i = 0; i < size; i++) x[i] /= y[i]; }
/*
* x = max(a, b).
*/
template <int size, typename T>
inline void max(T *x, const T *a, const T *b) { for (int i = 0; i < size; i++) x[i] = std::max(a[i], b[i]); }
/*
* x = min(a, b).
*/
template <int size, typename T>
inline void min(T *x, const T *a, const T *b) { for (int i = 0; i < size; i++) x[i] = std::min(a[i], b[i]); }
/*
* Matrix product.
* C = A * B
*/
template<int m, int n, int k, typename T>
inline void mat_prod(const T *A, const T *B, T *C) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < k; j++) {
T t = 0;
for (int l = 0; l < n; l++) t += A[l + i * n] * B[j + k * l];
C[i * k + j] = t;
}
}
}
/*
* Eigenproblem.
*/
template <int N>
inline void eigenproblem(float *A, float *wr, float *wi, float *vl, float *vr) {
#ifdef USE_LAPACK
int n = N, lda = N, ldvl = N, ldvr = N, info, lwork;
float *work;
float wkopt;
char V = 'V';
/* Query and allocate the optimal workspace */
lwork = -1;
sgeev_(&V, &V, &n, A, &lda, wr, wi, vl, &ldvl, vr, &ldvr, &wkopt, &lwork, &info);
lwork = (int)wkopt;
work = new float[lwork];
/* Solve eigenproblem */
sgeev_(&V, &V, &n, A, &lda, wr, wi, vl, &ldvl, vr, &ldvr, work, &lwork, &info);
delete [] work;
/* Check */
MLIB_DYNAMIC_CHECK(info <= 0 && "Eigenproblem failed.");
#else
MLIB_DYNAMIC_CHECK(false && "Compile with flag -DUSE_LAPACK");
#endif
}
template <int N>
inline void eigenproblem(double *A, double *wr, double *wi, double *vl, double *vr) {
#ifdef USE_LAPACK
int n = N, lda = N, ldvl = N, ldvr = N, info, lwork;
double *work;
double wkopt;
char V = 'V';
/* Query and allocate the optimal workspace */
lwork = -1;
dgeev_(&V, &V, &n, A, &lda, wr, wi, vl, &ldvl, vr, &ldvr, &wkopt, &lwork, &info);
lwork = (int)wkopt;
work = new double[lwork];
/* Solve eigenproblem */
dgeev_(&V, &V, &n, A, &lda, wr, wi, vl, &ldvl, vr, &ldvr, work, &lwork, &info);
delete [] work;
/* Check */
MLIB_DYNAMIC_CHECK(info <= 0 && "Eigenproblem failed.");
#else
MLIB_DYNAMIC_CHECK(false && "Compile with flag -DUSE_LAPACK");
#endif
}
template <int N>
inline void inverse(double *A) {
#ifdef USE_LAPACK
int n = N, info, lwork = N * N;
int *ipiv = new int[N + 1];
double *work;
work = new double[lwork];
dgetrf_(&n, &n, A, &n, ipiv, &info);
dgetri_(&n, A, &n, ipiv, work, &lwork, &info);
delete [] work;
delete [] ipiv;
/* Check */
MLIB_DYNAMIC_CHECK(info <= 0 && "Inverse failed.");
#else
MLIB_DYNAMIC_CHECK(false && "Compile with flag -DUSE_LAPACK");
#endif
}
};
#endif // MLIB_OPS_H
| true |
877003fcaa7fb2edf9adaffa1e9496d971ed1925 | C++ | shenzhiqiang1997/CppStudy | /CppStudy11.cpp | UTF-8 | 3,831 | 3.40625 | 3 | [] | no_license | // CppStudy11.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <time.h>
using namespace std;
class Quadrangle {
protected:
string name;
public:
virtual double area()=0;
virtual void draw() = 0;
virtual void what() {
cout << name << endl;
};
};
class Parallelogram :public Quadrangle {
protected:
double width;
double height;
public:
Parallelogram() {
width = rand() % 30;
height = rand() % 30;
name = "Parallelogram";
}
virtual double Width() {
return width;
}
virtual double Height() {
return height;
}
double area() {
return width*height;
}
void draw() {
cout << "length=" << width << "," << "height=" << height << endl;
}
};
class Rect:public Parallelogram {
public:
Rect() {
name = "Rectangle";
}
};
class Square :public Quadrangle {
private:
double width;
public:
Square() {
width = rand() % 30;
name = "Square";
}
double Width() {
return width;
}
double area() {
return width*width;
}
void draw() {
cout << "length=" << width << endl;
}
};
class Trapezoid :public Parallelogram {
private:
double width2;
public:
Trapezoid() {
width2 = rand()%30;
name = "Trapezoid";
}
double Width2() {
return width2;
}
double area() {
return (width+width2)*height/2;
}
void draw() {
cout << "first length=" << width << "," << "second length=" << width2 << "," << "height=" << height << endl;
}
};
class Diamond:public Parallelogram {
public:
Diamond() {
name = "Diamond";
}
double area() {
return width*height/2;
}
void draw() {
cout << "first diagonal=" << width << "," << "second diagonal=" << height << endl;
}
};
template<typename T>
class List{
private:
class Node {
private:
T data;
Node* next;
friend class List;
public:
Node(const T& data) {
this->data = data;
}
};
Node* first, *last;
public:
List() {
}
~List() {
Node* p = first;
Node* dp;
while (p)
{
dp = p;
p = p->next;
delete dp;
}
}
int size() {
int size = 0;
Node* p = first;
while (p) {
size += 1;
p = p->next;
}
return size;
}
void push_back(const T& data) {
Node* node = new Node(data);
if (last==NULL)
{
first = last = node;
}
else {
last->next = node;
last = node;
}
}
T& operator[](int index) {
if (index>=0&&index<size)
{
Node* p = first;
for (int i = 0; i < index; i++) {
p = p->next;
}
return *p;
}
else
{
return NULL;
}
}
void traverse(void (*f)(T q)) {
Node* p = first;
while (p) {
f(p->data);
p = p->next;
}
}
void pop_back() {
int size = size();
if (size !=0)
{
if (size==1)
{
delete first;
first = last = null;
}
else {
Node* p = first;
Node* pre;
for (int i = 0; i < size-1; i++) {
p = p->next;
}
pre = p;
p = first;
for (int i = 0; i < size - 1; i++) {
p = p->next;
}
delete p;
last = pre;
}
}
}
};
void learnQuadrangle(Quadrangle* q) {
q->what();
q->draw();
cout << "please caculator the area of the quadrangle:" << endl;
double result;
cin >> result;
if (result==q->area())
{
cout << "result correct" << endl;
}
else {
cout << "result incorrect" << endl;
}
}
int main() {
List<Quadrangle*> quadrangles;
string command;
int choice;
srand((unsigned)time(NULL));
do
{
Quadrangle* q = NULL;
choice = rand() % 5;
switch (choice)
{
case 0:
q=new Rect();
break;
case 1:
q = new Square();
break;
case 2:
q = new Parallelogram();
break;
case 3:
q = new Trapezoid();
break;
case 4:
q = new Diamond();
break;
}
learnQuadrangle(q);
quadrangles.push_back(q);
cout << "enter stop to stop,others will continue" << endl;
cin >> command;
} while (command!="stop");
quadrangles.traverse(&learnQuadrangle);
}
| true |
e4d83f7e3008917be8161e0ffdabd1a074e9b873 | C++ | gohar-malik/Stream-Cipher-Cryptanalysis | /RC4.cpp | UTF-8 | 1,843 | 3.578125 | 4 | [] | no_license | #include "RC4.h"
RC4::RC4()
{
}
unsigned char * RC4::encrypt(unsigned char *m, unsigned char *t)
{
message = m;
key = t;
encrypted = new unsigned char[strlen((char*)message) + 1];
//making a new array in the heap
key_scheduling_algorithm();
PRG_algorithm();
return encrypted;
}
void RC4::key_scheduling_algorithm()
{
int i, j = 0, k;
//variables for loops
int K[256];
//array that will be filled from letters from the key
//it is different for different pass keys
for (i = 0; i < 256; i++)
{
S[i] = i;
//storing ascending numbers in the array
K[i] = key[i % strlen((char*)key)];
//array will contain ASCII values of letters from the key
}
for (i = 0; i < 256; i++)
{
j = (j + S[i] + K[i]) % 256;
//generates an index for swapping
k = S[i];
S[i] = S[j];
S[j] = S[i];
//swapping the values at position i and j
}
}
void RC4::PRG_algorithm()
{
int i = 0, j = 0;
//for storing the indexes during swapping
int dummy;
//used during swapping
int k;
//loop variable
int s;
//used for filling encrypted message;
for (k = 0; k < strlen((char*)message); k++)
{
i = (i + 1) % 256;
j = (j + S[i]) % 256;
//generating pseudo random numbers for swapping;
dummy = S[i];
S[i] = S[j];
S[j] = dummy;
//swapping done
s = (S[i] + S[j]) % 256;
//XOR operation
if (S[s] == message[k])
{
encrypted[k] = message[k];
}
else
{
encrypted[k] = S[s] ^ message[k];
}
}
encrypted[k] = '\0';
//marks the end of the message
}
unsigned char* RC4::decrypt(unsigned char *m, unsigned char *k)
{
return encrypt(m, k);
//we have called the encrypt method again because of a basic property of XOR
// A XOR B XOR B
//= A XOR (B XOR B)
//= A XOR 0
//= A
} | true |
0d1ccc9adc3554813f6c2600a237e39e90f5f712 | C++ | garyjohnson/build-button | /firmware/build-button/ButtonApp.cpp | UTF-8 | 620 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "ButtonApp.h"
ButtonApp::ButtonApp() {
}
ButtonApp::~ButtonApp() {
}
void ButtonApp::setup() {
pinMode(PIN_BUTTON, INPUT_PULLUP);
}
bool ButtonApp::update(uint32_t runTime, uint32_t updateDelta) {
if (digitalRead(PIN_BUTTON) == 1) {
timeKeyPressed += updateDelta;
return true;
} else if(timeKeyPressed > 0) {
if(onRelease != NULL) {
onRelease(timeKeyPressed);
}
timeKeyPressed = 0;
return true;
}
return false;
}
void ButtonApp::setReleaseHandler(releaseHandler handler) {
onRelease = handler;
}
uint32_t ButtonApp::getHeldDuration() {
return timeKeyPressed;
}
| true |
9a671858d05fe7e4bf52462634e50338ca74b78d | C++ | cmacdougald/2020SPRING-ITSE1307 | /chp12-example2/chp12-example2/chp12-example2.cpp | UTF-8 | 627 | 2.96875 | 3 | [
"MIT"
] | permissive | // chp12-example2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Card.h"
#include <iostream>
int main()
{
Card objCard = Card();
Card objCard2 = Card(13);
std::cerr << objCard.getValue() << std::endl;
std::cerr << objCard.getSuite() << std::endl;
std::cerr << objCard.getFace() << std::endl;
std::cout << objCard.toString() << std::endl;
std::cout << objCard2.toString() << std::endl;
for (int intIndex = 1; intIndex <= 52; intIndex++) {
Card objCard3 = Card(intIndex);
std::cout << objCard3.toString() << std::endl;
}
return 0;
}
| true |
8524c6d4b6b9bd0e6f458771270eb42727ef93ed | C++ | girishlande/CPlusPlus | /exercise_solutions/58HTML_SVG_Generator.cpp | UTF-8 | 15,837 | 2.515625 | 3 | [] | no_license | // ConsoleApplication18.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/* HTML CODE GENERATOR FOR FOLLOWING GRAPH
ypad
(x1,y1)
| _ _ param data
| _ _ | variable data
| | |
| | |
| | |
| | |
| | |
| * _
| | V
| O |
<xpad> | | |
| + |
| | |
| | |
| | |
| | |
| --- ---
|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
(ox,oy) (x2,y2)
graph width
Determine graph origin (ox,oy) and then compute everything relative to it.
*/
std::string styleBlock = R"html(
<style>
.iconsize {
width: 24;
height: 24;
}
.midiconsize {
height: 48;
width: 48;
}
.blueSymbol {
border: 1px solid #4571c4;
fill: #4571c4;
}
.greenSymbol {
border: 1px solid green;
fill: green;
}
.blueLineSymbol {
stroke: #4571c4;
stroke-width: 2;
}
.greenLineSymbol {
stroke: green;
stroke-width: 2;
}
.greybarSymbol {
border: 1px solid black;
fill: lightgrey;
stroke-width: 1;
stroke: rgb(0,0,0);
}
.darkgreybarSymbol {
border: 1px solid black;
fill: darkgray;
stroke-width: 1;
stroke: rgb(0,0,0);
}
td {
padding-bottom: 25px;
text-align:right;
font-family:Calibri;
font-size: 20px;
}
.names {
font-weight: bold;
}
</style>
)html";
std::string svgdefinitions = R"html(
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
<symbol id="shapes-line" viewBox="0 0 8 8"> <line x1="0" y1="4" x2="8" y2="4" /> </symbol>
<symbol id="shapes-triangle" viewBox="0 0 8 8"> <polygon points="4,1 7,7 1,7" /> </symbol>
<symbol id="shapes-cross" viewBox="0 0 8 8"> <polygon points="2,1 4,3 6,1 7,2 5,4 7,6 6,7 4,5 2,7 1,6 3,4 1,2 " /> </symbol>
<symbol id="shapes-plus" viewBox="0 0 8 8"> <polygon points="2,0 6,0 6,2 8,2 8,6 6,6 6,8 2,8 2,6 0,6 0,2 2,2" /> </symbol>
<symbol id="shapes-circle" viewBox="0 0 8 8"> <circle cx="4" cy="4" r="4" /> </symbol>
<symbol id="shapes-vbar" viewBox="0 0 20 60"> <rect width="20" height="60" /> </symbol>
</svg>
)html";
std::string graphContent = R"html(
<svg width="400" height="600" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- X and Y axis -->
<line class="line1" x1="30" y1="10" x2="30" y2="550" stroke="black" stroke-width="3" />
<line x1="30" y1="550" x2="400" y2="550" stroke="black" stroke-width="3" />
<!-- Legends on Y axis -->
<text x="0" y="450" fill="black" font-weight="bold">1.0</text>
<text x="0" y="350" fill="black" font-weight="bold">1.5</text>
<text x="0" y="250" fill="black" font-weight="bold">2.0</text>
<text x="0" y="150" fill="black" font-weight="bold">2.5</text>
<text x="0" y="50" fill="black" font-weight="bold">3.0</text>
<!-- Reference lines parallel to X axis -->
<line x1="30" y1="450" x2="400" y2="450" stroke="black" stroke-width="1" />
<line x1="30" y1="350" x2="400" y2="350" stroke="black" stroke-width="1" />
<line x1="30" y1="250" x2="400" y2="250" stroke="black" stroke-width="1" />
<line x1="30" y1="150" x2="400" y2="150" stroke="black" stroke-width="1" />
<line x1="30" y1="50" x2="400" y2="50" stroke="black" stroke-width="1" />
<!-- Delta Rectangles -->
<rect x="200" y="100" width="100" height="300" stroke="black" stroke-width="1" fill="grey" />
<rect x="220" y="140" width="60" height="220" stroke="black" stroke-width="1" fill="#c9ffe5" />
<!-- Parameter Min Max Line -->
<line x1="230" y1="70" x2="230" y2="430" stroke="black" stroke-width="1" />
<line x1="225" y1="70" x2="235" y2="70" stroke="black" stroke-width="1" />
<line x1="225" y1="430" x2="235" y2="430" stroke="black" stroke-width="1" />
<!-- Variable Data Min Max Line -->
<line x1="260" y1="60" x2="260" y2="440" stroke="green" stroke-width="3" />
<line x1="255" y1="60" x2="265" y2="60" stroke="green" stroke-width="3" />
<line x1="255" y1="440" x2="265" y2="440" stroke="green" stroke-width="3" />
<!-- min, max, mod, median symbols on graph -->
<svg x="248" y="270" width="25" height="25"> <use href="#shapes-triangle" class="greenSymbol" /> </svg>
<svg x="218" y="220" width="25" height="25"> <use href="#shapes-plus" class="blueSymbol" /> </svg>
<svg x="218" y="270" width="25" height="25"> <use href="#shapes-circle" class="blueSymbol" /> </svg>
<svg x="218" y="320" width="25" height="25"> <use href="#shapes-cross" class="blueSymbol" /> </svg>
</svg>
)html";
std::string LegendContent = R"html(
<table>
<tr>
<td><span class="names">Variable Data:</span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-line" class="blueLineSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">Mean:</span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-circle" class="blueSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">Median:</span></td>
<td style="text-align:right"><svg x="248" y="270" width="25" height="25"> <use href="#shapes-plus" class="blueSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">Mode:</span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-cross" class="blueSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">+/-1δ: </span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-vbar" class="greybarSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">+/-2δ: </span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-vbar" class="darkgreybarSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">Parameter Data:</span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-line" class="greenLineSymbol" /> </svg></td>
</tr>
<tr>
<td><span class="names">Goal:</span></td>
<td><svg x="248" y="270" width="25" height="25"> <use href="#shapes-triangle" class="greenSymbol" /> </svg></td>
</tr>
</table>
)html";
std::string docHeader = R"html(
<html>
<head>
<title>My SVG experiement</title>
)html";
std::string headCloseBodyOpen = R"html(
</head>
<body>
)html";
std::string tableOpen = R"html(
<table width="600">
<td>
)html";
std::string tableClose = R"html(
</td>
</table>
)html";
std::string tableDataCloseDataOpen = R"html(
</td>
<td>
)html";
std::string bodyCloseDocClose = R"html(
</body>
</html>
)html";
std::string color1 = "#d6dce5";
std::string color2 = "#a5a5a5";
int graphWidth = 500;
int graphHeight = 500;
int xpad = 50;
int ypad = 50;
int svgWidth = graphWidth + xpad;
int svgHeight = graphHeight + ypad;
int ox = xpad;
int oy = ypad + graphHeight;
int x1 = xpad;
int yy1 = ypad;
int x2 = xpad + graphWidth;
int y2 = oy;
int margin = 5;
int num_steps = 6;
int step_size = graphHeight / (num_steps) - margin;
int param_variable_gap = static_cast<int>(graphWidth * 0.05); // gap between parameter line and variable line
int graphCenterX = xpad + graphWidth / 2;
int graphCenterY = ypad + graphHeight / 2;
int paramLine_X = graphCenterX + param_variable_gap/2; // X position for Parameter graph
int variableLine_X = graphCenterX - param_variable_gap/2; // X position for Variable graph
int delta1RectWidth = param_variable_gap * 2; // 2 times Delta 1 rectangle width
int delta2RectWidth = param_variable_gap * 3; // 3 times Delta 2 rectangle width
int delta1_X = graphCenterX - delta1RectWidth / 2; // delta 1 rectangle x position
int delta2_X = graphCenterX - delta2RectWidth / 2; // delta 2 rectangle x position
double param_min = 0.2;
double param_max = 3.4;
double param_goal = 1.8;
//Mean is the average value of the given observations
//Median is the middle value of the given observations (will use this as center)
//Mode is the most repeated value in the given observation
double variable_min = 0.3;
double variable_max = 3.2;
double variable_range = abs(variable_max - variable_min);
double variable_mean = 2.4;
double variable_median = 2.1;
double variable_mode = 1.8;
int delta1RectHeight = static_cast<int>(graphHeight * .4);
int delta2RectHeight = static_cast<int>(graphHeight * .6);
int delta1_Y = graphCenterY - delta1RectHeight / 2;
int delta2_Y = graphCenterY - delta2RectHeight / 2;
int paramLineY1 = oy - graphHeight * .9;
int paramLineY2 = oy - graphHeight * .1;
int pCap = delta1RectWidth / 3;
int variableLineY1 = oy - graphHeight * .95;
int variableLineY2 = oy - graphHeight * .07;
double data_step = 0.5;
double data_start = 1.0;
int symbolWidth = 25;
int symbolHeight = 25;
double YMin = variable_min < param_min ? variable_min : param_min;
double YMax = variable_max > param_max ? variable_max : param_max;
int variableMeanYPosition = 10;
int variableMedianYPosition = 10;
int variableModeYPosition = 10;
int paramGoalYPosition = 10;
void initialiseData() {
// Keep YMin and YMax 10% smaller and greater than input data.
YMin = YMin * 0.9;
YMax = YMax * 1.1;
double YRange = abs(YMax - YMin);
variableMeanYPosition = static_cast<int> ((graphHeight * abs(variable_mean)) / YRange);
variableMedianYPosition = static_cast<int> ((graphHeight * abs(variable_median)) / YRange);
variableModeYPosition = static_cast<int> ((graphHeight * abs(variable_mode)) / YRange);
paramGoalYPosition = static_cast<int> ((graphHeight * abs(param_goal)) / YRange);
}
std::string f(int v) {
return std::to_string(v);
}
#include <sstream>
#include <iomanip> // std::setprecision
std::string fd(double v) {
std::stringstream ss;
ss << std::fixed << std::setprecision(1) << v;
return ss.str();
}
std::string getTableOpenTag() {
std::string tableOpen = "";
tableOpen += "<table width=\"" + f(graphWidth*2) + "\">";
tableOpen += "<td>";
return tableOpen;
}
std::string computeGraph() {
std::string s = "";
s += "<svg width=\"" + f(svgWidth) + "\" height=\"" + f(svgHeight) + "\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">";
s += "<!-- X and Y axis -->";
s += "<line class=\"line1\" x1=\"" + f(x1) + "\" y1=\"" + f(yy1) + "\" x2=\"" + f(ox) + "\" y2=\"" + f(oy) + "\" stroke=\"black\" stroke-width=\"3\" />";
s += "<line class=\"line1\" x1=\"" + f(x2) + "\" y1=\"" + f(y2) + "\" x2=\"" + f(ox) + "\" y2=\"" + f(oy) + "\" stroke=\"black\" stroke-width=\"3\" />";
s += "<!-- Legends on Y axis -->";
int xpos = ox - xpad;
for (int i = 1; i <= num_steps; i++) {
int ypos = oy - (i * step_size);
double value = data_start + i * data_step;
s += "<text x=\"" + f(xpos) + "\" y=\"" + f(ypos) + "\" fill=\"black\" font-weight=\"bold\">" + fd(value) + "</text>";
s += "<line x1=\"" + f(ox) + "\" y1=\"" + f(ypos) + "\" x2=\"" + f(x2) + "\" y2=\"" + f(ypos) + "\" stroke=\"black\" stroke-width=\"1\"/>";
}
s += "<!-- Delta Rectangles -->";
s += "<rect x=\"" + f(delta2_X) + "\" y=\"" + f(delta2_Y) + "\" width=\"" + f(delta2RectWidth) + "\" height=\"" + f(delta2RectHeight) + "\" stroke=\"black\" stroke-width=\"1\" fill=\"" + color2 + "\"/>";
s += "<rect x=\"" + f(delta1_X) + "\" y=\"" + f(delta1_Y) + "\" width=\"" + f(delta1RectWidth) + "\" height=\"" + f(delta1RectHeight) + "\" stroke=\"black\" stroke-width=\"1\" fill=\"" + color1 + "\"/>";
s += "<!-- Parameter Min Max Line -->";
s += "<line x1=\"" + f(paramLine_X) + "\" y1=\"" + f(paramLineY1) + "\" x2=\"" + f(paramLine_X) + "\" y2=\"" + f(paramLineY2) + "\" stroke=\"green\" stroke-width=\"2\"/>";
s += "<line x1=\"" + f(paramLine_X-pCap) + "\" y1=\"" + f(paramLineY1) + "\" x2=\"" + f(paramLine_X+pCap) + "\" y2=\"" + f(paramLineY1) + "\" stroke=\"green\" stroke-width=\"2\"/>";
s += "<line x1=\"" + f(paramLine_X-pCap) + "\" y1=\"" + f(paramLineY2) + "\" x2=\"" + f(paramLine_X+pCap) + "\" y2=\"" + f(paramLineY2) + "\" stroke=\"green\" stroke-width=\"2\"/>";
s += "<!-- Variable Min Max Line -->";
s += "<line x1=\"" + f(variableLine_X) + "\" y1=\"" + f(variableLineY1) + "\" x2=\"" + f(variableLine_X) + "\" y2=\"" + f(variableLineY2) + "\" stroke=\"#4571c4\" stroke-width=\"2\"/>";
s += "<line x1=\"" + f(variableLine_X - pCap) + "\" y1=\"" + f(variableLineY1) + "\" x2=\"" + f(variableLine_X + pCap) + "\" y2=\"" + f(variableLineY1) + "\" stroke=\"#4571c4\" stroke-width=\"2\"/>";
s += "<line x1=\"" + f(variableLine_X - pCap) + "\" y1=\"" + f(variableLineY2) + "\" x2=\"" + f(variableLine_X + pCap) + "\" y2=\"" + f(variableLineY2) + "\" stroke=\"#4571c4\" stroke-width=\"2\"/>";
s += "<svg x=\"" + f(paramLine_X - symbolWidth/2) + "\" y=\"" + f(paramGoalYPosition) + "\" width=\"" + f(symbolWidth) + "\" height=\"" + f(symbolHeight) + "\">" + "<use href=\"#shapes-triangle\" class=\"greenSymbol\"/></svg>";
s += "<svg x=\"" + f(variableLine_X - symbolWidth / 2) + "\" y=\"" + f(variableMeanYPosition) + "\" width=\"" + f(symbolWidth) + "\" height=\"" + f(symbolHeight) + "\">" + "<use href=\"#shapes-circle\" class=\"blueSymbol\"/></svg>";
s += "<svg x=\"" + f(variableLine_X - symbolWidth / 2) + "\" y=\"" + f(variableMedianYPosition) + "\" width=\"" + f(symbolWidth) + "\" height=\"" + f(symbolHeight) + "\">" + "<use href=\"#shapes-plus\" class=\"blueSymbol\"/></svg>";
s += "<svg x=\"" + f(variableLine_X - symbolWidth / 2) + "\" y=\"" + f(variableModeYPosition) + "\" width=\"" + f(symbolWidth) + "\" height=\"" + f(symbolHeight) + "\">" + "<use href=\"#shapes-cross\" class=\"blueSymbol\"/></svg>";
return s;
}
int main()
{
initialiseData();
std::string doc;
doc += docHeader;
doc += styleBlock;
doc += headCloseBodyOpen;
doc += svgdefinitions;
doc += getTableOpenTag();
doc += computeGraph();
doc += tableDataCloseDataOpen;
doc += LegendContent;
doc += tableClose;
doc += bodyCloseDocClose;
std::ofstream out("D:\\output.html");
out << doc;
out.close();
}
| true |
979b05fa8395c0fd16250f5443ef0c526296913a | C++ | SebastienLAURET/UQAR_POO | /TP4/src/main.cpp | UTF-8 | 899 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "Robot.hpp"
#include "Arbitre.hpp"
int main(int, char const **) {
Arbitre arb;
Robot robot;
std::string letterTest, wordTest;
int nbTest;
while (1) {
system("clear");
letterTest = arb.getNewWord();
std::cout << "Les lettres disponible sont :" << letterTest << std::endl;
nbTest = 1;
do {
std::cout << "Faite une proposition [" << nbTest << "/10]" << '\n';
std::getline (std::cin, wordTest);
} while ((wordTest.size() == 0
|| arb.tryWord(wordTest) == -1)
&& nbTest++ < 10);
do {
std::cout << "Les lettres disponible sont :" << letterTest << std::endl;
wordTest = robot.searchWord(letterTest);
std::cout << "Word selectionner par robot : ["<< wordTest <<"]" << '\n';
} while (arb.tryWord(wordTest) == -1);
std::getline (std::cin, wordTest);
}
return 0;
}
| true |
0f506d7a9cc5cba927884b15147dfa44f9816301 | C++ | rahulkr007/sageCore | /trunk/src/c++/ageon/ExtraOutput.cpp | UTF-8 | 5,633 | 2.625 | 3 | [] | no_license | #include <string>
#include <fstream>
#include "numerics/functions.h"
#include "ageon/ExtraOutput.h"
namespace SAGE {
namespace AO {
//===================================
//
// generateFile(...)
//
//===================================
void
ExtraOutput::generateFile(
const SAMPLING::PartitionedMemberDataSample & sample,
const ModelTraitsVector & model_traits,
const std::string & analysis_name,
std::ostream & info)
{
// Grab the individual / sex codes:
const std::string & ind_missing = sample.getMultipedigree().info().individual_missing_code (),
& sex_missing = sample.getMultipedigree().info().sex_code_unknown (),
& sex_male = sample.getMultipedigree().info().sex_code_male (),
& sex_female = sample.getMultipedigree().info().sex_code_female (),
filename = analysis_name;
// Pedigree block info for .inf file:
info << endl
<< "Note:\n"
<< " To use the susceptability traits and survival analysis residuals,\n"
<< " use the additinal output files from this analysis\n"
<< " '" << analysis_name+".par' and '" << analysis_name+".ped'.\n\n";
// Parameter file:
std::ofstream opar((filename+".par").c_str());
opar << "pedigree, file=\"" << (filename+".ped") << "\"\n"
<< "{\n"
<< " delimiter_mode = multiple\n"
<< " delimiters=\" \t\"\n"
<< " individual_missing_value=\"" << ind_missing << "\"\n"
<< " sex_code, male=\"" << sex_male << "\", female=\"" << sex_female << "\", unknown=\"" << sex_missing << "\"\n"
<< " pedigree_id = PED\n"
<< " individual_id = ID\n"
<< " parent_id = P1\n"
<< " parent_id = P2\n"
<< " sex_field = SEX\n"
<< " trait = nt_equal_trait, missing=\"nan\"\n"
<< " trait = nt_equal_residual, missing=\"nan\"\n"
<< " trait = nt_free_trait, missing=\"nan\"\n"
<< " trait = nt_free_residual, missing=\"nan\"\n"
<< " trait = t_equal_trait, missing=\"nan\"\n"
<< " trait = t_equal_residual, missing=\"nan\"\n"
<< " trait = t_free_trait, missing=\"nan\"\n"
<< " trait = t_free_residual, missing=\"nan\"\n"
<< "}\n\n"
<< std::endl
<< std::flush;
// Pedigree file:
std::ofstream o((filename+".ped").c_str());
o << "PED\tID\tP1\tP2\tSEX\t"
<< "nt_equal_trait\t"
<< "nt_equal_residual\t"
<< "nt_free_trait\t"
<< "nt_free_residual\t"
<< "t_equal_trait\t"
<< "t_equal_residual\t"
<< "t_free_trait\t"
<< "t_free_residual\n";
for(size_t i = 0; i < sample.getMultipedigree().member_count(); ++i)
{
// Grab the member reference:
const FPED::Member & member = sample.getMultipedigree().member_index(i);
// Grab sex:
bool male = member.is_male();
bool female = member.is_female();
// Structure:
o << member.pedigree()->name() << "\t"
<< member.name() << "\t"
<< (member.parent1() ? member.parent1()->name() : ind_missing) << "\t"
<< (member.parent2() ? member.parent2()->name() : ind_missing) << "\t";
// Sex:
o << (male ? sex_male : (female ? sex_female : sex_missing)) << "\t";
// Traits:
o << model_traits[NO_TRUNCATION | SUSCEPTIBILITIES_EQUAL] . cond_probs[i] << "\t"
<< model_traits[NO_TRUNCATION | SUSCEPTIBILITIES_EQUAL] . surv_resid[i] << "\t"
<< model_traits[NO_TRUNCATION | SUSCEPTIBILITIES_FREE] . cond_probs[i] << "\t"
<< model_traits[NO_TRUNCATION | SUSCEPTIBILITIES_FREE] . surv_resid[i] << "\t"
<< model_traits[USE_TRUNCATION | SUSCEPTIBILITIES_EQUAL] . cond_probs[i] << "\t"
<< model_traits[USE_TRUNCATION | SUSCEPTIBILITIES_EQUAL] . surv_resid[i] << "\t"
<< model_traits[USE_TRUNCATION | SUSCEPTIBILITIES_FREE] . cond_probs[i] << "\t"
<< model_traits[USE_TRUNCATION | SUSCEPTIBILITIES_FREE] . surv_resid[i];
// Newline:
o << std::endl;
}
}
//===================================
//
// populateModelTraits(...)
//
//===================================
void
ExtraOutput::populateModelTraits(const MemberCovariateCalculator & mcc, ModelTraits & model_traits)
{
model_traits.cond_probs.resize(mcc.getSample().getMultipedigree().member_count(), 0.0);
model_traits.surv_resid.resize(mcc.getSample().getMultipedigree().member_count(), 0.0);
for(size_t i = 0; i < mcc.getSample().getMultipedigree().member_count(); ++i)
{
bool affected = mcc.getSample().getAdjValue(i, "CORE_TRAITS", "affectedness") == 1;
double suscept = mcc.get_genetic_suscept (i),
AO_transf = mcc.get_AO_transf (i),
AE_transf = mcc.get_AE_transf (i),
AO_mean = mcc.get_AO_mean (i),
AO_stdev = mcc.get_AO_stdev (i),
aff_cdf_term = normal_cdf((AO_transf - AO_mean) / AO_stdev),
unaff_cdf_term = normal_cdf((AE_transf - AO_mean) / AO_stdev);
if(affected)
{
model_traits.cond_probs[i] = 1.0;
model_traits.surv_resid[i] = 1.0 - (suscept * aff_cdf_term);
}
else // Not affected
{
model_traits.cond_probs[i] = (suscept - suscept * unaff_cdf_term)
/ (1.0 - suscept * unaff_cdf_term);
model_traits.surv_resid[i] = -suscept * unaff_cdf_term;
}
}
}
} // End namespace AO
} // End namespace SAGE
| true |
d6a5abfc42aeffaaea3dbd2b4d8d06a5be5bb676 | C++ | homsluo/LeetCode | /188. Best Time to Buy and Sell Stock IV.cpp | UTF-8 | 1,846 | 2.921875 | 3 | [] | no_license | //
// Created by homsl on 2020/5/5.
//
int maxProfit(int k, vector<int>& prices) {
if(prices.empty())
return 0;
int n = prices.size();
vector<vector<int>> local(k+1, vector<int>(n, 0));
vector<vector<int>> global(k+1, vector<int>(n, 0));
for(int i = 1; i <= k; i++){
for(int j = 1; j < n; j++){
int diff = prices[j]-prices[j-1];
local[i][j] = max(0, max(local[i][j-1], global[i-1][j-1]))+diff;
global[i][j] = max(global[i][j-1], local[i][j]);
}
}
return global[k][n-1];
}
// -------------------------------------------------------------
// Time: O(nk), Space: O(nk)
int maxProfit(int k, vector<int>& prices) {
if(prices.empty())
return 0;
int n = prices.size();
vector<vector<int>> profit(k+1, vector<int>(n, 0));
for(int t = 1; t <= k; t++){
int prepro = INT32_MIN;
for(int d = 1; d < n; d++){
prepro = max(prepro, profit[t-1][d-1]-prices[d-1]);
profit[t][d] = max(profit[t][d-1], prices[d] + prepro);
}
}
return profit[k][n-1];
}
// --------------------------------------------------------------------
// Time: O(nk), Space: O(n)
int maxProfit(int k, vector<int>& prices) {
if(prices.empty())
return 0;
int n = prices.size();
vector<vector<int>> profit(2, vector<int>(n, 0));
int cur, pre;
for(int t = 1; t <= k; t++){
int prepro = INT32_MIN;
if(t%2){
int cur = 1;
int pre = 0;
}
else{
int cur = 0;
int pre = 1;
}
for(int d = 1; d < n; d++){
prepro = max(prepro, profit[pre][d-1] - prices[d-1]);
profit[cur][d] = max(profit[cur][d-1], prices[d] + prepro);
}
}
return (k%2 == 1)?profit[1][n-1]:profit[0][n-1];
}
| true |
a34fe9757bdb2a77e662a3906c7c6f47ace8d5d0 | C++ | billy4479/cpp-snake | /src/Grid.hpp | UTF-8 | 611 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include "Cell.hpp"
#include "Types.hpp"
#include <tuple>
#include <vector>
class Grid {
public:
Grid(uint width, uint height);
~Grid();
const Cell GetCellAt(uint x, uint y) const;
const Cell GetCellAt(std::pair<uint, uint> pos) const;
void SetCellContentAt(uint x, uint y, Cell newCell);
void SetCellContentAt(std::pair<uint, uint> position, Cell newCell);
const uint GetWidth() const;
const uint GetHeight() const;
private:
uint m_width;
uint m_height;
std::vector<Cell> m_Grid;
Cell *GetCellAtMut(uint x, uint y);
}; | true |
eaea4c234fd5a49cdc6fd0a69bad51e52598527b | C++ | Werevector/SDLBulletHell | /BulletHell/Main.cpp | UTF-8 | 3,051 | 2.78125 | 3 | [] | no_license | #pragma once
#include "SDL.h"
#include <iostream>
#include "stdio.h"
#include <string>
#include "Player.h"
#include "GameTimer.h"
#include "Graphics.h"
#include <vector>
#include "Enemy.h"
#include "Schedule.h"
#include "Bullet.h"
using namespace std;
void init();
bool loadMedia();
void close();
//World obects
Player player;
vector<Enemy*> enemyVectors;
Schedule gameSched(enemyVectors);
vector<Bullet*> bulletVectors;
//timer
GameTimer gTimer;
//SDL_Texture* loadTexture( std::string path );
void init()
{
SDL_Init( SDL_INIT_VIDEO );
SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" );
Graphics::gWindow = SDL_CreateWindow( "BulletHell", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, Graphics::SCREEN_WIDTH, Graphics::SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
Graphics::gRenderer = SDL_CreateRenderer( Graphics::gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
SDL_SetRenderDrawColor( Graphics::gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Nothing to load
return success;
}
void close()
{
//Destroy window
SDL_DestroyRenderer( Graphics::gRenderer );
SDL_DestroyWindow( Graphics::gWindow );
Graphics::gWindow = NULL;
Graphics::gRenderer = NULL;
//Quit SDL subsystems
SDL_Quit();
}
void draw(){
//Clear screen
SDL_SetRenderDrawColor( Graphics::gRenderer, 0x00, 0x00, 0x00, 0xFF );
SDL_RenderClear( Graphics::gRenderer );
player.Draw();
for(int i = 0; i < enemyVectors.size(); i++){
enemyVectors[i]->Draw();
}
for(int i = 0; i < bulletVectors.size(); i++){
bulletVectors[i]->Draw();
}
//Update screen
SDL_RenderPresent( Graphics::gRenderer );
}
void update(const Uint8* currentKeyStates){
if(currentKeyStates[ SDL_SCANCODE_UP ]){
player.mUpp = true;
}else if (currentKeyStates[ SDL_SCANCODE_DOWN ]){
player.mDown = true;
}
if (currentKeyStates[ SDL_SCANCODE_LEFT ]){
player.mLeft = true;
}else if (currentKeyStates[ SDL_SCANCODE_RIGHT ]){
player.mRight = true;
}
//Enemies
for(int i = 0; i < enemyVectors.size(); i++){
enemyVectors[i]->Update(gTimer);
enemyVectors[i]->Shoot(bulletVectors, gTimer);
}
//Bullets
for(int i = 0; i < bulletVectors.size(); i++){
bulletVectors[i]->Update(gTimer, player);
if(bulletVectors[i]->isOutsideBounds()){
bulletVectors.erase(bulletVectors.begin() + i);
bulletVectors.shrink_to_fit();
}
}
player.Update(gTimer.DeltaTime());
gameSched.checkSpawn(gTimer.TotalTime(),enemyVectors);
}
int main( int argc, char* args[] ) {
//initialize the game
init();
loadMedia();
bool quit = false;
SDL_Event event;
gTimer.Reset();
while( !quit )
{
while( SDL_PollEvent( &event ) != 0 ){
if( event.type == SDL_QUIT ){
quit = true;
}
}//EventWhile
const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
update(currentKeyStates);
gTimer.Tick();
cout << gTimer.TotalTime() << " " << bulletVectors.size() << "\n";
//draw to the screen
draw();
}//GameLoop
close();
return 0;
}//main | true |
dd5bdfc85fec579816ae40c1b88d9f5e0e70a841 | C++ | pratikdas44/codingPratice_cpp | /graph & trees/has_path_sum.cpp | UTF-8 | 449 | 3.390625 | 3 | [] | no_license | //sum is given find whether that sum can be obtained by any
//root to leaf path.
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL) {
return sum == root->val;
}
int remainingSum = sum - root->val;
return hasPathSum(root->left, remainingSum) || hasPathSum(root->right, remainingSum);
}
| true |
862ff0f8b09a78de4965a7d41545886432969911 | C++ | rishabhs95/algorithms | /acpc11b.cpp | UTF-8 | 783 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <cstring> //memset
#include <algorithm>
#include <bitset>
#include <string>
#include <vector>
#include <utility>
#include <cstdio>
#include <queue>
#include <cmath>
#include <list>
#include <set>
#include <map>
using namespace std;
int main() {
freopen("input.txt", "r", stdin);
int test_cases, n1, n2;
cin >> test_cases;
while (test_cases--) {
cin >> n1;
int alt1[n1];
for (int i = 0; i < n1; ++i) {
cin >> alt1[i];
}
// sort(alt1, alt1+n1);
cin >> n2;
int alt2[n2];
for (int i = 0; i < n2; ++i) {
cin >> alt2[i];
}
// sort(alt2, alt2+n2);
int diff = 1000000;
for (int i = 0; i < n1; ++i) {
for (int j = 0; j < n2; ++j) {
diff = min(diff, abs(alt1[i]-alt2[j]));
}
}
cout << diff << endl;
}
return 0;
} | true |
37a353bc92201cab096efcda44d30131372dc9cd | C++ | nhdang1702/FindingDragonBall | /BulletObject.cpp | UTF-8 | 545 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "BulletObject.h"
BulletObj :: BulletObj()
{
x_val_ = 0;
y_val_ = 0;
is_moving = false;
}
BulletObj :: ~BulletObj()
{
}
void BulletObj :: HandleMove(const int &x_border , const int &y_border)
{
if(bullet_dir == DIR_RIGHT)
{
rect_.x += x_val_;
if(rect_.x > x_border)
{
is_moving = false;
}
}
else if(bullet_dir == DIR_LEFT)
{
rect_.x -= x_val_;
if(rect_.x < 0)
{
is_moving = false;
}
}
}
| true |
395f3b2cff750e11db7cef7668c6143269b91d03 | C++ | Badlylucky/Codeforces-Round404-Div.2- | /B.cpp | UTF-8 | 559 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,m;
int ans;
int l1[200000];
int r1[200000];
int l2[200000];
int r2[200000];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>l1[i]>>r1[i];
}
cin>>m;
for(int i=0;i<m;i++)
{
cin>>l2[i]>>r2[i];
}
sort(l1,l1+n,[](int x,int y) -> int {return (x>y);});
sort(l2,l2+m,[](int x,int y) -> int {return (x>y);});
sort(r1,r1+n);
sort(r2,r2+m);
//cerr<<l1[0]<<l2[0]<<r1[0]<<r2[0]<<endl;
ans = max(l1[0]-r2[0],l2[0]-r1[0]);
if(ans<0)
{
ans=0;
}
cout<<ans<<endl;
return 0;
} | true |
6a47bcf73a506e9f4948c0d50dfdd51cb02572e1 | C++ | chijinxina/Code-Tempates | /src/遍历目录下的所有文件/FindFile.cpp | UTF-8 | 1,152 | 3.46875 | 3 | [] | no_license | //
// Created by chijinxin on 17-12-4.
//
#include <iostream>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
using namespace std;
/*
* 遍历某一文件夹下所有文件
* 依赖: Boost(filesystem) #include <boost/filesystem.hpp>
* 参数: path--文件夹路径 flag=true -- 返回文件名
* flag=false -- 返回文件绝对路径
* 返回值:文件数组
*/
std::vector<std::string> findAllFile(std::string path,bool flag){
boost::filesystem::directory_iterator end;
boost::filesystem::directory_iterator pos(path);
if(pos==end) {std::cerr<<"文件夹为空 or 文件夹不存在"<<std::endl;}
std::vector<std::string> result;
for(;pos!=end;++pos)
{
if(flag){
result.push_back(pos->path().filename().string());
} else{
result.push_back(pos->path().string());
}
}
return result;
}
/*
* 测试demo
*/
int main(){
string path = "../src/遍历目录下的所有文件/test";
vector<string> a = findAllFile(path,false);
for(int i=0;i<a.size();i++){
cout<<a[i]<<endl;
}
return 0;
}
| true |
174d78c37d68af65d5bf526eaeae19da166267ca | C++ | eze210/tp1-restorrente | /src/LobbyMonitor.cpp | UTF-8 | 4,643 | 2.890625 | 3 | [] | no_license | #include "LobbyMonitor.h"
#include "LockedScope.h"
#include "Logger.h"
#include <string>
static const std::string lobbyFifoName("lobby.fifo");
static const std::string tableQueueFifoName("tablequeue.fifo");
/** The instances in different processes of this class will have the
* same exclusive lock, and share the same shared counters.
*/
LobbyMonitor::LobbyMonitor() :
mutex("lobby_monitor.mutex"),
numberOfFreeTables(__FILE__, 't'),
numberOfClientsInLobby(__FILE__, 'c'),
lobbyFifo(lobbyFifoName),
tableQueueFifo(tableQueueFifoName) {
alive = true;
lobbyFifoW = NULL;
tableQueueFifoW = NULL;
lobbyFifoR = NULL;
tableQueueFifoR = NULL;
}
/** Adds a client in the corresponding queue (lobby or direct queue to tables)
*/
void LobbyMonitor::addClients(const ClientsGroup &clients) {
ClientID clientID = clients.getID();
mutex.lock();
size_t freeTables = numberOfFreeTables.read();
if (freeTables == 0) {
numberOfClientsInLobby.write(numberOfClientsInLobby.read() + 1);
} else {
decreaseFreeTables();
}
mutex.unlock();
if (freeTables == 0) {
LOGGER << "Releasing client " << clientID <<
" in the lobby" << logger::endl;
lobbyFifoW->write(static_cast<const void *>(&clientID), sizeof clientID);
} else {
LOGGER << "Releasing client " << clientID <<
" in the table queue" << logger::endl;
tableQueueFifoW->write(static_cast<const void *>(&clientID),
sizeof clientID);
}
}
/** Gets a client from the corresponding queue (first wants in lobby queue
* and after in the direct queue)
*/
ClientsGroup LobbyMonitor::getClients() {
ClientID clientID;
mutex.lock();
size_t clientsInLobby = numberOfClientsInLobby.read();
if (clientsInLobby > 0) {
numberOfClientsInLobby.write(clientsInLobby - 1);
mutex.unlock();
lobbyFifoR->read(static_cast<void *>(&clientID), sizeof clientID);
LOGGER << "Getting client " << clientID << " from lobby" << logger::endl;
} else {
increaseFreeTables();
mutex.unlock();
tableQueueFifoR->read(static_cast<void *>(&clientID), sizeof clientID);
LOGGER << "Getting client " << clientID << " from the table queue" << logger::endl;
}
return ClientsGroup(clientID);
}
/** Gets the current number of clients in the lobby queue.
*/
size_t LobbyMonitor::getNumberOfClientsInLobby() {
LockedScope l(mutex);
return numberOfClientsInLobby.read();
}
/** When a table is free, it should take an advice to the monitor.
*/
void LobbyMonitor::increaseFreeTables() {
// LockedScope l(mutex);
numberOfFreeTables.write(numberOfFreeTables.read() + 1);
}
/** When a table is busy, it should take an advice to the monitor.
*/
void LobbyMonitor::decreaseFreeTables() {
// LockedScope l(mutex);
numberOfFreeTables.write(numberOfFreeTables.read() - 1);
}
/** Gets the number of free tables in the restaurant.
*/
size_t LobbyMonitor::getNumberOfFreeTables() {
LockedScope l(mutex);
return numberOfFreeTables.read();
}
/** Releases the fifos used by monitor.
*/
void LobbyMonitor::release() {
lobbyFifo.release();
tableQueueFifo.release();
mutex.release();
numberOfClientsInLobby.free();
numberOfFreeTables.free();
}
/** There is only one instance of this class for each process where it is used.
* This method returns that instance, which is destroyed with the
* data segment of the process.
*/
LobbyMonitor &LobbyMonitor::getInstance() {
static LobbyMonitor instance;
return instance;
}
void LobbyMonitor::clear() {
ClientID clientID;
size_t clientsInLobby = numberOfClientsInLobby.read();
LOGGER << "Evacuating lobby" << logger::endl;
while (clientsInLobby > 0) {
numberOfClientsInLobby.write(clientsInLobby - 1);
lobbyFifoR->forceRead(static_cast<void *>(&clientID), sizeof clientID);
clientsInLobby = numberOfClientsInLobby.read();
}
alive = false;
}
bool LobbyMonitor::isAlive() {
return alive;
}
void LobbyMonitor::openForWrite() {
lobbyFifoW = new FifoWrite(lobbyFifoName);
tableQueueFifoW = new FifoWrite(tableQueueFifoName);
}
void LobbyMonitor::openForRead() {
lobbyFifoR = new FifoRead(lobbyFifoName);
tableQueueFifoR = new FifoRead(tableQueueFifoName);
}
void LobbyMonitor::closeFifoWrite() {
lobbyFifoW->close();
tableQueueFifoW->close();
}
LobbyMonitor::~LobbyMonitor() {
if (lobbyFifoW)
delete lobbyFifoW;
if (tableQueueFifoW)
delete tableQueueFifoW;
if (lobbyFifoR)
delete lobbyFifoR;
if (tableQueueFifoR)
delete tableQueueFifoR;
}
| true |
b91a29698dc50cb7abbbca6910b0ee76f23a4e98 | C++ | FaizChishtie/LCG | /matrix.h | UTF-8 | 624 | 2.6875 | 3 | [] | no_license | //
// matrix.h
// LogicCircuitGenerator
//
// Created by Faizaan Chishtie on 2018-11-09.
// Copyright © 2018 Faizaan Chishtie. All rights reserved.
//
#include <iostream>
#ifndef matrix_h
#define matrix_h
struct Matrix{
private:
int rows;
int cols;
std::string** matrix;
public:
Matrix() = default;
Matrix(int rows, int cols);
Matrix(int cols);
void assignValueToPos(int _x, int _y, std::string s);
void removeValueAtPos(int _x, int _y);
void removeCol(int _y);
void removeRow(int _x);
ostream operator<<(const Matrix& mat);
};
#endif /* matrix_h */
| true |
57bbf639534ee554376ca739e0d5a76c4da79060 | C++ | marius454/Block-Chain | /Block-Chain/Block.h | UTF-8 | 3,234 | 2.96875 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "storage.h"
std::string manoHash(std::string input);
//Sukuriama bloko klase
class Block {
private:
uint16_t index;
std::vector<transaction> data = std::vector<transaction>(100);
std::string hash;
int64_t nonce;
time_t time;
std::string merkle_root;
std::string BlockInfo;
uint32_t maxiter;
std::string calculateHash() {
std::string blockInfo = BlockInfo + std::to_string(nonce);
return manoHash(blockInfo);
};
std::string create_merkle(std::vector<transaction>& data);
public:
std::string prevHash;
Block() {};
Block(uint16_t index_, std::vector<transaction> data_, uint8_t difficulty, uint32_t maxIter) {
index = index_;
nonce = -1;
data = data_;
time = std::time(nullptr);
std::stringstream blockInfo;
merkle_root = create_merkle(data);
//blockInfo << index << merkle_root << time << prevHash;
blockInfo << index << merkle_root << prevHash;
BlockInfo = blockInfo.str();
maxiter = maxIter;
mineBlock(difficulty);
std::cout << "iterations: " << nonce + 2 << std::endl;
};
std::string getHash() {
return hash;
};
uint16_t getIndex() {
return index;
}
std::vector<transaction> getData() {
return data;
}
void mineBlock(uint8_t difficulty) {
char* cstr = new char[difficulty + 1];
for (uint8_t i = 0; i < difficulty; ++i) {
cstr[i] = '0';
}
cstr[difficulty] = '\0';
std::string str(cstr);
std::string Hash;
auto t1 = std::chrono::high_resolution_clock::now();
do {
Hash = calculateHash();
nonce++;
} while (Hash.substr(0, difficulty) != str && nonce < maxiter - 1);
nonce--;
auto t2 = std::chrono::high_resolution_clock::now();
long long duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
double dur = (double)duration * 0.000001;
std::cout << "mining time: " << dur << "s" << std::endl;
if (Hash.substr(0, difficulty) == str) {
blockMined(Hash);
}
else {
hash = "";
}
};
void blockMined(std::string Hash) {
hash = Hash;
}
void print1() {
std::cout << "Block " << index << ":" << std::endl;
std::cout << "Previous Hash - \"" << prevHash << "\"" << std::endl;
std::cout << "Hash - \"" << hash << "\"" << std::endl;
std::cout << "Transactions:" << std::endl;
for (uint8_t i = 0; i < data.size(); i++) {
std::cout << "\"" << data[i].getHash() << "\"" << std::endl;
}
}
void print2() {
std::cout << "Block " << index << " hash:" << std::endl;
std::cout << "\"" << hash << "\"" << std::endl;
}
};
//Sukuriama bloku grandines klase
class Block_Chain {
private:
uint8_t difficulty;
std::vector<Block> chain;
size_t Size;
uint32_t maxiter;
time_t candidateTimeStamp;
public:
size_t size() {
return Size;
}
Block getLastBlock() const {
return chain.back();
};
Block getBlock(short i) const {
return chain[i];
}
void incrementIter() {
maxiter = maxiter + 1000;
}
Block_Chain() {
difficulty = 3;
Size = 0;
maxiter = 1000;
};
void addBlock(std::vector<transaction> &data) {
Block bNew(Size, data, difficulty, maxiter);
if (bNew.getHash() != "") {
if (Size > 0) {
bNew.prevHash = getLastBlock().getHash();
}
chain.push_back(bNew);
Size = chain.size();
maxiter = 1000;
}
};
};
| true |
01ce95aa9c302f34b1736e9676f77c6e8f4e4f80 | C++ | LevKats/msu_cpp_automn_2019 | /homework/04/BigInt.cpp | UTF-8 | 8,817 | 3.296875 | 3 | [] | no_license | #include "BigInt.h"
#include <cstdio>
BigInt::BigInt() : sign(true), length(0), mem(nullptr) {};
BigInt::BigInt(const BigInt& other)
: sign(other.sign), length(other.length) {
if (other.is_nan()) {
mem = nullptr;
}
else {
mem = new char[length];
for (int i = 0; i < length; ++i)
mem[i] = other.mem[i];
}
}
BigInt::BigInt(int i) {
if (i == 0) {
length = 1;
sign = true;
mem = new char[1];
mem[0] = 0;
}
else {
sign = true;
if (i <= 0) {
i = -i;
sign = false;
}
char buf[10];
int size;
for (size = 0; i; ++size) {
buf[size] = i % 10;
i /= 10;
}
length = size;
mem = new char[length];
for (int j = 0; j < length; ++j)
mem[j] = buf[j];
}
}
BigInt::BigInt(BigInt&& moved)
: sign(moved.sign), length(moved.length), mem(moved.mem) {
moved.length = 0;
moved.sign = true;
moved.mem = nullptr;
}
BigInt& BigInt::operator=(const BigInt& other) {
if (this == &other)
return *this;
sign = other.sign;
length = other.length;
mem = new char[length];
for (int i = 0; i < length; ++i)
mem[i] = other.mem[i];
return *this;
}
BigInt& BigInt::operator=(int i) {
*this = BigInt(i);
return *this;
}
BigInt& BigInt::operator=(BigInt&& moved) {
if (this == &moved)
return *this;
sign = moved.sign;
length = moved.length;
delete[] mem;
mem = moved.mem;
moved.length = 0;
moved.sign = true;
moved.mem = nullptr;
return *this;
}
BigInt BigInt::operator-() const {
if (this->is_nan())
throw std::domain_error("object is nan");
BigInt result(*this);
if (result.length == 1 && result.mem[0] == 0)
return result;
result.sign = !sign;
return result;
}
BigInt operator-(BigInt&& rvalue) {
if (rvalue.is_nan())
throw std::domain_error("object is nan");
//std::cout << "rvalue " << rvalue << '\n';
rvalue.sign = !rvalue.sign;
return rvalue;
}
BigInt BigInt::natural_plus(const BigInt& right) const {
if (this->is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
if (length >= right.length) {
BigInt result;
char add = 0;
for (int i = 0; i < length; ++i) {
int r = i < right.length ? right.mem[i] : 0;
add = (mem[i] + r + add) > 9;
}
result.length = length + add;
result.sign = true;
result.mem = new char[result.length];
add = 0;
for (int i = 0; i < result.length; ++i) {
int r = i < right.length ? right.mem[i] : 0;
int l = i < length ? mem[i] : 0;
result.mem[i] = (l + r + add) % 10;
add = (l + r + add) > 9;
}
return result;
}
else {
return right.natural_plus(*this);
}
}
BigInt BigInt::natural_minus(const BigInt& right) const {
if (this->is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
BigInt result;
result.length = 0;
result.sign = true;
char add = false;
for (int i = 0; i < length; ++i) {
int r = i < length ? right.mem[i] : 0;
int digit = mem[i] - add - r;
add = (digit) < 0;
if (digit != 0)
result.length = i + 1;
}
if (result.length == 0)
return BigInt(0);
result.mem = new char[result.length];
add = false;
for (int i = 0; i < result.length; ++i) {
int r = i < right.length ? right.mem[i] : 0;
int digit = mem[i] - add - r;
add = digit < 0;
result.mem[i] = add ? 10 + digit : digit;
}
return result;
}
BigInt operator+(const BigInt& left, const BigInt& right) {
if (left.is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
if (left.sign == right.sign) {
return left.sign ? left.natural_plus(right) :
-left.natural_plus(right);
}
else {
if (left.sign)
return !left.abs_less(right) ? left.natural_minus(right) :
-right.natural_minus(left);
else
return !left.abs_less(right) ? -left.natural_minus(right) :
right.natural_minus(left);
}
}
BigInt operator-(const BigInt& left, const BigInt& right) {
if (left.is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
return left + (-right);
}
bool BigInt::abs_less(const BigInt& right) const {
if (this->is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
if (length < right.length)
return true;
else if (length > right.length)
return false;
else {
for (int i = length - 1; i >= 0; --i) {
if (mem[i] < right.mem[i])
return true;
else if (mem[i] > right.mem[i])
return false;
}
return false;
}
}
bool operator<(const BigInt& left, const BigInt& right) {
if (left.is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
if (left.sign != right.sign) {
if (!left.sign)
return true;
return false;
}
if (left.sign) {
return left.abs_less(right);
}
else {
return !left.abs_less(right);
}
}
bool operator>(const BigInt& left, const BigInt& right) {
if (left.is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
return right < left;
}
bool operator==(const BigInt& left, const BigInt& right) {
if (left.is_nan()) {
throw std::domain_error("left object is nan");
}
if (right.is_nan()) {
throw std::domain_error("right object is nan");
}
if (left.sign != right.sign)
return false;
if (left.length != right.length)
return false;
for (int i = left.length - 1; i >= 0; --i) {
if (left.mem[i] != right.mem[i])
return false;
}
return true;
}
bool operator!=(const BigInt& left, const BigInt& right) {
return !(left == right);
}
bool operator<=(const BigInt& left, const BigInt& right) {
return left < right || left == right;
}
bool operator>=(const BigInt& left, const BigInt& right) {
return left > right || left == right;
}
BigInt operator+(int left, const BigInt& right) {
return BigInt(left) + right;
}
BigInt operator-(int left, const BigInt& right) {
return BigInt(left) - right;
}
bool operator<(int left, const BigInt& right) {
return BigInt(left) < right;
}
bool operator>(int left, const BigInt& right) {
return BigInt(left) > right;
}
bool operator==(int left, const BigInt& right) {
return BigInt(left) == right;
}
bool operator!=(int left, const BigInt& right) {
return !(left == right);
}
bool operator<=(int left, const BigInt& right) {
return BigInt(left) <= right;
}
bool operator>=(int left, const BigInt& right) {
return BigInt(left) >= right;
}
BigInt operator+(const BigInt& left, int right) {
return left + BigInt(right);
}
BigInt operator-(const BigInt& left, int right) {
return left - BigInt(right);
}
bool operator<(const BigInt& left, int right) {
return left < BigInt(right);
}
bool operator>(const BigInt& left, int right) {
return left > BigInt(right);
}
bool operator==(const BigInt& left, int right) {
return left == BigInt(right);
}
bool operator!=(const BigInt& left, int right) {
return !(left == right);
}
bool operator<=(const BigInt& left, int right) {
return left <= BigInt(right);
}
bool operator>=(const BigInt& left, int right) {
return left >= BigInt(right);
}
bool BigInt::is_nan() const {
return sign && length == 0 && mem == nullptr;
}
std::ostream& operator<<(std::ostream& os, const BigInt& num) {
if (num.is_nan()) {
os << "nan";
return os;
}
if (!num.sign)
os << '-';
for (int i = num.length - 1; i >= 0; --i)
os << static_cast<char>(num.mem[i] + '0');
return os;
}
BigInt::~BigInt() {
delete[] mem;
}
| true |
b4488a74778ff703db8f5f82c9eb3f257a3b09b4 | C++ | Siriayanur/DSA | /DP/419goldMine.cpp | UTF-8 | 1,188 | 3.328125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<climits>
using namespace std;
class Solution{
public:
int maxGold(int n, int m, vector<vector<int>> t)
{
// code here
for (int col = m-2; col >= 0;col--){
for (int row = 0; row < n; row++){
//current value in the gold mine
int x = t[row][col+1];
//diagonally right up
int y = (row == 0 ? 0 : t[row-1][col+1]);
//diagonally right down
int z = (row == n - 1 ? 0 : t[row + 1][col + 1]);
//take the maximum of the values
t[row][col] = t[row][col] + max(x, max(y, z));
}
}
int result = INT_MIN;
for (int i = 0; i < n; i++)
{
if(t[i][0] > result)
result = t[i][0];
}
return result;
}
};
int main(){
int m;
int n;
//Take the number of rows and columns
cin >> m >> n;
//gold mine
int t[m][n];
for (int i = 0; i < m; i ++){
for (int j = 0; j < n; j++){
cin >> t[i][j];
}
}
}
| true |
2cc1c3c05d3e70c13d8159abc4f1f79d56c04c9b | C++ | pockman/ACM_ICPC | /Dynamic Programming/POJ3616_bat.cpp | UTF-8 | 1,410 | 2.59375 | 3 | [
"MIT"
] | permissive |
#include <iostream>
#include <algorithm>
#include <math.h>
#include <string>
#include <queue>
#include <set>
using namespace std;
#define rep(i, n) for (int (i) = 0; (i) < (n); (i) ++)
#define rep1(i, n) for (int (i) = 1; (i) <= (n); (i) ++)
#define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++)
#define db(x) {cout << #x << " = " << (x) << endl;}
#define dba(a, x, y) {cout<<#a<<" :";FOR(i123,x,y)cout<<setw(4)<<(a)[i123];cout<<endl;}
#define clr(x) memset(x,0,sizeof(x));
#define mp make_pair
#define pb push_back
#define sz(x) int((x).size())
struct Interval{
int s,e,c;
Interval() {};
Interval(int ss, int ee, int cc): s(ss), e(ee), c(cc){};
bool operator < (const Interval& i2) const
{
return e < i2.e;
}
};
int N, M, R;
Interval I[1010];
int dp[1010]; // dp[i] = Max C to get at the end of i-th interval
int main()
{
ios_base::sync_with_stdio(0); cout.precision(15); cout << fixed; cout.tie(0); cin.tie(0);
cin >> N >> M >> R;
rep1(i,M){
cin >> I[i].s >> I[i].e >> I[i].c;
I[i].e = min(N, I[i].e + R);
}
sort(I+1, I+M + 1);
dp[1] = I[1].c;
int ans = 0;
for(int i = 2; i <= M; i++){
dp[i] = I[i].c;
for(int j = 1; j < i; j++){
if(I[j].e <= I[i].s){
dp[i] = max(dp[i], dp[j] + I[i].c);
}
}
ans = max(ans, dp[i]);
}
cout << ans << endl;
}
| true |
d1682cb0d76b379b8f12c0ce29ba19ec020bf0c0 | C++ | FunkMonkey/Bound | /Wrapping/Spidermonkey/SpidermonkeyWrapper/include/wrap_helpers/boolean_x.hpp | UTF-8 | 1,395 | 2.96875 | 3 | [] | no_license | #ifndef WRAP_HELPERS_BOOLEAN_X_HPP
#define WRAP_HELPERS_BOOLEAN_X_HPP
#include <jsapi.h>
#include "exceptions.hpp"
#include "conversion_templates.hpp"
namespace jswrap
{
// TODO: rename to jsval_to_boolean_strict_x
/**
* Converts a jsval to a C++ boolean
* - throws exception if jsval is not a boolean
*
* \param val Value to convert
* \return C++ boolean
*/
static bool jsval_to_boolean_x(jsval val)
{
if(!JSVAL_IS_BOOLEAN(val))
throw exception("Given jsval is not a boolean");
return JSVAL_TO_BOOLEAN(val) != 0;
}
/**
* Converts a jsval to a C++ boolean
* - uses ECMAScript conversion function if jsval is not boolean
* - throws exception if conversion fails
*
* \param val Value to convert
* \return C++ boolean
*/
static bool jsval_to_boolean_convert_x(JSContext* cx, jsval val)
{
JSBool result;
if(!JS_ValueToBoolean(cx, val, &result))
throw exception("Could not convert jsval to boolean");
return result != 0;
}
//---------------------------------------------------
// TEMPLATED
//---------------------------------------------------
//template<>
//bool jsval_to_type_x(JSContext* cx, jsval val)
//{
// return jsval_to_boolean_x(val);
//}
//template<>
//bool jsval_to_type_convert_x(JSContext* cx, jsval val)
//{
// return jsval_to_boolean_convert_x(cx, val);
//}
}
#endif // WRAP_HELPERS_BOOLEAN_X_HPP | true |
e3860a00a6bbacb66e3fbedd3b482b62c3056896 | C++ | sergio5405/TTP-2018 | /Training Problems/2281_EncodedMessage.cpp | UTF-8 | 546 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
char table[100][100];
int main(){
int T;
string word;
cin >> T;
getline(cin, word);
for (int t = 0; t < T; t++){
getline(cin, word);
int sqlen = sqrt(word.length());
int strIt = 0;
for (int j = 0; j<sqlen; j++){
for (int i = sqlen-1; i>=0; i--){
table[i][j] = word[strIt++];
}
}
for (int i = 0; i<sqlen; i++){
for (int j = 0; j<sqlen; j++){
cout << table[i][j];
}
}
cout << endl;
}
return 0;
} | true |
b83b8ce30515372cf1a4534d91a461602c4c5aa0 | C++ | mobi12/study | /cpp/cpp596.cpp | UTF-8 | 642 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
struct car {
string company;
int year;
};
int answer = 0;
cout << "请问有多少辆车?" << endl;
cin >> answer;
car *pn = new car[answer];
cout << "输入每辆车的生产商和年份" << endl;
for (int i = 0; i < answer; i++)
{
cout << "输入名字:";
cin.get();
getline(cin,pn[i].company);
cout << "输入年份:";
cin >> pn[i].year;
}
cout << "你一共有这" << answer << "辆车:" << endl;
for (int j = 0; j < answer; j++)
{
cout << pn[j].year << " ";
cout << pn[j].company << endl;
}
delete [] pn;
return 0;
}
| true |
69fccb73f9113b47f5d47e24e5aabca9599b16dc | C++ | ccdxc/logSurvey | /data/crawl/tar/old_hunk_304.cpp | UTF-8 | 777 | 2.578125 | 3 | [] | no_license | }
/* Fix the statuses of all directories whose statuses need fixing, and
which are not ancestors of FILE_NAME. */
static void
apply_nonancestor_delayed_set_stat (char const *file_name)
{
size_t file_name_len = strlen (file_name);
while (delayed_set_stat_head)
{
struct delayed_set_stat *data = delayed_set_stat_head;
if (data->file_name_len < file_name_len
&& file_name[data->file_name_len]
&& (ISSLASH (file_name[data->file_name_len])
|| ISSLASH (file_name[data->file_name_len - 1]))
&& memcmp (file_name, data->file_name, data->file_name_len) == 0)
break;
delayed_set_stat_head = data->next;
set_stat (data->file_name, &data->stat_info,
data->invert_permissions, data->permstatus, DIRTYPE);
free (data);
}
}
| true |
8e2b02412afd7b52a2a532358d921c67a94e8c35 | C++ | xenron/sandbox-github-clone | /yubinbai/pcuva-problems/UVa 10115 - Automatic Editing/sol.cpp | UTF-8 | 824 | 2.765625 | 3 | [] | no_license | #include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int n, ax;
string s1, s2;
vector<string> v1;
vector<string> v2;
while (1)
{
cin >> n;
if (n == 0) break;
v1.clear();
v2.clear();
getline(cin, s1);
for (int i = 0; i < n; i++)
{
getline(cin, s1);
getline(cin, s2);
v1.push_back(s1);
v2.push_back(s2);
}
getline(cin, s1);
ax = 0;
while (ax != v1.size())
{
n = s1.find(v1[ax]);
if (n != -1)
{
s1.erase(n, v1[ax].size());
s1.insert(n, v2[ax]);
}
else ax++;
}
cout << s1 << endl;
}
return 0;
} | true |
baa9a1720f7aec80878de5f26cd09df9d8139743 | C++ | alan-turing-institute/BOAT | /examples/bo_naive/bo_naive_opti.cpp | UTF-8 | 2,807 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #include "../../include/boat.hpp"
using namespace std;
using boat::ProbEngine;
using boat::SemiParametricModel;
using boat::DAGModel;
using boat::GPParams;
using boat::NLOpt;
using boat::BayesOpt;
using boat::SimpleOpt;
using boat::generator;
using boat::RangeParameter;
struct BHParams{
BHParams() : x1_(-5, 10), x2_(0, 15){}
RangeParameter<double> x1_;
RangeParameter<double> x2_;
};
/// The Branin-Hoo objective function
double branin_hoo(const BHParams& p){
static constexpr double a = 1;
static constexpr double b = 5.1 / (4 * pow(M_PI, 2));
static constexpr double c = 5.0 / M_PI;
static constexpr double r = 6.0;
static constexpr double s = 10;
static constexpr double t = 1.0 / (8 * M_PI);
double x1 = p.x1_.value();
double x2 = p.x2_.value();
double fx = a * pow(x2 - b * pow(x1, 2) + c * x1 - r, 2) +
s * (1.0 - t) * std::cos(x1) + s;
return fx;
}
/// Naive way of optimizing it, model with simple GP prior
struct Param : public SemiParametricModel<Param> {
Param() {
p_.default_noise(0.0);
p_.mean(uniform_real_distribution<>(0.0, 10.0)(generator));
p_.stdev(uniform_real_distribution<>(0.0, 200.0)(generator));
p_.linear_scales({uniform_real_distribution<>(0.0, 15.0)(generator),
uniform_real_distribution<>(0.0, 15.0)(generator)});
set_params(p_);
}
GPParams p_;
};
struct FullModel : public DAGModel<FullModel> {
FullModel(){
eng_.set_num_particles(100);
}
void model(const BHParams& p) {
output("objective", eng_, p.x1_.value(), p.x2_.value());
}
void print() {
PR(AVG_PROP(eng_, p_.mean()));
PR(AVG_PROP(eng_, p_.stdev()));
PR(AVG_PROP(eng_, p_.linear_scales()[0]));
PR(AVG_PROP(eng_, p_.linear_scales()[1]));
}
ProbEngine<Param> eng_;
};
void maximize_ei(FullModel& m, BHParams& p, double incumbent) {
NLOpt<> opt(p.x1_, p.x2_);
auto obj = [&]() {
double r = m.expected_improvement("objective", incumbent, p);
return r;
};
opt.set_objective_function(obj);
opt.set_max_num_iterations(10000);
opt.set_maximizing();
opt.run_optimization();
}
void bo_naive_optim() {
FullModel m;
m.set_num_particles(100);
BHParams p;
BayesOpt<unordered_map<string, double> > opt;
auto subopt = [&]() {
maximize_ei(m, p, opt.best_objective());
};
auto util = [&](){
unordered_map<string, double> res;
res["objective"] = branin_hoo(p);
PR(p.x1_.value(), p.x2_.value(), res["objective"]);
return res;
};
auto learn = [&](const unordered_map<string, double>& r){
m.observe(r, p);
};
opt.set_subopt_function(subopt);
opt.set_objective_function(util);
opt.set_learning_function(learn);
opt.set_minimizing();
opt.set_max_num_iterations(25);
opt.run_optimization();
}
int main() {
bo_naive_optim();
}
| true |
eb68f0b678480060a2eb8743a01fe32d175d3268 | C++ | gourdi/ggp | /ggo2d/test/ggo_kdtree_nonreg.cpp | UTF-8 | 1,389 | 2.546875 | 3 | [] | no_license | #include <kernel/nonreg/ggo_nonreg.h>
#include <kernel/trees/ggo_kdtree.h>
#include <kernel/math/shapes_2d/ggo_shapes2d.h>
#include <kernel/math/shapes_3d/ggo_shapes3d.h>
#include <2d/paint/ggo_paint_layer.h>
#include <2d/io/ggo_bmp.h>
////////////////////////////////////////////////////////////////////
GGO_TEST(kdtree, random_points)
{
const int size = 500;
const float radius = 50;
// Create random points.
using tree_point = ggo::kdtree<void *, ggo::vec2_f>::data_point;
std::vector<tree_point> points;
for (int i = 0; i < 500; ++i)
{
float x = ggo::rand<float>(0.f, static_cast<float>(size));
float y = ggo::rand<float>(0.f, static_cast<float>(size));
points.push_back({ { x, y }, nullptr });
}
ggo::image_t<ggo::pixel_type::rgb_8u> image({ size, size });
ggo::paint<ggo::sampling_4x4>(image, ggo::disc_f({ size / 2.f, size / 2.f }, radius), ggo::red_8u());
for (const auto & point : points)
{
ggo::paint<ggo::sampling_4x4>(image, ggo::disc_f({ point._pos.x(), point._pos.y() }, 2.f), ggo::white_8u());
}
ggo::kdtree<void *, ggo::vec2_f> tree(points);
auto inside_points = tree.find_points({ size / 2.f, size / 2.f }, radius);
for (const auto & point : inside_points)
{
ggo::paint<ggo::sampling_4x4>(image, ggo::disc_f({ point._pos.x(), point._pos.y() }, 2.f), ggo::blue_8u());
}
ggo::save_bmp("kdtree.bmp", image);
}
| true |
9bc7fd83fec13915310674e1af93d0d21419b0cc | C++ | albertojosue/mtec2250 | /_3_Button_Switching.ino | UTF-8 | 3,597 | 3.171875 | 3 | [] | no_license |
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin1= 2; // the number of the pushbutton pin
const int buttonPin2= 3;
const int buttonPin3= 4;
const int ledPin1 = 13;
const int ledPin2 = 12; // constant int
const int ledPin3 = 11; // constant int
const int ledPin4 = 10; // constant int
const int ledPin5 = 9; // constant int
int switchRead1 = 0;
int switchRead2 = 0;
int switchRead3 = 0;
int counter = 0;
boolean pressing1 = false;
#define ledPin1 13 //define is used to set a constant variable
#define ledPin2 12 //define is used to set a constant variable
#define ledPin3 11 //define is used to set a constant variable
#define ledPin4 10 //define is used to set a constant variable
#define ledPin5 9 //define is used to set a constant variable
// variables will change:
int buttonState = 1; // variable for reading the pushbutton status
void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
}
void loop() {
// read the state of the pushbutton value:
//digitalWrite(ledPin1, HIGH);
switchRead1 = digitalRead(buttonPin1);
switchRead2 = digitalRead(buttonPin2);
switchRead3 = digitalRead(buttonPin3);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (switchRead1 == 1) {
Serial.println("Button #1 Pressed");
pressing1 = true;
}
if(switchRead2 == 1){
Serial.println("Button #2 Pressed");
counter = 2;
}
if(switchRead3 == 1){
Serial.println("Button #3 Pressed");
counter = 3;
}
// Check if the button is released and if it has been pressed before.
if (switchRead1 == 0 && pressing1 == true) {
// Setting for the next time button is pressed
pressing1 = false;
//Do Something
counter++;
Serial.print("Counter: ");
Serial.println(counter);
}
if (counter == 1) {
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, LOW);
} else if (counter == 2) {
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, LOW);
} else if (counter == 3) {
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, LOW);
} else if (counter == 4) {
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, HIGH);
digitalWrite(ledPin5, LOW);
} else if (counter == 5) {
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, HIGH);
} else {
counter = 0;
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPin5, LOW);
}
}
| true |
f6ecb2450b24e273300225f9e5843eebd65904c9 | C++ | wowk/Mario | /Classes/TmxMap.h | UTF-8 | 681 | 2.515625 | 3 | [
"MIT"
] | permissive | #ifndef __TMX_MAP_H__
#define __TMX_MAP_H__
#include "cocos2d.h"
class TmxMap : public cocos2d::TMXTiledMap {
public:
static TmxMap* create(const std::string & name);
bool initWithTMXFile(const std::string & name);
protected:
explicit TmxMap(){}
public:
void moveHor(float delta/* negative means left, positive means right*/);
void moveVer(float delta/* negative means left, positive means right*/);
void setMoveSpeed(float value);
bool isLeftEdgeArrived() const;
bool isRightEdgeArrived() const;
private:
bool leftEdgeArrived;
bool rightEdgeArrived;
float leftEdge;
float rightEdge;
float moveSpeed;
};
#endif//__MAP_H__
| true |
c1807b1f067ed8db90594a852fbb2505d71ee8c7 | C++ | Phoenix-RK/GeeksForGeeks | /Dynamic Programming/Max Sum without Adjacents.cpp | UTF-8 | 1,511 | 3.296875 | 3 | [] | no_license | //Phoenix_RK
/*
https://www.youtube.com/watch?v=UtGtF6nc35g
https://practice.geeksforgeeks.org/problems/max-sum-without-adjacents/0
Given an array A of positive integers. Find the maximum sum of a subsequence such that no two numbers in the sequence should be adjacent in the array.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N, size of array. The second line of each test case contains N elements.
Output:
Print the maximum sum of a subsequence.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 106
1 ≤ Ci ≤ 107
Example:
Input:
2
6
5 5 10 100 10 5
4
3 2 7 10
Output:
110
13
Explanation:
Testcase 2 : 3 and 10 forms a non-continuous subsequence with maximum sum.
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
//code
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int inc=0; //keeps track of maximum sum we could get at that time by including that element.Therefore, whenever we are updating inc, the maximum(old inc, exc+a[i]) is taken
int exc=0;//keeps track of maximum sum we could get at that time by including that element...the old inclusive becomes new exclusive because the old inclusive holds the max_so_far by excluding that particular element
for(int i=0;i<n;i++)
{
int temp=inc;
inc=max(exc+a[i],inc);
exc=temp;
}
cout<<max(inc,exc)<<endl;
}
return 0;
}
| true |
b907762db3b909cee610aca00637bea5ed13faca | C++ | anricardo98/Teste_prova | /Banco.hpp | WINDOWS-1252 | 1,038 | 3.328125 | 3 | [] | no_license | #ifndef SOBRECARGA_HPP
#define SOBRECARGA_HPP
class Banco{
private:
int saldo;
public:
Banco();
Banco (int x);
int getSaldo();
void setSaldo(int a);
Banco operator+(Banco &bank);
Banco operator-(Banco &bank);
//friend istream& operator >> (istream &i, Banco &bank);
//friend ostream operator<<(ostream& o, Banco &bank);
};
Banco::Banco(){
saldo = 0;
}
Banco::Banco(int x){
saldo = x;
}
void Banco::setSaldo (int a){
saldo = a;
}
int Banco::getSaldo (){
return saldo;
}
Banco Banco::operator+ (Banco &bank){
int saldo = this->saldo + bank.getSaldo();
return Banco(saldo);
}
Banco Banco::operator- (Banco &bank){
int saldo = this->saldo - bank.getSaldo();
return Banco(saldo);
}
/*
istream& operator>> (istream &i, Banco &bank){
i >> bank.saldo;
return i;
}
*/
/*ostream operator <<(ostream& o, Banco &bank){
o << "O saldo " << bank.getSaldo();
return o;
}*/
#endif
| true |
39ebd1e4f2ceb5e41faa56548cf6f96efd3341ec | C++ | steakdown/IGR205 | /shapetype.h | UTF-8 | 588 | 2.703125 | 3 | [] | no_license | /*
* shapetype.h
*
* Equivalent of latent variable R on paper.
* Contains the categories.
*
* Created on: May 7, 2017
* Author: blupi
*/
#ifndef SHAPETYPE_H_
#define SHAPETYPE_H_
#include "componentcategory.h"
class ShapeType {
public:
ShapeType();
ShapeType(std::vector<ComponentCategory> newCats);
void setCats(std::vector<ComponentCategory> newCats);
std::vector<ComponentCategory> getCats();
void addCat(ComponentCategory cat);
virtual ~ShapeType();
private:
std::vector<ComponentCategory> cats;
};
#endif /* SHAPETYPE_H_ */
| true |
f03ab92d33d85f3b11541d81e6c29e3261045575 | C++ | MesceBasse/arduino | /libraries/ArduinoGotronic/KY-009/KY-009-PWM.ino | UTF-8 | 742 | 2.96875 | 3 | [] | no_license | int Led_Rouge = 10;
int Led_Verte = 11;
int Led_Bleue = 12;
int val;
void setup () {
// Initialisation des broches de sortie pour les LEDS
pinMode (Led_Rouge, OUTPUT);
pinMode (Led_Verte, OUTPUT);
pinMode (Led_Bleue, OUTPUT);
}
void loop () {
// Dans une boucle For, différentes valeurs PWM sont envoyées aux 3 LEDS
for (val = 255; val> 0; val--)
{
analogWrite (Led_Bleue, val);
analogWrite (Led_Verte, 255-val);
analogWrite (Led_Rouge, 128-val);
delay (1);
}
// Les signaux sont ensuite inversés
for (val = 0; val <255; val++)
{
analogWrite (Led_Bleue, val);
analogWrite (Led_Verte, 255-val);
analogWrite (Led_Rouge, 128-val);
delay (1);
}
} | true |
da7f1385743244884f9b27727b50f88fb1ee3f10 | C++ | shivral/cf | /0200/30/234c.cpp | UTF-8 | 852 | 3.109375 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
#include <vector>
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(const std::vector<int>& t)
{
const size_t n = t.size();
std::vector<unsigned> p(1+n);
for (size_t i = 0; i < n; ++i)
p[i+1] = p[i] + (t[i] >= 0);
std::vector<unsigned> s(1+n);
for (size_t i = n; i > 0; --i)
s[i-1] = s[i] + (t[i-1] <= 0);
unsigned k = n;
for (size_t i = 1; i < n; ++i)
k = std::min(k, p[i] + s[i]);
answer(k);
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
size_t n;
std::cin >> n;
std::vector<int> t(n);
std::cin >> t;
solve(t);
return 0;
}
| true |
48acc86ec7c1f2a335e463fe65b30df1c255c8df | C++ | SCP120/LBEP1 | /abcd.cpp | UTF-8 | 589 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,j,b,s;
int *a;
printf("nhap cac so nguyen: ");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
for( i=0;i<n;i++){
printf("a[%d]= ",i);
scanf("%d",(a+i));
}
int n1=0;
printf("nhap so nguyen thu hai: ");
scanf("%d",&n1);
int tong=n1+n;
a=(int*)realloc(a,tong*sizeof(int));
for(i=n;i<tong;i++){
printf("a[%d]= ",i);
scanf("%d",(a+i));
}
for(j=1;j<tong;j++){
b=j-1;
s=*(a+j);
while((b>=0)&&(s<*(a+b))){
*(a+b+1)=*(a+b);
b--;
}
*(a+b+1)=s;
}
for(j=0;j<tong;j++){
printf("%5d",*(a+j));
}
}
| true |
a785defb8180b459935653069c6cebe7f7b8f2ee | C++ | jbji/Programming-Method-and-Practice---2019-CS | /2020AD-PROBLEM-A/main.cpp | UTF-8 | 476 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
// ios::sync_with_stdio(false);
int T;
int A,B,t,k,i;
for(cin >> T;T>0;T--){
cin >> A >> B >> t >> k;
if(t>B) {
t = (t - 1) % B + 1;
}
//i表示,第几次将会被滞留
for(i=1;t*i<A;i++);
//将k变到不大于i的范围
cout << t * ((k - 1) % i + 1) % B << endl;
}
// std::cout << "Hello, World!" << std::endl;
return 0;
} | true |
2652e9fa41c33039c69e294b1736e045477956ab | C++ | prasadgujar/Programming | /playtofit.cpp | UTF-8 | 465 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t,n,x,y;
std::cin>>t;
while(t--)
{
int maxx=0;
std::cin>>n>>y;
for(int i=1;i<n;i++)
{
std::cin>>x;
if(x<y)
y=x;
else if(x-y > maxx)
maxx = x-y;
}
if(maxx == 0)
std::cout<<"UNFIT"<<'\n';
else
std::cout<<maxx<<'\n';
}
return 0;
}
| true |
a3809a753767c4940a26496803c09a2cbc20c8ef | C++ | erebe/anonymousMailer | /src/Mail/Mail.cpp | UTF-8 | 8,318 | 2.53125 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: mail.cpp
*
* Description: Implémentation de la classe Mail. Cette classe permet d'envoyer des
* mails au format MIME et pouvant contenir des pièces-jointes
*
* Version: 1.0
* Created: 21/04/2011 20:33:46
* Revision: none
* Compiler: g++
*
* Author: Erebe (), erebe@erebe.eu
* Company: Erebe corporation
*
* =====================================================================================
*/
#include "Mail.hpp"
#include "Base64/Base64.hpp"
#include <fstream>
#include <string>
using namespace std;
Mail::Mail(const string& serveurSmtp, const string& expediteur, string& destinataires, const string& sujet,
const string& message, string& piecesJointes):
_serveurSmtp(serveurSmtp),
_expediteur(expediteur),
_sujet(sujet),
_message(message),
_socket(serveurSmtp, 25)
{
explodeString( destinataires, ",", _destinataires );
explodeString( piecesJointes, ",", _piecesJointes );
}
void Mail::send() {
/*-----------------------------------------------------------------------------
* On contacte le serveur smtp et on se présente à lui
*-----------------------------------------------------------------------------*/
cout << _socket.read( 500 ) << endl;
string message = "EHLO erebe\nMAIL FROM:<" + _expediteur + ">\n";
for( auto& destinataire: _destinataires ) {
message += "RCPT TO:<" + destinataire + ">\n";
}
message += "DATA";
_socket.write( message );
cout << _socket.read( 500 ) << endl;
message.erase();
/*-----------------------------------------------------------------------------
* On envoie le corps du message
*-----------------------------------------------------------------------------*/
message += "From: <" + _expediteur + ">\n";
for( auto& destinataire: _destinataires) {
message += "To: <" + destinataire + ">\n";
}
message += "Subject: " + _sujet + "\n"
+ "MIME-version: 1.0\n"
+ "Content-type: multipart/mixed;boundary=\"iletaitunefois\"\n"
+ "Ce message est au format MIME.\n"
+ " . \n"
+ " ':' \n"
+ " ' `;;;:. ' \n"
+ " `;:'`. ';;;;;:. ..`:;;.\n"
+ " .;;;;;;;'`.. . .:;;;;;;;;` ..`:;;;;;;' \n"
+ " `;;;;;;;;;;;''.. .`` .;;;;;;;;;;;'. `. .`':;;;;;;;;;;;. \n"
+ " ;;;;;;;;;;;;;;;;:'`. `;' `:;;;;::::::::'. ';` .`':;;:;:;:;:;:;:;:' \n"
+ " `;;;;;;;;;;;;;;;;;;;;:'`....';: ';' .';` :;'....`':;;::;:;:;:;:;:;:;:;;. \n"
+ " `'':::;;;;;;;;;;;;;;;;;;;;;;;` .;;;;'. .:;;;` `;;;::;;;:;:;;:;;:;:;;;:::''. \n"
+ " ....```''::::;;;;;;;;. .:;;;;;:. `:;;:;;'. .;;;;;;;;;:::'''``.... \n"
+ " ..:;;: `;;;;;;;;;` .';;:;;;;;:. :;;:.. \n"
+ " .......```;;;;.';;;;;;;;;;;:..:;;;;;;;;;;:`.:;;;```...... \n"
+ " `'''::::::;;;;;;;;;;;;;;;;:`...........................';;;;;;;;;;;;;;;;:::::''''. \n"
+ " .;;;;;;;;;;;;;;;;;;;;::;;;;'. E r e b e ';;;;::;;;;;;;;;;;;;;;;;;;:. \n"
+ " .:;;;;;;;;;;;;;:'`.. ';;;;:'`. .::. .`':;;;;' ..`':;;;;;;;;;;;;;' \n"
+ " .;;;;;;;;;'`.. .':;;;;;;;::'` .:;;;. `'::;;;;;;;:'. ..`';;;;;;;;' \n"
+ " .'::``. .':;;;;:::;:::;;;` .:;;;;;. `;;;;::;;::;;;;:'. .`'::' \n"
+ " .`:;;;;;:` .:;;;;;;: .:;;;;;;:. ':;;;;;:. .:;;;;;:`. \n"
+ " .`:;;;;;;:` ';;;:`.. .:;;;;;;;;:. `:;;;' `:;;;;;;'`. \n"
+ " `':;;;;;;:`. `;;;;' .:;;;;;;;;;;;. `;;;;` .`:;;:;;;;'. \n"
+ " `':;;;;;'. .:;:;:. ':;;;;;;;;;:' .:;;;;. .';;;;;:'. \n"
+ " .`':'. .:;;;;: .':;;;;:`. ';::;:. .':'. \n"
+ " .:;;;;;` .''. .:;;:. .''. `;;;;;:. \n"
+ " .````''. `;;;` ':;;:' `;;:. .''````. \n"
+ " `;;:. .::::::. .';:. \n"
+ " ;;;;;;;;;;:`. ':::::' .`:;:;;;;;;;; \n"
+ " ';::::::::;;:. ':::' .:;;:''':;;;:' \n"
+ " `':` .` ':' ``. ':' \n"
+ " `. ` .` \n"
+ "--iletaitunefois\n"
+ "Content-Type: text/plain; charset=utf-8; format=flowed\n"
+ "Content-Transfer-Encoding: 8bit\n\n"
+ _message + "\n\n";
/*-----------------------------------------------------------------------------
* On ajoute les pièces-jointes dans le message
*-----------------------------------------------------------------------------*/
for(auto& pieceJointe: _piecesJointes) {
char* fichierEncode = Base64::encodeFromFile( pieceJointe );
message += string("\n--iletaitunefois\n")
+ "Content-Type: " + Mail::getMimeType( pieceJointe ) + ";"
+ " name=\""
+ pieceJointe
+ "\"\n"
+ "Content-Transfer-Encoding: base64\n"
+ "Content-Disposition: attachment;"
+ " filename=\""
+ pieceJointe
+ "\"\n\n"
+ fichierEncode;
delete[] fichierEncode;
}
/*-----------------------------------------------------------------------------
* On termine l'echange avec le serveur smtp
*-----------------------------------------------------------------------------*/
message += string("\n--iletaitunefois--\n")
+ ".\r\n"
+ "QUIT";
_socket.write( message );
cout << _socket.read( 500 ) << endl;
}
/*
* === FUNCTION ======================================================================
* Name: explodeString
* Description: Permet d'extraire toutes les sous-chaines séparées par un delimiteur
* Parametres: chaine -> La chaine à découper
* separator -> Le delimiteur
* conteneur -> le vector dans lequel stocker les chaines extraites
* =====================================================================================
*/
void Mail::explodeString( string& chaine, string separator, vector<string>& conteneur ) {
int found = chaine.find_first_of( separator );
while( found != ((int) string::npos) ) {
if( found > 0 ) {
conteneur.push_back( chaine.substr( 0, found ));
}
chaine = chaine.substr( found + 1 );
found = chaine.find_first_of( separator );
}
if ( chaine.length() > 0 ) {
conteneur.push_back( chaine );
}
}
string Mail::getMimeType(const string& nomFichier ){
string ligne, mime, nomFic;
bool trouve = false;
nomFic = nomFichier.substr( nomFichier.find_last_of( '.' ) );
ifstream mimeListe( "mime.type", ios::in );
if( !mimeListe.is_open() )
throw ios_base::failure("Impossible d'ouvrir le fichier mime.type" );
while( !trouve && getline( mimeListe, ligne ) ) {
if( ligne.substr(0, ligne.find_first_of( '\t' ) - 1 ) == nomFic ){
trouve = true;
mime = ligne.substr( ligne.find_first_of( '\t' ) + 1 );
}
}
if( mime.empty() ){
mime = "application/octet-stream";
}
mimeListe.close();
return mime;
}
| true |
95123fbeb34d54fcbe2ddab37f2a39f5fcfb2bf5 | C++ | seanzaretzky23/AdvancedProg | /client/src/BoardCell.cpp | UTF-8 | 2,241 | 3.484375 | 3 | [] | no_license | /****************************************************************
* Student name: sean zaretzky(209164086), yaniv zimmer (318849908)
* Course Exercise Group: 03, 05
*****************************************************************/
#include "BoardCell.h"
BoardCell::BoardCell(int xCor, int yCor): xCor(xCor), yCor(yCor) {}
BoardCell::BoardCell(const BoardCell &existingBoardCell): xCor(existingBoardCell.getXCor()),
yCor(existingBoardCell.getYCor()) {}
int BoardCell::getXCor() const {
return this->xCor;
}
int BoardCell::getYCor() const {
return this->yCor;
}
string BoardCell::boardCellToString() const {
string str;
stringstream convertX, convertY;
//adjusting the co'ordinates because the board starts at 1 not 0
convertX << this->xCor + 1;
convertY << this->yCor + 1;
str = "(" + convertX.str() + "," + convertY.str() + ")";
return str;
}
bool BoardCell::operator==(const BoardCell &boardCell) const {
return ((this->xCor == boardCell.xCor) && (this->yCor == boardCell.yCor));
}
BoardCell::BoardCell(const string &str) {
//variables helping to build the co'ordinates from the input string
int xSum = 0, ySum = 0;
int k;
int i = str.length()-1;
int j = 1;
while(!((str[i] <= '9')&&(str[i] >= '0')))
{
if(str[i]!=')')
throw "oh oh- not ) after last num";
i--;
}
//get the second cord.
while((str[i] <= '9')&&(str[i] >= '0'))
{
ySum += j *( str[i] - '0');
i--;
j *= 10;
}
j = 1;
if(str[i]!=',')
throw "oh-oh no , before last num ";
//get the non num chars between the nums
k=i-1;
while(!((str[i] <= '9')&&(str[i] >= '0')))
{
i--;
}
if(i!=k)
throw "oh-oh to many chars between nums ";
//get the first cord.
while((str[i] <= '9')&&(str[i] >= '0'))
{
xSum += j *( str[i] - '0');
i--;
j *= 10;
}
if(str[i]!='(')
throw "oh-oh no ( before last num ";
this->xCor = xSum-1;
this->yCor = ySum-1;
if(str[0]!='(')
throw "oh-oh not starting with ( ";
if(str[str.length()-1]!=')')
throw "oh-oh not ending with ) ";
} | true |
5902629ee24bb3c6c044b890e306254f132e3356 | C++ | wallwpcab/hello-world | /lcs.cpp | UTF-8 | 605 | 3.109375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int max(int a, int b);
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
if (m == 0 || n == 0)
return -1;
if (X[m-1] != Y[n-1])
return 1 + lcs(X,Y,m-1,n-1);
else
return max(lcs(X,Y,m,n-1), lcs(X, Y, m-1, n));
}
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Driver program to test above function */
int main()
{
char X[123]={0};
char Y[234]={0};
scanf("%s%s",X,Y);
int m = strlen(X);
int n = strlen(Y);
printf("%d\n", lcs( X, Y, m, n )+1);
return 0;
}
| true |
806a40b67f470d4c3b324c929da7c3560f790c44 | C++ | Abhishek150598/Algorithms_for_cp | /SCC.cpp | UTF-8 | 1,674 | 3.09375 | 3 | [] | no_license | //STRONGLY CONNECTED COMPONENTS USING KOSARAJU'S ALGORITHM
//1 BASED INDEXING FOR VERTICES
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
bool visited[10001];
vector <lli> adjl[10001];
vector <lli> rev_adjl[10001];
stack <lli> s;
//FUNCTION FOR FIRST RECURSIVE DFS
void rec_dfs(lli i)
{
visited[i]=true;
vector <lli>::iterator it=adjl[i].begin();
while(it!=adjl[i].end())
{
if(!visited[*it])
rec_dfs(*it);
it++;
}
s.push(i);
}
//FUNCTION FOR SECOND RECURSIVE DFS
void rec_dfs2(lli i)
{
visited[i]=true;
cout<<i<<" ";
vector <lli>::iterator it=rev_adjl[i].begin();
while(it!=rev_adjl[i].end())
{
if(!visited[*it])
rec_dfs2(*it);
it++;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
lli i,V,E,a,b;
//Taking inputs for the graph
cin>>V>>E;
for(i=0;i<E;i++)
{
cin>>a>>b;
adjl[a].push_back(b);
}
//Mark all vertices as not visited (for 1st DFS)
for(i=1;i<=V;i++)
visited[i] = false;
//Performing DFS and storing nodes into a stack
for(i=1;i<=V;i++)
{
if(!visited[i])
rec_dfs(i);
}
//Obtaining the reverse graph
for(i=1;i<=V;i++)
{
vector <lli>::iterator it=adjl[i].begin();
while(it!=adjl[i].end())
{
rev_adjl[*it].push_back(i);
it++;
}
}
//Mark all vertices as not visited (for 2nd DFS)
for(i=1;i<=V;i++)
visited[i] = false;
//Performing 2nd DFS and printing the SCCs
while(!s.empty())
{
lli v=s.top();
s.pop();
if(!visited[v])
{
rec_dfs2(v);
cout<<endl;
}
}
}
| true |
65b0975e6c9ec831e6665816ceac794019d932aa | C++ | k911mipt/made_2019_algo | /14_1/graph.h | UTF-8 | 2,610 | 3.140625 | 3 | [
"MIT"
] | permissive | #include <unordered_set>
#include <unordered_map>
#include <set>
#include <vector>
using std::unordered_set;
using std::unordered_map;
using std::set;
using std::vector;
using uint = uint32_t;
struct Edge {
uint v = ~0;
uint weight = ~0;
Edge(const uint _v, const uint _weight) : v(_v), weight(_weight) {}
bool operator<(const Edge& rhs) const& {
return weight < rhs.weight || (weight == rhs.weight && v < rhs.v);
}
};
class Graph {
private:
vector<vector<Edge>> vertexes_;
public:
explicit Graph(uint v_count)
: vertexes_(v_count)
{
}
void AddEdge(uint v1, uint v2, uint weight) {
if (v1 == v2) {
return; // self-loops cannot be bridges
}
vertexes_[v1].emplace_back(v2, weight);
vertexes_[v2].emplace_back(v1, weight);
}
uint MST_Prim() {
uint result = 0;
set<Edge> edges; // add edges from every new MST node here to choose best at each iteration
unordered_set<uint> used; // vertexes already picked in MST
std::unordered_map<uint, uint> weights_to; // key - vertex num, value - minimal weight *to* vertex
edges.emplace(0, 0);
while (!edges.empty()) {
auto e_from = *edges.begin();
edges.erase(edges.begin());
used.insert(e_from.v);
result += e_from.weight;
auto& vertex_edges = vertexes_[e_from.v];
for (uint i = 0; i < vertex_edges.size(); ++i) {
while (i != vertex_edges.size() && used.find(vertex_edges[i].v) != used.end()) {
// Get rid of all used edges to not iterate through them again
vertex_edges[i] = vertex_edges.back();
vertex_edges.pop_back();
}
if (i == vertex_edges.size()) {
continue;
}
const auto& e_to = vertex_edges[i];
const auto& existing_edge = weights_to.find(e_to.v);
if (existing_edge == weights_to.end()) {
// candidate edge to be picked
edges.insert(e_to);
weights_to[e_to.v] = e_to.weight;
}
else if (existing_edge->second > e_to.weight) {
// replace previous candidate edge with a better one
edges.erase({ existing_edge->first, existing_edge->second });
edges.insert(e_to);
weights_to[e_to.v] = e_to.weight;
}
}
}
return result;
}
}; | true |
514deac078ed6caf6431f6c199b3b33d2c50588d | C++ | simon198805/cppExp | /implicit/implicit.cpp | UTF-8 | 598 | 3.078125 | 3 | [] | no_license | #include <iostream>
using std::cout;
using std::endl;
class MyExplicitClass
{
public:
explicit MyExplicitClass(int par1);
};
MyExplicitClass::MyExplicitClass(int par1)
{
cout << __PRETTY_FUNCTION__ << " int constructor got " << par1 << endl;
}
class MyClass
{
private:
/* data */
public:
MyClass(int par1);
};
MyClass::MyClass(int par1)
{
cout << __PRETTY_FUNCTION__ << " int constructor got " << par1 << endl;
}
int main(int argc, char const *argv[])
{
//MyClass myClass = 1; //err
MyExplicitClass mec2(1);
MyClass mc1 = 1;
MyClass mc2(1);
return 0;
}
| true |
8f96af1968819a4f302e65c1048d839c760444dd | C++ | ImagineMiracle-wxn/Book_Management_System | /图书馆管理系统/Library_Reader.cpp | GB18030 | 8,600 | 3.03125 | 3 | [] | no_license | #include "Library_Reader.h"
Reader * Readers = NULL;
Reader::Reader()
{
next = NULL;
if (Readers)
{
Reader * p = Get_Readers_Index();
while (p->Next())
{
p = p->Next();
}
p->Set_Next(this);
}
}
Reader::Reader(string Id, string Pw, const string name, const char sex)
{
this->next = NULL;
this->Reader_ID = Id;
this->Reader_PW = Pw;
this->Reader_Name = name;
this->Reader_Sex = sex;
if (Readers)
{
Reader * p = Get_Readers_Index();
while (p->Next())
{
p = p->Next();
}
p->Set_Next(this);
}
}
string Reader::Get_Reader_ID()
{
return Reader_ID;
}
string Reader::Get_Reader_PW()
{
return Reader_PW;
}
string Reader::Get_Reader_Name()
{
return Reader_Name;
}
char Reader::Get_Reader_Sex()
{
return Reader_Sex;
}
struct Borrow_Detail * Reader::Get_Borrow_Array()
{
return Borrow;
}
void Reader::Set_Reader_ID(const string id)
{
Reader_ID = id;
}
void Reader::Set_Reader_PW(const string pw)
{
Reader_PW = pw;
}
void Reader::Set_Reader_Name(const string name)
{
Reader_Name = name;
}
void Reader::Set_Reader_Sex(const char sex)
{
Reader_Sex = sex;
}
bool Reader::Find_Book_in_Borrow_By_onwself(const string Book_Name, int * n)
{
for (int i = 0; i < READER_BORROW_MAX; i++)
{
if (!Borrow[i].Book_Name.empty())
{
if (Book_Name == Borrow[i].Book_Name)
{
*n = i;
return true;
}
}
}
*n = -1;
return false;
}
void Reader::Show_Borrow_Book()
{
for (int i = 0; i < READER_BORROW_MAX; i++)
{
if (Borrow[i].Book_Name.empty() != true)
{
cout << Borrow[i].ID << " ";
cout << Borrow[i].Book_Name << " ";
}
if (i == 4)
{
cout << endl;
}
}
cout << endl;
}
bool Reader::Authentication(const string pw)
{
if (pw == Get_Reader_PW())
{
return true;
}
return false;
}
bool Reader::Borrow_Book(const string Book_Name)
{
Book * p = NULL;
p = Seach_in_Library_By_Name_Reader(Book_Name);
if (p)
{
int i = 0;
while (!Borrow[i++].Book_Name.empty())
{
if (i == 10)
{
break;
}
}
if (i == 10)
{
cout << "˻Ѵ뼰ʱĶ!!!" << endl;
return false;
}
else
{
this->Borrow[i - 1].Book_Name = p->Get_Book_Name();
this->Borrow[i - 1].ID = p->Get_Book_ID();
p->Set_Book_Nums(p->Get_Book_Nums() - 1);
time_t t = time(0);
memcpy((void *)this->Borrow[i - 1].Borrow_Time, (void *)ctime(&t), TIME_LENTH);
return true;
}
}
return false;
}
bool Reader::Borrow_Book(const int Book_ID)
{
Book * p = NULL;
stringstream ss;
ss << Book_ID;
p = Seach_in_Library_By_ID_Reader(ss.str());
if (p)
{
int i = 0;
while (!Borrow[i++].Book_Name.empty())
{
if (i == 10)
{
break;
}
}
if (i == 10)
{
cout << "˻Ѵ뼰ʱĶ!!!" << endl;
return false;
}
else
{
this->Borrow[i - 1].Book_Name = p->Get_Book_Name();
this->Borrow[i - 1].ID = p->Get_Book_ID();
p->Set_Book_Nums(p->Get_Book_Nums() - 1);
time_t t = time(0);
memcpy((void *)this->Borrow[i - 1].Borrow_Time, (void *)ctime(&t), TIME_LENTH);
return true;
}
}
return false;
}
bool Reader::Return_the_Book(const string Book_Name)
{
int n = 0;
if (Find_Book_in_Borrow_By_onwself(Book_Name, &n))
{
for (int i = n; i < READER_BORROW_MAX - 1; i++)
{
Borrow[i] = Borrow[i + 1];
}
memset(&Borrow[READER_BORROW_MAX - 1], 0, sizeof(struct Borrow_Detail));
int nums = this->Seach_in_Library_By_Name_Reader(Book_Name)->Get_Book_Nums();
this->Seach_in_Library_By_Name_Reader(Book_Name)->Set_Book_Nums(nums + 1);
return true;
}
return false;
}
bool Reader::Return_the_Book(const int Book_ID)
{
int n = 0;
stringstream ss;
ss << Book_ID;
if (Find_Book_in_Borrow_By_onwself(ss.str(), &n))
{
for (int i = n; i < READER_BORROW_MAX - 1; i++)
{
Borrow[i] = Borrow[i + 1];
}
memset(&Borrow[READER_BORROW_MAX - 1], 0, sizeof(struct Borrow_Detail));
int nums = this->Seach_in_Library_By_Name_Reader(ss.str())->Get_Book_Nums();
this->Seach_in_Library_By_Name_Reader(ss.str())->Set_Book_Nums(nums + 1);
return true;
}
return false;
}
void Reader::Show_Borrow_Book_Detail(void)
{
int i = 0;
string book_name;
while (!this->Borrow[i++].Book_Name.empty())
{
if (i == 10)
{
break;
}
Book * p = Seach_in_Library_By_Name(this->Borrow[i - 1].Book_Name);
cout << " ID : " << std::left << setw(5) << p->Get_Book_ID() << " ";
cout << "Name : " << std::left << setw(15) << p->Get_Book_Name() << " ";
cout << "Press : " << std::left << setw(15) << p->Get_Book_Press() << " ";
cout << "Author : " << std::left << setw(8) << p->Get_Book_Author() << " ";
cout << "Remanent Nums : " << std::left << setw(5) << p->Get_Book_Nums() << " ";
cout << "Borrow Time : " << this->Borrow[i - 1].Borrow_Time << endl;
}
}
void Reader::Show_Books_Detail_in_Library_Reader(void)
{
Show_Books_Detail_in_Library();
}
Book * Reader::Seach_in_Library_By_Name_Reader(const string name)
{
return Seach_in_Library_By_Name(name);
}
void Reader::Seach_in_Library_By_Name_Reader(const string name, int)
{
Seach_in_Library_By_Name(name, 1);
}
Book * Reader::Seach_in_Library_By_ID_Reader(const string id)
{
return Seach_in_Library_By_ID(id);
}
Reader * Reader::Next()
{
return next;
}
void Reader::Borrow_cpy_O(struct Borrow_Detail borrow[READER_BORROW_MAX])
{
if (borrow)
{
memcpy(borrow, Borrow, READER_BORROW_MAX * sizeof(struct Borrow_Detail));
}
else
{
cerr << "Error : Can't op the NULL!!!" << endl;
}
}
void Reader::Borrow_cpy_I(struct Borrow_Detail borrow[READER_BORROW_MAX])
{
if (borrow)
{
memcpy(Borrow, borrow, READER_BORROW_MAX * sizeof(struct Borrow_Detail));
}
else
{
cerr << "Error : Can't op the NULL!!!" << endl;
}
}
void Reader::Set_Next(Reader * reader)
{
this->next = reader;
}
void Init_Reader_List()
{
Readers = new Reader();
if (Readers == NULL)
{
cerr << "Error : Memory allocation error!" << endl;
exit(-1);
}
}
Reader * Get_Readers_Index()
{
return Readers;
}
void Sort_Reader_List(void)
{
for (Reader * i = Get_Readers_Index(); i->Next() != NULL; i = i->Next())
{
for (Reader * j = i->Next(); j->Next() != NULL; j = j->Next())
{
if (i->Next()->Get_Reader_ID() > j->Next()->Get_Reader_ID())
{
string reader_id_tmp = i->Next()->Get_Reader_ID();
string reader_pw_tmp = i->Next()->Get_Reader_PW();
struct Borrow_Detail borrow[READER_BORROW_MAX];
i->Next()->Borrow_cpy_O(borrow);
i->Next()->Set_Reader_ID(j->Next()->Get_Reader_ID());
i->Next()->Set_Reader_PW(j->Next()->Get_Reader_PW());
i->Next()->Borrow_cpy_I(j->Next()->Get_Borrow_Array());
j->Next()->Set_Reader_ID(reader_id_tmp);
j->Next()->Set_Reader_PW(reader_pw_tmp);
j->Next()->Borrow_cpy_I(borrow);
}
}
}
}
int Auto_Allot_ReaderID()
{
Reader * p = Get_Readers_Index();
int Reader_ID = 0;
Sort_Reader_List();
if (Get_Readers_Index()->Next())
{
while (p->Next())
{
if (p->Next()->Next())
{
if ((atoi(p->Next()->Get_Reader_ID().c_str()) + 1) != atoi(p->Next()->Next()->Get_Reader_ID().c_str()))
{
Reader_ID = atoi(p->Next()->Get_Reader_ID().c_str()) + 1;
return Reader_ID;
}
}
p = p->Next();
}
istringstream iss(p->Get_Reader_ID());
iss >> Reader_ID;
Reader_ID++;
return Reader_ID;
}
else
{
Reader_ID = 0;
return Reader_ID;
}
}
void R_Add_Reader_to_Reader_List(string pw, const string name, const char sex)
{
stringstream ss;
ss << Auto_Allot_ReaderID();
Reader * p = new Reader(ss.str(), pw, name, sex);
}
void R_Del_Reader_from_Reader_List(const string Reader_ID, const string Reader_pw)
{
Reader * p = Get_Readers_Index();
Reader * tmp = NULL;
int choose = 0;
while (p->Next())
{
if (p->Next()->Get_Reader_ID() == Reader_ID)
{
if (p->Next()->Authentication(Reader_pw))
{
if (p->Next()->Get_Borrow_Array()[0].Book_Name.empty())
{
while (choose != 1 && choose != 2)
{
cout << " " << endl << endl << endl;
cout << "-----------Ƿע(1. 2.)" << endl;
cin >> choose;
}
if (1 == choose)
{
tmp = p->Next();
p->Set_Next(p->Next()->Next());
delete tmp;
}
cout << " " << endl << endl << endl;
cout << "------------------עɹ!!!ӭ´ʹ!!!" << endl;
}
else
{
cout << " " << endl << endl << endl;
cout << "-----------עʧ!!!" << endl;
cout << "-----------Ƚ黹ע˺ţл!!! 밴!" << endl;
}
}
break;
}
p = p->Next();
}
} | true |
19007169bea214e5d583399edd699602e090d95b | C++ | manmeet0307/Pepcoding-IP | /Dynamic-Programming/russian-doll-envelope.cpp | UTF-8 | 1,256 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<bits/stdc++.h>
using namespace std;
int maxEnvelopes(vector<vector<int> >& envelopes) {
//Write your code here
if(envelopes.size() == 0) return 0;
vector<pair<int,int> > v(envelopes.size());
for(int i=0;i< envelopes.size() ;i++)
{
v[i] = make_pair(envelopes[i][0] , envelopes[i][1]);
}
sort(v.begin() , v.end());
int n = envelopes.size();
int lis[n] ;
int mlis = 1;
for(int i=0;i<n;i++)
{
lis[i] = 1;
}
for(int i=1;i<n;i++)
{
for(int x = i-1 ;x >=0 ; x--)
{
if(v[x].second < v[i].second && v[x].first != v[i].first )
{
lis[i] = max(lis[i] , lis[x] + 1);
}
}
mlis = max(mlis , lis[i]);
}
// for(int i=0;i<n;i++)
// {
// cout<<"pair array " <<v[i].first<<" " << v[i].second<<endl;
// cout<<"lis: "<<lis[i] <<endl;
// }
return mlis;
}
int main(){
int r;
cin>>r;
vector<vector<int> > envelopes(r,vector<int>(2));
for(int i=0;i<r;i++){
for(int j=0;j<2;j++){
cin>>envelopes[i][j];
}
}
cout<<maxEnvelopes(envelopes)<<endl;
}
| true |
830df3fd37c28894c1dc1b146d2651a9ba6b4cc5 | C++ | NobleRichard/CSCI-20 | /Lab13/Lab13.cpp | UTF-8 | 959 | 3.625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int years;
int future;
int sec = 60;
int minu = 60;
int hour = 24;
int days = 365;
double per = 12;
int pop = 325765736; //population
int net = 1; //number of people added every second p/s
double netgain ; // net gain per year
int gain; // population added with population over years
int main() {
cout << "The population of the United States on August 30th, 2017 was 325,765,736 people." << endl;
cout << "Type in how many years into the future you would like to travel, so that you may view the population number there." << endl;
cin >> years;
netgain = (net / per * sec * minu * hour * days);
gain = pop + (years * netgain);
future = 2017 + years;
cout << "There will be approximately, " << gain << " people alive in the United States in the year " << future << "." << endl;
return 0;
} | true |
ceafcf35cb343a69c41730812de40dc752aed188 | C++ | wembikon/flow | /src/pub/yano/flow/flow.h | UTF-8 | 657 | 2.890625 | 3 | [
"MIT"
] | permissive | /**
* Copyright (C) 2019 Adrian T Visarra
*/
#pragma once
#include <system_error>
#include <type_traits>
namespace yano {
class Flow final {
public:
Flow() = default;
Flow(std::error_code ec) : _ec(ec) {}
inline std::error_code ec() const { return _ec; }
template <typename HappyPath, typename = std::enable_if_t<
std::is_convertible_v<std::invoke_result_t<HappyPath>, Flow>>>
Flow operator|(HappyPath hpath) const {
if (_ec) {
return _ec;
}
return hpath();
}
inline std::error_code operator|(std::error_code) const { return _ec; }
private:
std::error_code _ec;
};
} // namespace yano | true |
db0160cce8db642349dfc869ee4bed710ca20f88 | C++ | cyp0922/Algorithm-Code | /나무 재테크_16235번.cpp | UHC | 1,837 | 2.625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
#include<cstring>
#include<queue>
#include<deque>
using namespace std;
int N, M, K;
int A[11][11];
int map[11][11];
deque<pair<int, pair<int, int>>> dq;
int dx[] = { -1,0,1,1,1,0,-1,-1 }; // ܺ
int dy[] = { -1,-1,-1,0,1,1,1,0 };
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> N >> M >> K; //
for (int j = 1; j <= N; j++) {
for (int i = 1; i <= N; i++) {
cin >> A[j][i];
map[j][i] = 5;
}
}
int x, y, z; // ġ
for (int i = 0; i < M; i++) {
cin >> x >> y >> z;
dq.push_back({ z,{ x, y } });
}
for (int p = 0; p < K; p++) {
queue<pair<int, pair<int, int>>> live;
queue<pair<int, pair<int, int>>> dead;
while (!dq.empty()) { //
int b = dq.front().second.first;
int a = dq.front().second.second;
int age = dq.front().first;
dq.pop_front();
if (map[b][a] - age >= 0) {
map[b][a] = map[b][a] - age;
age++;
live.push({ age,{b,a} });
}
else { // ״
dead.push({ age,{b,a} });
}
}
while (!dead.empty()) { //
int b = dead.front().second.first;
int a = dead.front().second.second;
int age = dead.front().first;
dead.pop();
map[b][a] += age / 2;
}
while (!live.empty()) { //
int b = live.front().second.first;
int a = live.front().second.second;
int age = live.front().first;
live.pop();
dq.push_back({ age,{b,a} });
if (age % 5 == 0) {
for (int i = 0; i < 8; i++) {
int nx = a + dx[i];
int ny = b + dy[i];
if (nx >= 1 && nx <= N && ny >= 1 && ny <= N) {
dq.push_front({ 1,{ny,nx} });
}
}
}
}
//ܿ
for (int j = 1; j <= N; j++) {
for (int i = 1; i <= N; i++) {
map[j][i] += A[j][i];
}
}
}
cout << dq.size();
} | true |
ca440220df94eb624abf82ef649945162320bdf8 | C++ | alexsilviu05/sdd-2018 | /AVLTree/main.cpp | UTF-8 | 3,365 | 3.828125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Book {
int year;
char *title;
};
struct Node {
Book data;
Node * left;
Node * right;
};
struct AVLTree {
Node * root;
};
Book createBook(int year, char * title)
{
Book b;
b.year = year;
b.title = (char *)malloc(sizeof(char) * strlen(title) + 1);
strcpy(b.title, title);
return b;
}
Node * createNode(Book b)
{
Node * newNode = (Node*)malloc(sizeof(Node));
newNode->data = b;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void printBook(Book b)
{
printf("Year: %d\nTitle: %s\n", b.year, b.title);
}
int calculateHeight(Node * root) {
if (root) {
int left = calculateHeight(root->left);
int right = calculateHeight(root->right);
// get max
return (left > right ? left : right) + 1;
}
else {
return 0;
}
}
int balanceFactor(Node * root) {
return calculateHeight(root->right) - calculateHeight(root->left);
}
Node * rotateToLeft(Node * root) {
Node* temp = root->right;
root->right = temp->left;
temp->left = root;
return temp;
}
Node * rotateToRight(Node * root) {
Node* temp = root->left;
root->left = temp->right;
temp->right = root;
return temp;
}
Node * insertInAVLTree(Node * root, Book book)
{
if (root != NULL)
{
if (book.year < root->data.year)
{
root->left = insertInAVLTree(root->left, book);
}
else {
root->right = insertInAVLTree(root->right, book);
}
int bf = balanceFactor(root);
if (bf == 2)
{
if (balanceFactor(root->right) == 1)
{
root = rotateToLeft(root);
}
else {
root->right = rotateToRight(root->right);
root = rotateToLeft(root);
}
}
if (bf == -2)
{
if (balanceFactor(root->left) == -1)
{
root = rotateToRight(root);
}
else {
root->left = rotateToLeft(root->left);
root = rotateToRight(root);
}
}
}
else {
root = createNode(book);
}
return root;
}
void inOrderPrintTree(Node * root)
{
if (root != NULL)
{
inOrderPrintTree(root->left);
printBook(root->data);
inOrderPrintTree(root->right);
}
}
Book * getBooksAtLevel(Node * root, int level)
{
if (root != NULL) {
if (level == 1) {
printBook(root->data);
}
else {
printByLevel(root->left, level - 1);
printByLevel(root->right, level - 1);
}
}
}
void printByLevel(Node * root, int level) {
if (root != NULL) {
if (level == 1) {
printBook(root->data);
}
else {
printByLevel(root->left, level - 1);
printByLevel(root->right, level - 1);
}
}
}
int main()
{
Book b = createBook(2011, "Fratii Karamazov");
AVLTree tree;
tree.root = NULL;
tree.root = insertInAVLTree(tree.root, b);
tree.root = insertInAVLTree(tree.root, createBook(2004, "Asa grait-a Zarathustra"));
tree.root = insertInAVLTree(tree.root, createBook(2010, "O zi din viata lui Ivan Denisovici"));
tree.root = insertInAVLTree(tree.root, createBook(2005, "1984"));
tree.root = insertInAVLTree(tree.root, createBook(2001, "Fahrenheit 451"));
tree.root = insertInAVLTree(tree.root, createBook(1999, "Picnic la marginea drumului"));
tree.root = insertInAVLTree(tree.root, createBook(2018, "Biblia"));
inOrderPrintTree(tree.root);
int treeHeight = calculateHeight(tree.root);
printf("\nHeight: %d\n", treeHeight);
printf("\Balance factor: %d\n", balanceFactor(tree.root));
for (int i = 1; i <= treeHeight; i++)
{
printf("\nLevel: %d\n", i);
printByLevel(tree.root, i);
}
return 0;
} | true |