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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4cc2fc2ebe2af547150ae361f00e954359dd7229 | C++ | csclyde/TGL | /Model/ResourceController.cpp | UTF-8 | 4,183 | 2.640625 | 3 | [] | no_license | #include "../Model/ResourceController.h"
ResourceController::ResourceController()
{
undo = new QUndoStack;
undo->setUndoLimit(500);
clipboard = new Clipboard;
}
ResourceController::~ResourceController()
{
delete clipboard;
}
void ResourceController::PurgeUndoStack()
{
undo->clear();
}
int ResourceController::GetTileWidth()
{
return levelProperties.GetTileWidth();
}
int ResourceController::GetTileHeight()
{
return levelProperties.GetTileHeight();
}
int ResourceController::AddImage(Image *newImage)
{
if(newImage == NULL)
newImage = new Image;
newImage->SetType(ImageType);
AddResourceCommand *add = new AddResourceCommand(newImage, &images);
undo->push(add);
emit ResourceAdded(newImage->GetID());
return 0;
}
bool ResourceController::DeleteImage(int ID)
{
if(images.value(ID))
{
DeleteResourceCommand *del = new DeleteResourceCommand(images[ID], &images);
undo->push(del);
emit ResourceDeleted(ID);
return true;
}
return false;
}
QImage *ResourceController::GetTileset()
{
if(levelProperties.GetTilesetID() == 0)
return NULL;
Image *tempImage = GetImage(levelProperties.GetTilesetID());
if(tempImage)
return tempImage->GetImage();
else
return NULL;
}
QPixmap ResourceController::GetTilePixmap(TileCoord coord)
{
if(pixmapCache.contains(coord))
return pixmapCache[coord];
QImage *tempTileset = GetTileset();
if(tempTileset == NULL)
return QPixmap();
QImage tempImage = *tempTileset;
if(tempImage.isNull())
return QPixmap();
tempImage = tempImage.copy(levelProperties.GetTileWidth() * coord.first, levelProperties.GetTileHeight() * coord.second, levelProperties.GetTileWidth(), levelProperties.GetTileHeight());
pixmapCache[coord] = QPixmap::fromImage(tempImage);
return pixmapCache[coord];
}
TileLayer *ResourceController::AddTileLayer(TileLayer *layer)
{
if(layer == NULL)
layer = new TileLayer;
layer->SetType(TileLayerType);
layers[layer->GetID()] = layer;
emit ResourceAdded(layer->GetID());
emit LayerAdded(layer->GetID());
return layer;
}
void ResourceController::DeleteTileLayer(int ID)
{
if(layers.contains(ID))
{
delete layers[ID];
layers[ID] = NULL;
layers.remove(ID);
emit ResourceDeleted(ID);
emit LayerRemoved(ID);
}
}
TileLayer *ResourceController::GetTileLayer(int ID)
{
if(layers.value(ID))
return layers[ID];
return NULL;
}
QList<TileLayer *> ResourceController::GetAllLayers()
{
return layers.values();
}
Image *ResourceController::GetImage(int imageID)
{
if(images.value(imageID))
return images[imageID];
return NULL;
}
QList<Image *> ResourceController::GetAllImages()
{
return images.values();
}
void ResourceController::DestroyAllResources()
{
undo->clear();
//destroy the images
QList<Image*> imageList = images.values();
for(int i = 0; i < imageList.count(); i++)
{
emit ResourceDeleted(imageList[i]->GetID());
delete imageList[i];
imageList[i] = NULL;
}
images.clear();
QList<TileLayer*> layerList = layers.values();
for(int i = 0; i < layerList.count(); i++)
{
emit ResourceDeleted(layerList[i]->GetID());
emit LayerRemoved(layerList[i]->GetID());
delete layerList[i];
layerList[i] = NULL;
}
layers.clear();
}
void ResourceController::Undo()
{
undo->undo();
}
void ResourceController::Redo()
{
undo->redo();
}
ResourceNode *ResourceController::GetResource(int ID)
{
if(ID == levelProperties.GetID())
return &levelProperties;
QHash<int,Image*>::iterator imageIter;
for(imageIter = images.begin(); imageIter != images.end(); ++imageIter)
{
if(imageIter.key() == ID)
return imageIter.value();
}
QHash<int,TileLayer*>::iterator layerIter;
for(layerIter = layers.begin(); layerIter != layers.end(); ++layerIter)
{
if(layerIter.key() == ID)
return layerIter.value();
}
return NULL;
}
| true |
e5629f59048a808c2f0dc2649567444b66235e76 | C++ | Twinklebear/tray | /src/material/fresnel.cpp | UTF-8 | 1,870 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <cmath>
#include "linalg/util.h"
#include "material/fresnel.h"
Colorf fresnel_dielectric(float cos_i, float cos_t, float eta_i, float eta_t){
Colorf r_par = (eta_t * cos_i - eta_i * cos_t) / (eta_t * cos_i + eta_i * cos_t);
Colorf r_perp = (eta_i * cos_i - eta_t * cos_t) / (eta_i * cos_i + eta_t * cos_t);
return 0.5 * (r_par * r_par + r_perp * r_perp);
}
Colorf fresnel_conductor(float cos_i, const Colorf &eta, const Colorf &k){
Colorf a = (eta * eta + k * k) * cos_i * cos_i;
Colorf r_par = (a - 2 * eta * cos_i + 1) / (a + 2 * eta * cos_i + 1);
a = eta * eta + k * k;
Colorf r_perp = (a - 2 * eta * cos_i + cos_i * cos_i) / (a + 2 * eta * cos_i + cos_i * cos_i);
//These are actually r_par^2 and r_perp^2, so don't square here
return 0.5 * (r_par + r_perp);
}
FresnelDielectric::FresnelDielectric(float eta_i, float eta_t)
: eta_i(eta_i), eta_t(eta_t)
{}
Colorf FresnelDielectric::operator()(float cos_i) const {
//We need to find out which side of the material we're incident on so
//we can pass the correct indices of refraction
cos_i = clamp(cos_i, -1.f, 1.f);
float ei = cos_i > 0 ? eta_i : eta_t;
float et = cos_i > 0 ? eta_t : eta_i;
float sin_t = ei / et * std::sqrt(std::max(0.f, 1.f - cos_i * cos_i));
//Handle total internal reflection
if (sin_t >= 1){
return Colorf{1};
}
float cos_t = std::sqrt(std::max(0.f, 1.f - sin_t * sin_t));
return fresnel_dielectric(std::abs(cos_i), cos_t, ei, et);
}
FresnelConductor::FresnelConductor(const Colorf &eta, const Colorf &k) : eta(eta), k(k){}
Colorf FresnelConductor::operator()(float cos_i) const {
return fresnel_conductor(std::abs(cos_i), eta, k);
}
Colorf FresnelNoOp::operator()(float) const {
return Colorf{1};
}
FresnelFlip::FresnelFlip(const Fresnel *fresnel) : fresnel(fresnel){}
Colorf FresnelFlip::operator()(float cos_i) const {
return 1 - (*fresnel)(cos_i);
}
| true |
a97eae59e1180f7fc784f32a183d085e11d59c91 | C++ | Im-Rudra/LightOJ-Solutions | /1311-Unlucky-Bird.cpp | UTF-8 | 614 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
double v1;
double v2;
double a1;
double a2;
double v3;
int t;
double tim;
double ans;
double dis;
double tim1;
double tim2;
scanf("%d", &t);
for (int cs = 1; cs <= t; cs++) {
scanf("%lf", &v1);
scanf("%lf", &v2);
scanf("%lf", &v3);
scanf("%lf", &a1);
scanf("%lf", &a2);
tim1 = v1 / a1;
tim2 = v2 / a2;
tim = max(tim1, tim2);
ans = tim * v3;
dis = v1 * tim1 + 0.5 * -a1 * tim1 * tim1;
dis += v2 * tim2 + 0.5 * -a2 * tim2 * tim2;
printf("Case %d: %.9lf %.9lf\n",cs,dis, ans);
}
return 0;
}
| true |
92c01d75dc3f392bb0623c7e0326d8e8e8d10af8 | C++ | cocahack/Missions | /cs23/step2/alu.h | UTF-8 | 856 | 2.84375 | 3 | [] | no_license | //
// Created by MCC on 11/04/2019.
//
#ifndef STEP2_ALU_H
#define STEP2_ALU_H
#include <cstdint>
#include "register.h"
class ALU
{
public:
Word add_impl(const Reg& r1, const Reg& r2)
{
return r1.get_value() + r2.get_value();
}
Word add_impl(const Reg& r1, const Word value)
{
return r1.get_value() + value;
}
Word sub_impl(const Reg& r1, const Reg& r2)
{
return (int16_t )r1.get_value() - (int16_t )r2.get_value();
}
Word sub_impl(const Reg& r1, const Word value)
{
return (int16_t )r1.get_value() - (int16_t )value;
}
Word and_impl(const Reg& r1, const Reg& r2)
{
return r1.get_value() & r2.get_value();
}
Word or_impl(const Reg& r1, const Reg& r2)
{
return r1.get_value() | r2.get_value();
}
}
;
#endif //STEP2_ALU_H
| true |
3ca748289b1e8814b7ba77e946ae050537f8056d | C++ | kamyu104/LeetCode-Solutions | /C++/build-binary-expression-tree-from-infix-expression.cpp | UTF-8 | 1,715 | 3.21875 | 3 | [
"MIT"
] | permissive | // Time: O(n)
// Space: O(n)
// Support +, -, *, /.
class Solution {
public:
Node* expTree(string s) {
static const unordered_map<char, int> precedence = {{'+', 0}, {'-', 0}, {'*', 1}, {'/', 1}};
stack<Node *> operands;
stack<char> operators;
int64_t operand = 0;
for (int i = 0; i < size(s); ++i) {
if (isdigit(s[i])) {
operand = operand * 10 + s[i] - '0';
if (i + 1 == size(s) || !isdigit(s[i + 1])) {
operands.emplace(new Node(operand + '0'));
operand = 0;
}
} else if (s[i] == '(') {
operators.emplace(s[i]);
} else if (s[i] == ')') {
while (!empty(operators) && operators.top() != '(') {
compute(&operands, &operators);
}
operators.pop();
} else if (precedence.count(s[i])) {
while (!empty(operators) && precedence.count(operators.top()) &&
precedence.at(operators.top()) >= precedence.at(s[i])) {
compute(&operands, &operators);
}
operators.emplace(s[i]);
}
}
while (!empty(operators)) {
compute(&operands, &operators);
}
return operands.top();
}
private:
template<typename T>
void compute(stack<T> *operands, stack<char> *operators) {
const auto right = operands->top(); operands->pop();
const auto left = operands->top(); operands->pop();
const char op = operators->top(); operators->pop();
operands->emplace(new Node(op, left, right));
}
};
| true |
5980287a1274e6b1f0ca971b6829efa8c1d51f8c | C++ | Jason0803/Algorithm_ProblemSolving | /Algorithm_cpp/14501_prac/main.cpp | UTF-8 | 667 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int N, ans;
pair<int, int> days[16];
void dfs(int current, pair<int, int> node, int current_sum) {
if(current + node.first > N+1) return;
current_sum += node.second;
if(ans < current_sum) ans = current_sum;
for(int next = current + node.first; next <= N; next++) {
dfs(next, days[next], current_sum);
}
current_sum -= node.second;
}
int main() {
cin >> N;
for(int i=1; i<=N; i++)
cin >> days[i].first >> days[i].second;
for(int start=1; start<=N; start++)
dfs(start, days[start], 0);
cout << ans << '\n';
return 0;
}
| true |
99836c19c51460f31a538f2df448058cb34a3c4f | C++ | ddeka0/CP | /2018-2019/ilya_and_Sticks.cpp | UTF-8 | 1,692 | 3.234375 | 3 | [] | no_license | // http://codeforces.com/contest/525/problem/C
#include <bits/stdc++.h>
using namespace std;
/*template code starts*/
typedef unsigned long long ULL;
typedef long long LL;
template<typename T>
void LOG(T const& t) {
std::cout << t<<endl;
}
template<typename First, typename ... Rest>
void LOG(First const& first, Rest const& ... rest) {
std::cout << first<<" "; LOG(rest ...);
}
/*
please check:
1. **overflow <> type of answer : it may be long long
2. handle special case carefuinty. Avoid making the loop generic for special cases
3. order not needed : sort it
4. For 2D matrix : if possible try to store max/min/best/ values row wise for considering aint cols
5. if the answer reainty exists for a query: then draw the possible structure and observe the property
*/
/* template code ends */
void solve();
int main() {
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
solve();
return 0;
}
int a[100009];
void solve() {
int n;
cin >> n;
for(int i = 1;i<=n;i++) {
cin >> a[i];
}
// sort it
sort(a+1,a+n+1);
// make a list where each elememnt occurs twice
// reduce one length when required
// make two stick of same length and push in a list or vector
std::vector<int> v;
for(int i = n;i>1;i--) {
if(a[i] - a[i - 1] < 2) {
v.push_back(a[i - 1]); // now we have at least two stick of length a[i - 1]
// there can be more // but has to be even
i--;
}
}
// inside v there are stick lengths, each with frequency 2 ... stick lengths may be equal
// if equal they will remain contiguosly because we have sorted the array initially
int m = v.size();
LL ans = 0;
for(int i = 0;i<m - 1;i = i + 2) {
ans += v[i]*1LL*v[i+1];
}
cout << ans << endl;
} | true |
bba0f4949a9e5ba3714c0b36f7c5a9557663f8ad | C++ | tuanacetinkaya/Daily-Leetcode-Challenge | /January 2021/27.01.2021/vedat.cpp | UTF-8 | 438 | 2.953125 | 3 | [] | no_license | class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
vector<int> pref;
pref.push_back(0);
for (int i=0; i<arr.size(); i++) {
pref.push_back(arr[i] + pref[i]);
}
int ans = 0;
for (int i=1; i<=arr.size(); i+=2) {
for (int j=i; j<=arr.size(); j++) {
ans += pref[j] - pref[j-i];
}
}
return ans;
}
}; | true |
f9383255558de2283df1aee228548066fc35e5e3 | C++ | muhammad-ur-rehman/3x3-Sliding-Tile-Puzzle | /puzzle.cpp | UTF-8 | 3,451 | 3.4375 | 3 | [] | no_license | //Matthew Joyce
#include<iostream>
#include<cassert>
using namespace std;
enum game_status { uncompleted, completed };
struct spacePosition
{
int row, col;
};
struct puzzle
{
game_status status;
int board[3][3];
spacePosition position;
int numberOfMoves;
};
void initializeGoal(puzzle &gam)
{
gam.position.row = 2;
gam.position.col = 2;
int count = 1;
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
gam.board[r][c] = count;
count++;
}
}
gam.status = completed;
}
void up(puzzle &gam)
{
int temp[1][1];
temp[0][0] = gam.board[gam.position.row - 1][gam.position.col];
gam.board[gam.position.row - 1][gam.position.col] = gam.board[gam.position.row][gam.position.col];
gam.board[gam.position.row][gam.position.col] = temp[0][0];
gam.position.row = gam.position.row - 1;
}
void right(puzzle &gam)
{
int temp[1][1];
temp[0][0] = gam.board[gam.position.row][gam.position.col + 1];
gam.board[gam.position.row][gam.position.col + 1] = gam.board[gam.position.row][gam.position.col];
gam.board[gam.position.row][gam.position.col] = temp[0][0];
gam.position.col = gam.position.col + 1;
}
void down(puzzle &gam)
{
int temp[1][1];
temp[0][0] = gam.board[gam.position.row + 1][gam.position.col];
gam.board[gam.position.row + 1][gam.position.col] = gam.board[gam.position.row][gam.position.col];
gam.board[gam.position.row][gam.position.col] = temp[0][0];
gam.position.row = gam.position.row + 1;
}
void left(puzzle &gam)
{
int temp[1][1];
temp[0][0] = gam.board[gam.position.row][gam.position.col - 1];
gam.board[gam.position.row][gam.position.col - 1] = gam.board[gam.position.row][gam.position.col];
gam.board[gam.position.row][gam.position.col] = temp[0][0];
gam.position.col = gam.position.col - 1;
}
puzzle scramblePuzzle(puzzle gam, int shuffle)
{
gam.status = uncompleted;
while (shuffle > 0)
{
int direction = rand() % 4;
switch (direction)
{
//up
case 0:
if (gam.position.row > 0)
{
up(gam);
shuffle = shuffle - 1;
}
else
scramblePuzzle(gam, shuffle);
break;
//Right
case 1:
if (gam.position.col < 2)
{
right(gam);
shuffle = shuffle - 1;
}
else
scramblePuzzle(gam, shuffle);
break;
//Down
case 2:
if (gam.position.row < 2)
{
down(gam);
shuffle = shuffle - 1;
}
else
scramblePuzzle(gam, shuffle);
break;
//Left
case 3:
if (gam.position.col > 0)
{
left(gam);
shuffle = shuffle - 1;
}
else
scramblePuzzle(gam, shuffle);
break;
}
}
return gam;
}
void printPuzzle(puzzle gam)
{
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
if (gam.board[r][c] == 9)
cout << " " << " " << " ";
else
cout << " " << gam.board[r][c] << " ";
}
cout << endl;
}
}
int main()
{
puzzle goalPuzzle;
puzzle game;
initializeGoal(goalPuzzle);
int num = 0;
cout << "Enter max number of moves needed to solve puzzle optimally: ";
cin >> num;
cout << endl;
game = scramblePuzzle(goalPuzzle, num);
printPuzzle(game);
char c;
while (game.status != completed)
{
cout << endl << "Enter:" << endl << "U for Up" << endl << "R for Right"
<< endl << "D for Down " << endl << "L for Left" << endl << endl;
cin >> c;
}
return 0;
} | true |
b70639d1e585f84c3f1d057921f9e1791088d703 | C++ | dmayna/Sudoku | /sudoku/Levels.cpp | UTF-8 | 8,983 | 2.703125 | 3 | [] | no_license | #include "pch.h"
#include "Levels.h"
#include <fstream>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <Windows.h>
using namespace std;
Levels::Levels()
{
filename = "sudokuVeryEasy.txt";
scoreFilename = "veryEasyScore.txt";
playing = true;
score = 100;
average = getAverage();
}
void Levels::loadGrid(void)
{
// create file object
ifstream file(filename);
string line = "";
int index = 0;
int answerIndex = 0;
// read file one line at a time ignoring the comma
while (getline(file, line, ','))
{
// allow string to be read one word at a time
stringstream lineStream(line);
// string to hold word from line
string cell;
// iterate through the line and store cell in vector
while (getline(lineStream, cell))
{
index++;
if (index > gridNumBegin && index <= gridNumEnd)
{
//cout << cell << " | " << index << "\n";
mAnswer_Row.clear();
for (auto i = cell.begin(); i != cell.end(); i++)
{
if (*i == '0')
{
mAnswer_Row.push_back(pair<string, char>("Answer", *i));
}
else
{
mAnswer_Row.push_back(pair<string, char>("Grid", *i));
}
}
mAnswer_Grid.push_back(mAnswer_Row);
}
else if (index <= answerNumEnd && index > answerNumBegin)
{
int s = 0;
for (auto it = cell.begin(); it != cell.end(); it++)
{
if (mAnswer_Grid[answerIndex][s].second == '0')
{
mAnswer_Grid[answerIndex][s].second = *it;
}
s++;
}
answerIndex++;
}
}
cout << "\n";
}
file.close();
}
void Levels::selectGrid(void)
{
// select correct file name baased on difficulty
// select random grids file
srand(time(NULL));
int randomNumber = std::rand() % 10;
if (randomNumber == 0)
{
gridNumBegin = (9 * randomNumber) + 1;
gridNumEnd = 9 * (randomNumber + 1);
answerNumBegin = 9 * (randomNumber + 1);
answerNumEnd = 9 * (randomNumber * +2);
}
else
{
gridNumBegin = 9 * (randomNumber * 2);
gridNumEnd = 9 * ((randomNumber * 2) + 1);
answerNumBegin = 9 * ((randomNumber * 2) + 1);
answerNumEnd = 9 * ((randomNumber * 2) + 2);
}
loadGrid();
printAnswer();
}
void Levels::prindHorizontalBorder(void)
{
char border = 205;
for (int i = 0; i < 35; i++)
{
cout << border;
}
}
void Levels::printGrid(void)
{
system("CLS");
int horizontalIndex = 0;
// used to keep track of columns to print correct border
int verticalIndex;
cout << char(201); prindHorizontalBorder(); cout << char(187) << "\n";
for (auto i = mAnswer_Grid.begin(); i != mAnswer_Grid.end(); i++)
{
verticalIndex = 1;
cout << char(186) << " ";
for (auto j = i->begin(); j != i->end(); j++)
{
//cout << char(186) << " ";
if (j->first == "Grid")
{
SetColor(1);
cout << j->second << " ";
SetColor(7);
}
else if (j->first == "userAnswer")
{
SetColor(2);
cout << j->second << " ";
SetColor(7);
}
else
{
cout << " ";
}
if (verticalIndex % 3 == 0)
{
cout << char(186) << " ";
}
else
{
cout << "| ";
}
verticalIndex++;
}
cout << "\n";
horizontalIndex++;
//print border for middle rows
if (horizontalIndex % 3 == 0 && horizontalIndex != 9)
{
cout << char(204); prindHorizontalBorder(); cout << char(185) << "\n";
}
}
cout << char(200); prindHorizontalBorder(); cout << char(188) << "\n";
}
void Levels::printAnswer(void)
{
// used to keep track of rows to print correct border
int horizontalIndex = 0;
// used to keep track of columns to print correct border
int verticalIndex;
cout << char(201); prindHorizontalBorder(); cout << char(187) << "\n";
for (auto i = mAnswer_Grid.begin(); i != mAnswer_Grid.end(); i++)
{
verticalIndex = 1;
cout << char(186) << " ";
for (auto j = i->begin(); j != i->end(); j++)
{
//cout << char(186) << " ";
if (j->first == "Grid")
{
SetColor(1);
cout << j->second << " ";
SetColor(7);
}
else
{
SetColor(2);
cout << j->second << " ";
SetColor(7);
}
if (verticalIndex % 3 == 0)
{
cout << char(186) << " ";
}
else
{
cout << "| ";
}
verticalIndex++;
}
cout << "\n";
horizontalIndex++;
//print border for middle rows
if (horizontalIndex % 3 == 0 && horizontalIndex != 9)
{
cout << char(204); prindHorizontalBorder(); cout << char(185) << "\n";
}
}
cout << char(200); prindHorizontalBorder(); cout << char(188) << "\n";
}
void Levels::playGame(void)
{
while (playing)
{
if (endOfGame())
{
if (score == 100)
{
cout << "Excellent Player, should try next level\n";
}
if (score >= 80 && score < 100)
{
cout << " Good player, keep practicing on this level\n";
}
if (score >= 60 && score < 80)
{
cout << "OK player... keep practicing on this level if you dare\n";
}
if (score >= 40 && score < 60)
{
cout << "Well.. suggest trying a easier level\n";
}
if (score < 40)
{
cout << "Watch this video on how to play\n";
}
// add score to file for correct level and increment games played variable
ifstream fin(scoreFilename);
int gameScoreTotal;
int gamesPlayed;
while (fin >> gameScoreTotal >> gamesPlayed)
{
gameScoreTotal += score;
gamesPlayed++;
}
average = gameScoreTotal / gamesPlayed;
// write new total score and games played into file
ofstream fout(scoreFilename);
fout << gameScoreTotal << " " << gamesPlayed;
playing = false;
break;
}
cout << "\n\nScore = " << score;
cout << "\nEnter 'kill' into grid to quit game\n";
cout << "Enter 'new' into grid to start a new game\n";
cout << "Enter the Row and Column number of the box you would like to fill >";
int choiceRow, choiceCol;
cin >> choiceRow;
cin >> choiceCol;
while (cin.fail() || choiceRow > 9 || choiceCol > 9 || choiceRow < 1 || choiceCol < 1)
{
cout << "Error please enter a Row and Column number between 1-9 > ";
cin.clear();
cin.ignore(256, '\n');
cin >> choiceRow;
cin >> choiceCol;
}
// if the spot is taken already then alert user and ask again
while (mAnswer_Grid[choiceRow - 1][choiceCol - 1].first == "Grid" || choiceRow > 9 || choiceCol > 9 || choiceRow < 1 || choiceCol < 1 || mAnswer_Grid[choiceRow - 1][choiceCol - 1].first == "userAnswer")
{
cout << "Spot Already Taken! Enter a new Row and Column >";
cin.clear();
cin.ignore(256, '\n');
cin >> choiceRow;
cin >> choiceCol;
}
// otherwise ask user for input into grid
string userAnswer;
cout << "Enter number to enter into grid >";
// check if user answer is valid
cin >> userAnswer;
if (userAnswer == "kill")
{
mAnswer_Row.clear();
mAnswer_Grid.clear();
exit(1);
}
if (userAnswer == "new")
{
mAnswer_Row.clear();
mAnswer_Grid.clear();
break;
}
// if the answer is correct alert user and change the key
if (mAnswer_Grid[choiceRow - 1][choiceCol - 1].second == userAnswer[0])
{
cout << "Correct input\n";
mAnswer_Grid[choiceRow - 1][choiceCol - 1].first = "userAnswer";
printGrid();
}
else
{
// otherwise subtract points
// add algorithm fo find correct spot on the grid to blink error
int row = 0;
int col = 0;
if (choiceRow <= 3)
{
row = choiceRow;
}
if (choiceRow > 3)
{
row = choiceRow + 1;
}
if (choiceRow > 6)
{
row++;
}
// find correct col position
if (choiceCol <= 1)
{
col = choiceCol + 3;
}
if (choiceCol <= 3)
{
col = (choiceCol * 3) + (choiceCol - 2);
}
if (choiceCol > 3)
{
col = (choiceCol * 3) + (choiceCol - 2);
}
// flash error
blink(userAnswer, 4, 0, col, row);
system("CLS");
printGrid();
cout << "-5 Wrong Answer\n";
score -= 5;
cout << "Current Score = " << score;
}
}
}
bool Levels::endOfGame(void)
{
if (score == 0)
{
return true;
}
for (auto i = mAnswer_Grid.begin(); i != mAnswer_Grid.end(); i++)
{
for (auto j = i->begin(); j != i->end(); j++)
{
if (j->first == "Answer")
{
return false;
}
}
}
return true;
}
void Levels::blink(string attempt, int ForgC, int BackC = 0, int row = 0, int col = 0)
{
COORD pos = { row,col };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
for (int i = 0; i < 5; i++) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), ForgC | (BackC << 4));
cout << attempt;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
Sleep(100);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BackC | (ForgC << 4));
cout << attempt;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
Sleep(100);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7 | (BackC << 0));
}
}
void Levels::SetColor(int color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
double Levels::getAverage(void)
{
int total;
int games;
ifstream fin(scoreFilename);
fin >> total >> games;
if (total == 0 || games == 0)
{
return 0;
}
else
{
return total / games;
}
}
| true |
d66d9a33224fe98633fc9ef505a5a41df943c774 | C++ | donkaban/grasshopper | /jni/microGL/logger.h | UTF-8 | 1,551 | 2.5625 | 3 | [] | no_license | #ifndef __GRASSHOPPER_LOGGER__
#define __GRASSHOPPER_LOGGER__
#include <android/log.h>
#include <iostream>
#include <cstdlib>
#include <sstream>
#define _MODULE(tag) static auto LOCAL_LOGGER = std::make_shared<logger>(tag)
#define INFO(...) LOCAL_LOGGER->info(__VA_ARGS__)
#define ERROR(...) LOCAL_LOGGER->error(__VA_ARGS__)
#define PRINT(...) LOCAL_LOGGER->print(__VA_ARGS__)
#define ABORT(...) LOCAL_LOGGER->fatal(__VA_ARGS__)
using strref = const std::string &;
class logger
{
public:
logger(strref tag = "[LOG]") :
_tag(tag)
{}
~logger()
{}
template<typename ... T>
void message(strref prefix, T && ... a)
{
_prn(a...);
__android_log_print(ANDROID_LOG_DEBUG,"[GRASSHOPPER]","[%s] %s",_tag.c_str(),_ss.str().c_str());
_ss.str("");
}
template<typename ... T>
void print(T && ... a)
{
_prn(a...);
gui(_ss.str());
_ss.str("");
}
template<typename ... T> void info(T && ... a) {message("[I]", a...);}
template<typename ... T> void error(T && ... a) {message("[E]", a...);}
template<typename ... T> void fatal(T && ... a) {message("[F]", a...); std::abort();}
private:
std::string _tag;
std::stringstream _ss;
void _prn() {_ss << std::endl;}
template <typename T>
void _prn(const T &t) {_ss << t << std::endl;}
template <typename T, typename... A>
void _prn(const T &head, const A&... tail) {_ss << head;_prn(tail...); }
void gui(strref);
};
#endif | true |
b80672c4cd8abaf8efab235c984136f2a85cb7f7 | C++ | blizmax/synthese_image | /Camera.h | ISO-8859-1 | 8,635 | 2.546875 | 3 | [] | no_license | #pragma once
#include "Component.h"
#include "DirectionalLight.h"
#include "mat.h"
#include "wavefront.h"
#include "texture.h"
#include "program.h"
#include "uniforms.h"
#include <vector>
class Skybox;
using namespace std;
class Camera : public Component
{
private:
Transform projectionMatrix;
int frameWidth = 800;
int frameHeight = 800;
float nearZ = 0.1f;
float farZ = 2000.0f;
float fov = 60.0f;
GLuint frameBuffer;
GLuint colorBuffer; // RGB : albedo.rgb / A : roughness
GLuint normalBuffer; // RGB : normal.xyz / A : metallic
GLuint depthBuffer;
GLuint colorSampler;
GLuint normalSampler;
GLuint depthSampler;
// Post effect
GLuint deferredFinalPass;
GLuint shaderSSAO;
GLuint frameBuffer2;
GLuint colorBuffer2;
GLuint skyboxSampler;
// Previous frame for temporal reprojection
Transform prevProjectionMatrix;
Transform prevViewMatrix;
GLuint prevColorBuffer;
GLuint prevColorSampler;
public:
void Start()
{
SetParameters(frameWidth, frameHeight, fov, nearZ, farZ);
}
void OnDestroy()
{
glDeleteTextures(1, &colorBuffer);
glDeleteTextures(1, &depthBuffer);
glDeleteFramebuffers(1, &frameBuffer);
glDeleteSamplers(1, &colorSampler);
glDeleteSamplers(1, &normalSampler);
glDeleteTextures(1, &colorBuffer2);
glDeleteFramebuffers(1, &frameBuffer2);
glDeleteProgram(deferredFinalPass);
glDeleteTextures(1, &prevColorBuffer);
glDeleteSamplers(1, &prevColorSampler);
}
void LoadDeferredShader(string s)
{
deferredFinalPass = read_program(s.c_str());
}
void SetParameters(const float width, const float height, const float fov, const float nearZ, const float farZ)
{
projectionMatrix = Perspective(fov, width / height, nearZ, farZ);
//projectionMatrix = GetOrthographicMatrix(150.0f, 150.0f, 0.1f, 1000.0f);
}
void SetupFrameBuffer(int width, int height)
{
frameWidth = width;
frameHeight = height;
// Color Buffer setup
glGenTextures(1, &colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0,
GL_RGBA, frameWidth, frameHeight, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glGenerateMipmap(GL_TEXTURE_2D);
glGenSamplers(1, &colorSampler);
glSamplerParameteri(colorSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glSamplerParameteri(colorSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glSamplerParameteri(colorSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glSamplerParameteri(colorSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glGenTextures(1, &prevColorBuffer);
glBindTexture(GL_TEXTURE_2D, prevColorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0,
GL_RGBA, frameWidth, frameHeight, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glGenerateMipmap(GL_TEXTURE_2D);
glGenSamplers(1, &prevColorSampler);
glSamplerParameteri(prevColorSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glSamplerParameteri(prevColorSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glSamplerParameteri(prevColorSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glSamplerParameteri(prevColorSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
// Normal Buffer setup
glGenTextures(1, &normalBuffer);
glBindTexture(GL_TEXTURE_2D, normalBuffer);
glTexImage2D(GL_TEXTURE_2D, 0,
GL_RGBA16F, frameWidth, frameHeight, 0,
GL_RGBA, GL_HALF_FLOAT, nullptr);
glGenerateMipmap(GL_TEXTURE_2D);
glGenSamplers(1, &normalSampler);
glSamplerParameteri(normalSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glSamplerParameteri(normalSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glSamplerParameteri(normalSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glSamplerParameteri(normalSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
// Depth Buffer setup
glGenTextures(1, &depthBuffer);
glBindTexture(GL_TEXTURE_2D, depthBuffer);
glTexImage2D(GL_TEXTURE_2D, 0,
GL_DEPTH_COMPONENT, frameWidth, frameHeight, 0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);
glGenSamplers(1, &depthSampler);
glSamplerParameteri(depthSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glSamplerParameteri(depthSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glSamplerParameteri(depthSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glSamplerParameteri(depthSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
// Frame Buffer setup
glGenFramebuffers(1, &frameBuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, /* attachment */ GL_COLOR_ATTACHMENT0, /* texture */ colorBuffer, /* mipmap level */ 0);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, /* attachment */ GL_COLOR_ATTACHMENT1, /* texture */ normalBuffer, /* mipmap level */ 0);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, /* attachment */ GL_DEPTH_ATTACHMENT, /* texture */ depthBuffer, /* mipmap level */ 0);
// Fragment shader output
GLenum buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glDrawBuffers(2, buffers);
// Color Buffer 2 setup
glGenTextures(1, &colorBuffer2);
glBindTexture(GL_TEXTURE_2D, colorBuffer2);
glTexImage2D(GL_TEXTURE_2D, 0,
GL_RGBA, frameWidth, frameHeight, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glGenerateMipmap(GL_TEXTURE_2D);
// Frame Buffer 2 setup
glGenFramebuffers(1, &frameBuffer2);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer2);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, /* attachment */ GL_COLOR_ATTACHMENT0, /* texture */ colorBuffer2, /* mipmap level */ 0);
// Fragment shader output
GLenum buffers2[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, buffers2);
// Skybox sampler
glGenSamplers(1, &skyboxSampler);
glSamplerParameteri(skyboxSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glSamplerParameteri(skyboxSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glSamplerParameteri(skyboxSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(skyboxSampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glSamplerParameteri(skyboxSampler, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
// Cleanup
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
void FinishDeferredRendering(DirectionalLight* light, Skybox* skybox)
{
BeginPostEffect();
FinalDeferredPassSSR(light, skybox);
EndPostEffect();
}
void BeginPostEffect()
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer2);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorBuffer2, 0);
}
void EndPostEffect()
{
glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBuffer2);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer);
glViewport(0, 0, frameWidth, frameHeight);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glBlitFramebuffer(
0, 0, frameWidth, frameHeight,
0, 0, frameWidth, frameHeight,
GL_COLOR_BUFFER_BIT, GL_LINEAR);
}
void FinalDeferredPassSSR(DirectionalLight* light, Skybox* skybox);
void SSAO();
void DrawPostEffects()
{
glDisable(GL_DEPTH_TEST);
BeginPostEffect();
SSAO();
EndPostEffect();
// Reset before ending
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, colorBuffer, 0);
glFramebufferTexture(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, normalBuffer, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glUseProgram(0);
glEnable(GL_DEPTH_TEST);
}
GLuint GetFrameBuffer()
{
return frameBuffer;
}
GLuint GetColorBuffer()
{
return colorBuffer;
}
GLuint GetNormalBuffer()
{
return normalBuffer;
}
GLuint GetDepthBuffer()
{
return depthBuffer;
}
void UpdatePreviousColorBuffer()
{
glBindTexture(GL_TEXTURE_2D, prevColorBuffer);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, frameWidth, frameHeight, 0);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, frameWidth, frameHeight);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, prevColorBuffer);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
prevProjectionMatrix = projectionMatrix;
prevViewMatrix = GetViewMatrix();
}
/*!
* \brief Rcupre la matrice de projection.
*/
Transform GetProjectionMatrix()
{
return projectionMatrix;
}
/*!
* \brief Rcupre l'inverse de la matrice du monde.
*/
Transform GetViewMatrix();
/*!
* \brief Rcupre la matrice de projection orthographique.
*/
Transform GetOrthographicMatrix(const float width, const float height, const float znear, const float zfar)
{
float w = width / 2.f;
float h = height / 2.f;
return Transform(
1 / w, 0, 0, 0,
0, 1 / h, 0, 0,
0, 0, -2 / (zfar - znear), -(zfar + znear) / (zfar - znear),
0, 0, 0, 1);
}
vector<Vector> GetFrustumNearCorners();
Vector GetNearBottomLeftCorner();
Vector GetFarBottomLeftCorner();
};
| true |
72b12bef36e73827d34c5d4ad0b111000b970c57 | C++ | Leo-778/wangdao | /915/2021t1.cpp | UTF-8 | 1,239 | 2.96875 | 3 | [] | no_license | /*
* @Description: 寻找马鞍点
* @Author: Leo
* @Date: 2021-10-26 19:13:46
* @LastEditTime: 2021-10-27 06:44:00
*/
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
int a[100][100];
int m, n;
cin >> m >> n;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cin >> a[i][j];
}
int count = 0, b[100], c[100];//b是每行最小的数,c是每列最大的数
for (int i = 0; i < n; i++)//找到每列最大的数
{
int mx = 0;
for (int j = 0; j < m; j++)
{
mx > a[j][i] ?: mx = a[j][i];
}
c[i] = mx;
}
for (int i = 0; i < m; i++)//找到每行最大的数
{
int mn = 9999;
for (int j = 0; j < n; j++)
{
mn < a[i][j] ?: mn = a[i][j];
}
b[i] = mn;
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j]==b[i]&&a[i][j]==c[j])
{
printf("%d %d %d\n", i, j, a[i][j]);
count = 1;
}
}
}
if (count==0)
{
cout << "no exit";
}
return 0;
}
| true |
41c2c9d309433fef90806f76ee8ac55d2fff5ccd | C++ | mmaricic/FilesystemManagement | /projekat2/ComplexCommandContainer.cpp | UTF-8 | 815 | 3.390625 | 3 | [] | no_license | #include "ComplexCommandContainer.h"
void ComplexCommandContainer::add(string name, ComplexCommand* cc) {
newCommands.insert(make_pair(name, cc));
}
void ComplexCommandContainer::operator()(const vector<string> &elem) {
int i = newCommands.find(elem[0])->second->argNum();
if (i != elem.size() - 1) {
cout << "Invalid argument number!" << endl;
return;
}
vector<string> args = elem;
args.erase(args.begin());
newCommands.find(elem[0])->second->run(args);
}
ComplexCommandContainer::~ComplexCommandContainer(){
for (auto itr = newCommands.begin(); itr != newCommands.end(); itr++)
delete itr->second;
}
void ComplexCommandContainer::help() {
cout << "Make complex command using simple and old complex commands.\nSyntax is: new [NAME]" << endl
<< "(add [COMMAND])+" << endl
<< "end" << endl;
} | true |
110b782e53dd9f0a19956e36c82eaf3b76dac804 | C++ | SayaUrobuchi/uvachan | /UVa/10703.cpp | UTF-8 | 754 | 2.8125 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int a,b,c,d,e,f,g,h,i,j;
bool k[500][500];
while(scanf("%d%d%d",&a,&b,&h)==3)
{
if(a==0&&b==0&&h==0)
{
break;
}
for(c=0;c<a;c++)
{
for(d=0;d<b;d++)
{
k[c][d]=1;
}
}
for(h;h>0;h--)
{
scanf("%d%d",&c,&d);
scanf("%d%d",&e,&f);
if(c>e)
{
g=c;
c=e;
e=g;
}
if(d>f)
{
g=d;
d=f;
f=g;
}
for(c--;c<e;c++)
{
for(g=d-1;g<f;g++)
{
k[c][g]=0;
}
}
}
for(c=0,i=0;c<a;c++)
{
for(d=0;d<b;d++)
{
i+=k[c][d];
}
}
if(i==0)
{
printf("There is no empty spots.\n");
}
else if(i==1)
{
printf("There is one empty spot.\n");
}
else
{
printf("There are %d empty spots.\n",i);
}
}
return 0;
} | true |
593737c7955ef11444035144765bea44d023d78c | C++ | ojaster/first_project | /structure/massive86.cpp | UTF-8 | 398 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
const int n=8;
int k[n];
for(int i =0; i<n; i++){
cin>>k[i];
}
int j=0;
for(int i =0; i<n; i++){
if(k[i]==2){
j++;
}
}
cout<<"-----"<<endl;
cout<<"kolv="<<j<<endl;
cout<<"-----"<<endl;
if(j>0){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
}
} | true |
b66cce3c8574349556a549965d6a0e0b8c61b8c3 | C++ | johnnyflame/RANSACPlanefinder | /planeFinder.cpp | UTF-8 | 1,845 | 3.265625 | 3 | [] | no_license | #include "SimplePly.h"
#include <iostream>
int main (int argc, char *argv[]) {
// Check the commandline arguments.
if (argc != 6) {
std::cout << "Usage: planeFinder <input file> <output file> <number of planes> <point-plane threshold> <number of RANSAC trials>" << std::endl;
return -1;
}
int nPlanes = atoi(argv[3]);
double threshold = atof(argv[4]);
int nTrials = atoi(argv[5]);
std::cout << "Searching for " << nPlanes << " planes" << std::endl;
std::cout << "Using a point-plane threshold of " << threshold << " units" << std::endl;
std::cout << "Applying RANSAC with " << nTrials << " trials" << std::endl;
// Storage for the point cloud.
SimplePly ply;
// Read in the data from a PLY file
std::cout << "Reading PLY data from " << argv[1] << std::endl;
if (!ply.read(argv[1])) {
std::cout << "Could not read PLY data from file " << argv[1] << std::endl;
return -1;
}
std::cout << "Read " << ply.size() << " points" << std::endl;
// Recolour points - here we are just doing colour based on index
std::cout << "Recolouring points" << std::endl;
std::vector<Eigen::Vector3i> colours;
colours.push_back(Eigen::Vector3i(255,0,0));
colours.push_back(Eigen::Vector3i(0,255,0));
colours.push_back(Eigen::Vector3i(0,0,255));
// Can add more colours as needed
size_t planeSize = ply.size()/nPlanes;
for (size_t ix = 0; ix < ply.size(); ++ix) {
size_t planeIx = ix / planeSize;
size_t colourIx = planeIx % colours.size(); // May need to recycle colours
ply[ix].colour = colours[colourIx];
}
// Write the resulting (re-coloured) point cloud to a PLY file.
std::cout << "Writing PLY data to " << argv[2] << std::endl;
if (!ply.write(argv[2])) {
std::cout << "Could not write PLY data to file " << argv[2] << std::endl;
return -2;
}
return 0;
}
| true |
c62fadeff58a47576d0fa4ce48ab78de3df17bb5 | C++ | engyebrahim/CompetitiveProgramming | /Topcoder/SRM373-D2-1000.cpp | UTF-8 | 2,694 | 3.125 | 3 | [] | no_license | /*
first case
for every rectangle if any end poit inside it (check by cross product) sum its area and mark it as visited
second case
1- if rec is not visited and a point exist in any of its sides
2- if rec is not vis and any of its sides intersect with any segment
*/
#include<bits/stdc++.h>
using namespace std;
struct point
{
int x,y;
};
struct rec
{
point p1,p2,p3,p4;
};
struct seg
{
point p1,p2;
};
vector<rec> r;
vector<seg> s;
vector<bool >vis;
int ccw(point p,point q,point r)
{
int val= (q.x - p.x) * (r.y - q.y)-(q.y - p.y) * (r.x - q.x) ;
if (val>0) return 1;
else if(val<0) return -1;
else return 0;
}
bool on(point p, point r, point q)
{
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
return true;
return false;
}
bool inter(point p1, point q1, point p2, point q2)
{
int o1 = ccw(p1, q1, p2);
int o2 = ccw(p1, q1, q2);
int o3 = ccw(p2, q2, p1);
int o4 = ccw(p2, q2, q1);
if (o1 != o2 && o3 != o4)
return true;
return false;
}
int fun1()
{
int ans=0;
for(int i=0;i<s.size();i++)
{
for(int j=0;j<r.size();j++)
if(!vis[j]&&((ccw(r[j].p1,r[j].p2,s[i].p1)>0&&ccw(r[j].p2,r[j].p3,s[i].p1)>0&&
ccw(r[j].p3,r[j].p4,s[i].p1)>0&&ccw(r[j].p4,r[j].p1,s[i].p1)>0)||
(ccw(r[j].p1,r[j].p2,s[i].p2)>0&&ccw(r[j].p2,r[j].p3,s[i].p2)>0&&
ccw(r[j].p3,r[j].p4,s[i].p2)>0&&ccw(r[j].p4,r[j].p1,s[i].p2)>0)))
{
vis[j]=1;
ans+=(r[j].p2.x-r[j].p1.x)*(r[j].p3.y-r[j].p2.y);
}
}
return ans;
}
int fun2()
{
int ans=0;
for(int i=0;i<s.size();i++)
{
for(int j=0;j<r.size();j++)
if(!vis[j]&&((on(r[j].p1,r[j].p2,s[i].p1)>0||on(r[j].p2,r[j].p3,s[i].p1)>0||
on(r[j].p3,r[j].p4,s[i].p1)>0||on(r[j].p4,r[j].p1,s[i].p1)>0||
on(r[j].p1,r[j].p2,s[i].p2)>0||on(r[j].p2,r[j].p3,s[i].p2)>0||
on(r[j].p3,r[j].p4,s[i].p2)>0||on(r[j].p4,r[j].p1,s[i].p2)>0)||
(inter(r[j].p1,r[j].p2,s[i].p1,s[i].p2)>0||inter(r[j].p2,r[j].p3,s[i].p1,s[i].p2)>0||
inter(r[j].p3,r[j].p4,s[i].p1,s[i].p2)>0||inter(r[j].p4,r[j].p1,s[i].p1,s[i].p2)>0)))
{
vis[j]=1;
ans+=(r[j].p2.x-r[j].p1.x)*(r[j].p3.y-r[j].p2.y);
}
}
return ans;
}
class RectangleCrossings
{
public: vector <int> countAreas(vector <string> rectangles, vector <string> segments)
{
rec tmp;
stringstream ss;
for(int i=0;i<rectangles.size();i++)
{
ss.clear();
ss<<rectangles[i];
ss>>tmp.p1.x;
ss>>tmp.p1.y;
ss>>tmp.p3.x;
ss>>tmp.p3.y;
tmp.p2.x=tmp.p3.x;
tmp.p2.y=tmp.p1.y;
tmp.p4.x=tmp.p1.x;
tmp.p4.y=tmp.p3.y;
r.push_back(tmp);
}
seg cur;
for(int i=0;i<segments.size();i++)
{
ss.clear();
ss<<segments[i];
ss>>cur.p1.x;
ss>>cur.p1.y;
ss>>cur.p2.x;
ss>>cur.p2.y;
s.push_back(cur);
}
vis.resize(r.size());
vector<int> ans(2);
ans[0]=fun1();
ans[1]=fun2();
return ans;
}
};
| true |
7b373d7105938378672948241eb17e04c8f927af | C++ | djuanbei/graphmodel | /ftma/include/domain/dbmset.hpp | UTF-8 | 5,850 | 2.8125 | 3 | [] | no_license | /**
* @file DBMset.h
* @author Liyun Dai <dlyun2009@gmail.com>
* @date Sun Mar 31 21:58:00 2019
*
* @brief A dbm matrix set class.
*
*
*/
#ifndef DBM_SET_H
#define DBM_SET_H
#include <algorithm>
#include <map>
#include <vector>
#include "domain/dbm.h"
#include "util/dbmutil.hpp"
namespace graphmodel {
// using namespace std;
template <typename C>
class DBMset {
public:
class iterator;
class const_iterator;
DBMset(DBMManager& manager) { dbm_manager = manager; }
~DBMset() { deleteAll(); }
iterator begin() { return iterator(this); }
const_iterator begin() const { return const_iterator(this); }
iterator end() {
return iterator(this, map_data.size() + recovery_data.size());
/**/
}
const_iterator end() const {
return const_iterator(this, map_data.size() + recovery_data.size());
/**/
}
/**
* @param DM A dbm matrix
*
* @return true if real insert DBMFactory into set
* false otherwise. DM does not destory in function
*/
bool add(C* DM) {
uint32_t hashValue = dbm_manager.getHashValue(DM);
typename std::pair<typename std::map<uint32_t, int>::iterator, bool> ret;
ret = passed_data.insert(
std::pair<uint32_t, int>(hashValue, map_data.size()));
DF_T featrue = dbm_manager.getIncludeFeature(DM);
if (false == ret.second) {
// hashValue has in passedD
C* D1 = getD(hashValue);
if (!dbm_manager.equal(DM, D1)) {
bool have = false;
for (typename std::vector<C*>::iterator it = recovery_data.begin();
it != recovery_data.end(); it++) {
if (dbm_manager.equal(DM, *it)) {
have = true;
break;
}
}
if (have) {
return false;
}
if (include(DM, featrue)) {
return false;
} else {
recoveryDAdd(DM, featrue);
}
} else {
return false;
}
} else {
mapDAdd(DM, featrue);
}
return true;
}
bool contain(const C* const DM) const {
DF_T featrue = dbm_manager.getIncludeFeature(DM);
return include(DM, featrue);
}
size_t size() const { return passed_data.size() + recovery_data.size(); }
void clear(void) {
passed_data.clear();
map_data.clear();
map_data_feature.clear();
recovery_data.clear();
recovery_data_feature.clear();
}
void deleteAll(void) {
for (typename std::vector<C*>::const_iterator it = map_data.begin();
it != map_data.end(); it++) {
delete[] * it;
}
for (typename std::vector<C*>::iterator it = recovery_data.begin();
it != recovery_data.end(); it++) {
delete[] * it;
}
clear();
}
void And(DBMset<C>& other) {
for (typename std::vector<C*>::iterator it = other.map_data.begin();
it != other.map_data.end(); it++) {
add(dbm_manager, *it);
}
for (typename std::vector<C*>::iterator it = other.recovery_data.begin();
it != other.recovery_data.end(); it++) {
add(dbm_manager, *it);
}
other.clear();
}
class const_iterator {
protected:
const DBMset<C>* data;
size_t index;
public:
const_iterator(const DBMset<C>* odata) : data(odata) { index = 0; }
const_iterator(const DBMset<C>* odata, size_t oindex) : data(odata) {
index = oindex;
}
const_iterator(const const_iterator& other) : data(other.data) {
index = other.index;
}
const_iterator& operator++() {
index++;
return *this;
}
bool operator==(const const_iterator& other) const {
return index == other.index;
}
bool operator!=(const const_iterator& other) const {
return index != other.index;
}
const C* operator*() const {
size_t dSize = data->mapD.size();
if (index < dSize) {
return data->mapD[index];
}
if (index >= dSize + data->recoveryD.size()) {
return nullptr;
}
return data->recoveryD[index - dSize];
}
};
class iterator {
protected:
const DBMset<C>* data;
size_t index;
public:
iterator(DBMset<C>* odata) : data(odata) { index = 0; }
iterator(DBMset<C>* odata, size_t oindex) : data(odata) { index = oindex; }
iterator(const iterator& other) : data(other.data) { index = other.index; }
iterator& operator++() {
index++;
return *this;
}
bool operator==(const iterator& other) const {
return index == other.index;
}
bool operator!=(const iterator& other) const {
return index != other.index;
}
C* operator*() {
size_t dSize = data->mapD.size();
if (index < dSize) {
return data->mapD[index];
}
if (index >= dSize + data->recoveryD.size()) {
return nullptr;
}
return data->recoveryD[index - dSize];
}
};
private:
DBMManager dbm_manager;
std::map<uint32_t, int> passed_data;
std::vector<C*> map_data;
std::vector<DF_T> map_data_feature;
std::vector<C*> recovery_data;
std::vector<DF_T> recovery_data_feature;
C* getD(uint32_t hash_value) { return map_data[passed_data[hash_value]]; }
void mapDAdd(C* D, DF_T& value) {
map_data.push_back(D);
map_data_feature.push_back(value);
}
void recoveryDAdd(C* D, DF_T& value) {
recovery_data.push_back(D);
recovery_data_feature.push_back(value);
}
bool include(const C* const DM, DF_T& featrue) const {
for (size_t i = 0; i < map_data.size(); i++) {
if ((map_data_feature[i] >= featrue) &&
dbm_manager.include(map_data[i], DM)) {
return true;
}
}
for (size_t i = 0; i < recovery_data.size(); i++) {
if ((recovery_data_feature[i] >= featrue) &&
dbm_manager.include(recovery_data[i], DM)) {
return true;
}
}
return false;
}
};
} // namespace graphmodel
#endif
| true |
1076a1c62ef7c450096d91448655e6861c7b32a0 | C++ | arturomf94/of-experiments | /meshImage/ofApp.cpp | UTF-8 | 3,252 | 2.65625 | 3 | [] | no_license | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
image.load("example.jpg");
image.resize(300,200);
mesh.setMode(OF_PRIMITIVE_POINTS);
mesh.enableColors();
float intensityThreshold = 150.0;
int w = image.getWidth();
int h = image.getHeight();
for (int x=0; x<w; ++x) {
for (int y=0; y<h; ++y) {
ofColor c = image.getColor(x, y);
float intensity = c.getLightness();
if (intensity >= intensityThreshold) {
// We shrunk our image by a factor of 4, so we need to multiply our pixel
// locations by 4 in order to have our mesh cover the openFrameworks window
ofVec3f pos(x*4, y*4, 0.0);
mesh.addVertex(pos);
mesh.addColor(c);
}
}
}
// Don't forget to change to lines mode!
mesh.setMode(OF_PRIMITIVE_LINES);
// We are going to be using indices this time
mesh.enableIndices();
// ...
// Omitting the code for creating vertices for clarity
// but don't erase it from your file!
// Let's add some lines!
float connectionDistance = 30;
int numVerts = mesh.getNumVertices();
for (int a=0; a<numVerts; ++a) {
ofVec3f verta = mesh.getVertex(a);
for (int b=a+1; b<numVerts; ++b) {
ofVec3f vertb = mesh.getVertex(b);
float distance = verta.distance(vertb);
if (distance <= connectionDistance) {
// In OF_PRIMITIVE_LINES, every pair of vertices or indices will be
// connected to form a line
mesh.addIndex(a);
mesh.addIndex(b);
}
}
}
}
void ofApp::draw(){
ofColor centerColor = ofColor(85, 78, 68);
ofColor edgeColor(0, 0, 0);
ofBackgroundGradient(centerColor, edgeColor, OF_GRADIENT_CIRCULAR);
mesh.draw();
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
bab5cef010c61b20a60c67758d3a00c8c8dd595f | C++ | thulsadum/openbot | /include/IRC.h | UTF-8 | 1,626 | 2.703125 | 3 | [] | no_license | #ifndef IRC_H
#define IRC_H
#include "include/Socket.h"
#include <queue>
#include <string>
#include <ctime>
#include <sstream>
using std::string;
using std::queue;
using std::ostringstream;
#define CRLF "\r\n"
#define RBUF_SIZE 4096
class IRC
{
public:
/** Default constructor */
IRC();
/** Default destructor */
virtual ~IRC();
bool isConnected() const;
bool connect(string server, unsigned short port, string password);
bool connect(string server, unsigned short port);
void setNick(string nick);
string getNick() const;
void setUser(string user);
string getUser() const;
void setRealname(string realname);
string getRealname() const;
void setResetInterval(double value);
double getResetInterval() const;
void setMaxMessages(int value);
int getMaxMessages() const;
void sendCmd(string cmd);
void poll();
// some use full functions
void join(string channel);
void part(string channel);
void privmsg(string target, string message);
void flush();
protected:
private:
Socket *m_sock;
queue<string> *m_qsend;
queue<string> *m_qrecv;
double m_rstint;
time_t m_lastrst;
int m_sendcount;
int m_maxcount;
string m_nick;
string m_user;
string m_realname;
ostringstream m_recvbuf;
void parse(string msg);
void send(string msg);
int recv();
void sendImmediate(string msg);
};
#endif // IRC_H
| true |
0392ac245b413dafce6807b9fbbab13deafee4ea | C++ | jericho31/ProblemSoving | /solved/swea.1215 3일차 - 회문1/main.cpp | UTF-8 | 900 | 3.046875 | 3 | [] | no_license | // 22min
#include <iostream>
#include <string>
using std::cin; using std::cout; using std::string;
string table[8] = {};
bool isPalindrome(string s)
{
int a = 0, b = (int)s.size() - 1;
for (int i = 0; i < (int)s.size() / 2; ++i) {
if (s[a + i] != s[b - i]) return false;
}
return true;
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
for (int citer = 1; citer <= 10; ++citer)
{
int n;
cin >> n;
if (n == 1) {
cout << '#' << citer << "64\n";
continue;
}
int ans = 0;
for (int i = 0; i < 8; ++i) {
cin >> table[i];
}
for (int i = 0; i < 8; ++i) {
for (int j = 0; j <= 8 - n; ++j) {
string tmp = "", tmp2 = "";
for (int k = 0; k < n; ++k) {
tmp += table[i][j + k];
tmp2 += table[j + k][i];
}
if (isPalindrome(tmp)) ++ans;
if (isPalindrome(tmp2)) ++ans;
}
}
cout << '#' << citer << ' ' << ans << '\n';
}
}
| true |
30531282378d72e5eec9245bf62e0b79d80cac69 | C++ | panguangze/Ibalance | /include/Vertex.hpp | UTF-8 | 1,598 | 2.984375 | 3 | [] | no_license | #ifndef _VERTEX_H_
#define _VERTEX_H_
#include <vector>
#include "Edge.hpp"
#include "Segment.hpp"
#include "Weight.hpp"
using namespace std;
class Segment;
class Edge;
class Weight;
class Vertex {
protected:
int mId; // vertex id
char mDir; // +/-
bool mIsOrphan; // record whether originally orphan
bool mHasCheckedOrphan;
bool mIsVisited;
Edge * mShortestPrevEdge;
Segment * mSegment; // the host segment
Weight * mWeight; // weight object including copy number
vector<Edge *> * mEdgesAsSource; // edges for this vertex as source
vector<Edge *> * mEdgesAsTarget; // edges for this vertex as target
public:
// constructor and destructor
Vertex(int aId, char aDir, Weight * aWeight, double aCredibility);
~Vertex();
// getter and setter
char getDir();
string getInfo();
inline bool operator == (const Vertex &other) const {
if (mId == other.mId && mDir == other.mDir) return true;
return false;
};
bool hasEdgeAsSource();
bool hasEdgeAsTarget();
bool isOrphan(bool aIsOriginal = true);
void checkOrphan(); // using only time RIGHT AFTER READING GRAPH
Segment * getSegment();
void setSegment(Segment * aSeg);
vector<Edge *> * getEdgesAsSource();
vector<Edge *> * getEdgesAsTarget();
void insertEdgeAsSource(Edge * aEdge);
void insertEdgeAsTarget(Edge * aEdge);
};
#endif
| true |
bec5935f04f77930b8917f983c40264e4e31a8a0 | C++ | ruslanchistov/different-tasks_2 | /zadacha_1.cpp | UTF-8 | 821 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Array
{
int Content [6];
public:
const int Length;
//------------------------------------------
Array(int theMass [], int theNum) : Length(theNum)
{
for (int i = 0; i < Length; i++)
Content[i] = theMass[i];
}
//------------------------------------------
Array(const Array& theArray) : Length(theArray.Length)
{
for (int Iter = 0; Iter < Length; Iter++)
{
Content[Iter] = theArray.Content[Iter];
cout << theArray.Content[Iter] << "\t";
}
cout << endl << "Length " << Length << endl;
}
//------------------------------------------
~Array()
{
}
};
int main()
{
int mass[6] = { 1,2,3,4,5,6 };
Array Ar1(mass,6);
Array Ar2 = Array(Ar1);
return 0;
} | true |
7495ba2ea1e8c2d6e3c06bf2a2997308fe9b751a | C++ | xchuki00/PGP | /geCore/include/GPUEngine/geCore/CopyOp.h | UTF-8 | 638 | 2.640625 | 3 | [] | no_license | #ifndef GE_COPYOP
#define GE_COPYOP
#include <GPUEngine/geCore/gecore_export.h>
namespace ge
{
namespace core
{
class Object;
class GECORE_EXPORT CopyOp
{
public:
enum Options
{
SHALLOW_COPY = 0,
DEEP_COPY_OBJECTS = 1<<0,
DEEP_COPY = 0x7FFFFFFF
};
inline CopyOp(unsigned flags=SHALLOW_COPY):_flags(flags) {}
virtual ~CopyOp(){}
virtual Object* operator() (const Object* obj) const;
unsigned getFlags() const { return _flags; }
void setFlags(unsigned flags) { _flags = flags; }
protected:
unsigned _flags;
};
}
}
#endif //GE_COPYOP
| true |
002dcd9b68cf3a5cb047c6662bc1557b31bedcc3 | C++ | aldgoff/DP4 | /DP4/src/Skeletons/bridge.cpp | UTF-8 | 4,666 | 3.109375 | 3 | [] | no_license | /*
* bridge.cpp
*
* Created on: Feb 2, 2015
* Author: aldgoff
*/
#include <iostream>
#include <map>
using namespace std;
#define COUNT(x) (sizeof(x)/sizeof(*x))
namespace skeleton {
class BridgeImplementation { // If multiple elements need to vary independently...
public: virtual ~BridgeImplementation() { cout << "~BridgeImplementation "; }
public:
virtual void concreteA()=0;
virtual void concreteB()=0;
public:
static BridgeImplementation* getImplementation(map<string,string>& domain);
};
class ImplementationX : public BridgeImplementation {
public: virtual ~ImplementationX() { cout << "~ImplementationX "; }
void concreteA() { cout << "concrete A implementation X.\n"; }
void concreteB() { cout << "concrete B implementation X.\n"; }
};
class ImplementationY : public BridgeImplementation {
public: virtual ~ImplementationY() { cout << "~ImplementationY "; }
void concreteA() { cout << "concrete A implementation Y.\n"; }
void concreteB() { cout << "concrete B implementation Y.\n"; }
};
class ImplementationZ : public BridgeImplementation {
public: virtual ~ImplementationZ() { cout << "~ImplementationZ "; }
void concreteA() { cout << "concrete A implementation Z.\n"; }
void concreteB() { cout << "concrete B implementation Z.\n"; }
};
// Seam point - add another implementation.
BridgeImplementation* BridgeImplementation::getImplementation(map<string,string>& domain) {
if( domain["implementation"] == "one") return new ImplementationX;
else if(domain["implementation"] == "two") return new ImplementationY;
else if(domain["implementation"] == "three") return new ImplementationZ;
// Seam point - insert another implementation.
else { // Throw error, or select a default.
throw "OOPS!";
}
}
class BridgeAbstraction { // If multiple elements need to vary independently...
protected:
BridgeImplementation* imp;
public:
explicit BridgeAbstraction(BridgeImplementation* imp) : imp(imp) {}
virtual ~BridgeAbstraction() { delete imp; cout << "~BridgeAbstraction\n"; }
public:
virtual void run()=0;
public:
static BridgeAbstraction* getAbstraction(map<string,string>& domain);
};
class Abstraction1 : public BridgeAbstraction {
public:
Abstraction1(BridgeImplementation* imp) : BridgeAbstraction(imp) {}
~Abstraction1() { cout << "~Abstraction1 "; }
public:
void run() { cout << " Bridge abstraction 1 - "; imp->concreteA(); }
};
class Abstraction2 : public BridgeAbstraction {
public:
Abstraction2(BridgeImplementation* imp) : BridgeAbstraction(imp) {}
~Abstraction2() { cout << "~Abstraction2 "; }
public:
void run() { cout << " Bridge abstraction 2 - "; imp->concreteB(); }
};
class Abstraction3 : public BridgeAbstraction {
public:
Abstraction3(BridgeImplementation* imp) : BridgeAbstraction(imp) {}
~Abstraction3() { cout << "~Abstraction3 "; }
public:
void run() { cout << " Bridge abstraction 3 - "; imp->concreteA(); }
};
// Seam point - add another abstraction.
BridgeAbstraction* BridgeAbstraction::getAbstraction(map<string,string>& domain) {
BridgeImplementation* implementation = BridgeImplementation::getImplementation(domain);
if( domain["abstraction"] == "first") return new Abstraction1(implementation);
else if(domain["abstraction"] == "second") return new Abstraction2(implementation);
else if(domain["abstraction"] == "third") return new Abstraction3(implementation);
// Seam point - insert another abstraction.
else { // Throw error, or select a default.
throw "OOPS!";
}
}
void clientBridge() {
cout << "Bridge\n";
BridgeImplementation* imps[] = { new ImplementationX, new ImplementationY, new ImplementationZ };
for(size_t i=0; i<COUNT(imps); i++) {
BridgeAbstraction* abs[] = { new Abstraction1(imps[i]), new Abstraction2(imps[i]), new Abstraction3(imps[i]) };
for(size_t j=0; j<COUNT(abs); j++) {
abs[j]->run();
}
cout << endl;
}
{ // Use domain and static construct methods (getA/I) to lower coupling.
map<string,string> domain;
string imps[] = { "one", "two", "three" };
string abs[] = { "first", "second", "third" };
BridgeAbstraction* abstractions[COUNT(abs)*COUNT(imps)] = {0};
size_t k = 0;
for(size_t i=0; i<COUNT(abs); i++) {
for(size_t j=0; j<COUNT(imps); j++) {
domain["abstraction"] = abs[i];
domain["implementation"] = imps[j];
abstractions[k] = BridgeAbstraction::getAbstraction(domain);
abstractions[k]->run();
k++;
}
}
// Show Dtor instrumentation.
cout << COUNT(abstractions) << endl;
for(size_t k=0; k<COUNT(abstractions); k++)
delete abstractions[k];
}
}
}
| true |
f21c4fdb0ea080c70ae74248e29d771356c2d7c7 | C++ | Diego10HDZ/CUFICO-2018-2 | /TallerJuegoDeLaVida/JuegoDeLaVida_comented_2especie.cpp | UTF-8 | 8,115 | 3.671875 | 4 | [] | no_license | #include <iostream> //incluir libreria para operaciones de entrada y salida
#include <cstdlib> //Incluir libreria para control de memoria
#include <vector> //Inicializar un vector vacio
#include <unistd.h> //Incluir la libreria unistd.h
using namespace std; //Incluir las palabras del diccionario estandar de C++
class Mapa //declarar la clase mapa
{
public: //Declarar las funciones que se pueden usar fuera de la clase Mapa
int fil; //Declarar el atributo fila de tipo entero
int col; // declarar el atributo columna de tipo entero
int tipo1; //declarar el atributo tipo1 como entero
int tipo2; //declarar el atributo tipo2 como entero
vector<vector<int> > mapa; //declara una matriz de numeros enteros cuyo nombre es mapa
Mapa(int f, int c); //declara la funcion mapa que recibe dos enteros f y c
void dibujar(); //declara la funcion dibujar
int analizarVecinos(int posf, int posc); //declara la funcion analizarVecinos, recibe dos enteros posf y posc
void ciclo(); //declara la funcion ciclo
};
Mapa::Mapa(int f, int c) //Definicion de la funcion Mapa de la clase Mapa
{
fil = f; //Para la funcion se define fil como f
col = c; //Para la funcion se define col como c
mapa.resize(fil); //redefine el tamaño de la matriz mapa
for(int i=0; i<mapa.size(); i++) //Ciclo con el cual se llena cada elemento del vector con otro vector
{
mapa[i].resize(col); //Se define el tañamo de la entrada de cada elemento del vector con el numero de columnas
}
for(int f=0; f<fil; f++) //Se inicia un ciclo para barrer las filas
{
for(int c=0; c<col; c++) //Se inicia un ciclo para barrer las columnas
{
mapa[f][c] = rand()%3; //A cada elemento de la matriz se le asigna un numero aleatorio que puede ser cero, uno o dos, esto depende del modulo 3 de un numero aleatorio natural
}
}
}
void Mapa::dibujar() //Definicion de la funcion dibujar de la clase Mapa
{
for(int f=0; f<fil; f++) //Se inicia un ciclo para barrer las filas
{
for(int c=0; c<col; c++) //Se inicia un ciclo para barrer las columnas
{
if(mapa[f][c] == 1) //Si en la entrada de la matriz hay un uno, se imprime *
cout << "* ";
else if(mapa[f][c] == 2) //Si en la entrada de la matriz hay un dos, se imprime ~
cout << "~ ";
else //Si en la entrada de la matriz hay un cero, se imprime .
cout << ". ";
}
cout << "\n"; //Cuando se barre una fila se agrega un salto de linea
}
}
int Mapa::analizarVecinos(int posf, int posc)
// Definicion de la funcion analizarVecinos de la clase mapa, recibe la posicion de la fila y de la columna de la entrada de la matriz
{
tipo1 = 0; //Se inicializa la variable tipo1 con un cero
tipo2 = 0; //Se inicializa la variable tipo2 con un cero
if(posf-1 >= 0 and posc-1 >= 0) // si la fila es mayor o igual que la segunda y la columna es mayor o igual que la segunda
if(mapa[posf-1][posc-1] == 1) //si en la diagonal superior izquierda de la entrada hay un uno, en ese caso se adiciona a tipo1 si hay un uno
tipo1++;
else if(mapa[posf-1][posc-1] == 2) //si en la diagonal superior izquierda de la entrada hay un dos, en ese caso se adiciona a tipo2 si hay un uno
tipo2++;
if(posf-1 >= 0) //Si la fila es mayor o igual que la segunda
if(mapa[posf-1][posc] == 1) //Si arriba de la entrada hay un uno se incrementa el contador tipo1
tipo1++;
else if(mapa[posf-1][posc] == 2)//Si arriba de la entrada hay un dos se incrementa el contador tipo2
tipo2++;
if(posf-1 >= 0 and posc+1 <= col-1) // si la fila es mayor o igual que la segunda y la posicion de la columna mas dos es menor o igual que el numero de columnas
if(mapa[posf-1][posc+1] == 1) // Si en la esquina superior derecha haya un uno, en este caso se adiciona a tipo1
tipo1++;
else if(mapa[posf-1][posc+1] == 2) // Si en la esquina superior derecha haya un uno, en este caso se adiciona a tipo2
tipo2++;
if(posc-1 >= 0) //Si la columna es mayor o igual que la segunda
if(mapa[posf][posc-1] == 1) //Si a la izquierda de la entrada hay un uno se incrementa el contador tipo1
tipo1++;
else if(mapa[posf][posc-1] == 2) //Si a la izquierda de la entrada hay un dos se incrementa el contador tipo2
tipo2++;
if(posc+1 <= col-1) //Si la columna más dos es menor o igual que el numero de columnas
if(mapa[posf][posc+1] == 1) //Si a la derecha de la entrada hay un uno se incrementa el contador tipo1
tipo1++;
else if(mapa[posf][posc+1] == 2) //Si a la derecha de la entrada hay un dos se incrementa el contador tipo2
tipo2++;
if(posf+1 <= fil-1 and posc-1 >= 0) //Si la posicion de la fila más dos es menor o igual que el numero de filas y la columna es mayor o igual que la segunda
if(mapa[posf+1][posc-1] == 1) //Si en la esquina inferior izquierda hay un uno, se añade al contador tipo1
tipo1++;
else if(mapa[posf+1][posc-1] == 2) //Si en la esquina inferior izquierda hay un dos, se añade al contador tipo2
tipo2++;
if(posf+1 <= fil-1) //Si la posicion de la fila más dos es menor o igual que el numero de filas
if(mapa[posf+1][posc] == 1) //Si debajo de la entrada hay un uno, se añade al contador tipo1
tipo1++;
else if(mapa[posf+1][posc] == 2) //Si debajo de la entrada hay un dos, se añade al contador tipo2
tipo2++;
if(posf+1 <= fil-1 and posc+1 <= col-1) //Si la posicion de la fila más dos es menor o igual que el numero de filas y la columna mas dos es menor o igual que el numero de columnas
if(mapa[posf+1][posc+1] == 1) //si en la diagonal derecha inferior hay un uno se añade al contador tipo1
tipo1++;
else if(mapa[posf+1][posc+1] == 2) //si en la diagonal derecha inferior hay un dos se añade al contador tipo2
tipo2++;
return 0;
}
void Mapa::ciclo() // Con esta funcion de la clase mapa, se barren las filas y las columnas
{
vector<vector<int> > nueva_conf = mapa; // se inicializa una configuración de mapa
for (int f=0; f<fil; f++) //con este ciclo se barre sobre las filas
{
for(int c=0; c<col; c++) //con este ciclo se barre sobre las columnas
{
analizarVecinos(f, c); //se declara como entero n_vecinos, el cual proviene de la funcion analizarVecinos
if(mapa[f][c] == 0) //Condiciones bajo las cuales se transforma una celda cuya entrada es 0
{
if(tipo1 == 3 )
nueva_conf[f][c] = 1;
else if(tipo2 == 3)
nueva_conf[f][c] = 2;
else
nueva_conf[f][c] = 0;
}
if(mapa[f][c] == 1) //Condiciones bajo las cuales se transforma una celda cuya entrada es 1
{
if(tipo1 >= tipo2 && (tipo1 == 3 || tipo1 == 2))
nueva_conf[f][c] = 1;
else if(tipo2 > tipo1 && tipo2 == 3)
nueva_conf[f][c] = 2;
else
nueva_conf[f][c] = 0;
}
if(mapa[f][c] == 2) //Condiciones bajo las cuales se transforma una celda cuya entrada es 2
{
if(tipo1 >= tipo2 && tipo1 == 3 )
nueva_conf[f][c] = 1;
else if(tipo2 > tipo1 && (tipo2 == 3 || tipo2 == 2))
nueva_conf[f][c] = 2;
else
nueva_conf[f][c] = 0;
}
tipo1 = 0; //Se reinician a ceros los contadores tipo1 y tipo2 de la estructura
tipo2 = 0;
}
}
mapa = nueva_conf;// el mapa se redefine de acuerdo a la configuración anterior
}
int main() //Se define la función principal
{
srand(time(NULL)); //genera una semilla para numeros aleatorios con base en el tiempo interno del computador
Mapa mapa(50, 50); //inicia la función mapa de la clase Mapa con cincuenta filas y cincuenta columnas
while(1) //Para la ejecución del ciclo
{
mapa.dibujar(); //se dibuja la matriz
usleep(100000); //se le añade un delay
system("clear"); //limpia la pantalla para la nueva configuracion
mapa.ciclo(); //se corre la función ciclo de la clase Mapa
}
}
| true |
9dbfda74ac2cf1fb29b0eaa6e03d287b7221a50e | C++ | ecepep/smallcppsoft | /src/GUI/propwindow.h | UTF-8 | 1,420 | 2.671875 | 3 | [] | no_license | #ifndef PROPWINDOW_H
#define PROPWINDOW_H
#include <QWidget>
#include <QDate>
#include <memory>
#include <QEvent>
#include "dbconnection/dbprop.h"
namespace Ui {
class PropWindow;
}
/**
* @brief The PropLoadFail class
* @details
* Child of QEvent. A PropLoadFail of type (QEvent::Type) eventPLF,
* will be sent by @class PropWindow to warn PropWindow's warnOnFail QWidget that
* PropWindow has no more Prop to load and display.
*/
class PropLoadFail : public QEvent
{
public:
explicit PropLoadFail();
virtual ~PropLoadFail();
static QEvent::Type type();
static QEvent::Type eventPLF;
};
/**
* @brief The PropWindow class QWidget for Prop display
*
* @details
* @see Prop
* @see MainWindow
*/
class PropWindow : public QWidget
{
Q_OBJECT
public:
explicit PropWindow(QWidget *parent = nullptr, QWidget *warnOnFail = nullptr);
~PropWindow();
void nextProp();
protected:
void loadFailed();
enum struct kEval { perfect, good, hard, again };
Ui::PropWindow *ui;
std::unique_ptr<Prop> property; /**< Property being displayed.
@note because of @see Prop::load, @see Prop::save property is never replaced just updated @see @function nextProp*/
QWidget* warnOnFail; /**< QWidget to receive PropLoadFail event in case of @see @function loadFailed */
protected slots:
void showProp();
void evaluateProp(kEval const& eval);
};
#endif // PROPWINDOW_H
| true |
a9983645d38b074d88a75fd43c3eee46a3f30751 | C++ | honeysuckcle/Garden.github.io | /algorithm/algorithm/algorithm/week2/p107-4/matrix.h | GB18030 | 906 | 3.1875 | 3 | [] | no_license | #pragma once
class SparseMatrix {
public:
SparseMatrix();
SparseMatrix Transpose();
private:
int Rows, Cols,Terms;
MatrixTerm smArray[5];
};
class MatrixTerm {
friend SparseMatrix;
private:
int row, col, value;
};
SparseMatrix SparseMatrix::Transpose() {
int *RowStart = new int[Cols];
SparseMatrix b;
b.Rows = Cols;
b.Cols = Rows;
b.Terms = Terms;
if (Terms > 0)
{
RowStart[0] = 0;
for(int i = 1;i < Cols;i++)
{
int size = 0;
for (int j = 0; j < Terms; j++)
{
if ((i-1) == smArray[j].col)
size++;
}
RowStart[i] = RowStart[i - 1] + size;
}
for (int i = 0; i < Terms; i++)
{
int j = RowStart[smArray[i].col];
b.smArray[j].row = smArray[i].col;
b.smArray[j].col = smArray[i].row;
b.smArray[j].value = smArray[i].value;
RowStart[smArray[i].col]++;
//ȷĸλֵ
}
}
} | true |
a720fa76025b749522c00a2ab4f118bf6eb87238 | C++ | MayaPosch/NymphCast | /src/server/gui/core/components/TextEditComponent.cpp | UTF-8 | 7,691 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "components/TextEditComponent.h"
#include "resources/Font.h"
#include "utils/StringUtil.h"
#define TEXT_PADDING_HORIZ 10
#define TEXT_PADDING_VERT 2
#define CURSOR_REPEAT_START_DELAY 500
#define CURSOR_REPEAT_SPEED 28 // lower is faster
TextEditComponent::TextEditComponent(Window* window) : GuiComponent(window),
mBox(window, ":/textinput_ninepatch.png"), mFocused(false),
mScrollOffset(0.0f, 0.0f), mCursor(0), mEditing(false), mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT)),
mCursorRepeatDir(0)
{
addChild(&mBox);
onFocusLost();
setSize(4096, mFont->getHeight() + TEXT_PADDING_VERT);
}
void TextEditComponent::onFocusGained()
{
mFocused = true;
mBox.setImagePath(":/textinput_ninepatch_active.png");
}
void TextEditComponent::onFocusLost()
{
mFocused = false;
mBox.setImagePath(":/textinput_ninepatch.png");
}
void TextEditComponent::onSizeChanged()
{
mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-34, -32 - TEXT_PADDING_VERT));
onTextChanged(); // wrap point probably changed
}
void TextEditComponent::setValue(const std::string& val)
{
mText = val;
onTextChanged();
}
std::string TextEditComponent::getValue() const
{
return mText;
}
void TextEditComponent::textInput(const char* text)
{
if(mEditing)
{
mCursorRepeatDir = 0;
if(text[0] == '\b')
{
if(mCursor > 0)
{
size_t newCursor = Utils::String::prevCursor(mText, mCursor);
mText.erase(mText.begin() + newCursor, mText.begin() + mCursor);
mCursor = (unsigned int)newCursor;
}
}else{
mText.insert(mCursor, text);
mCursor += (unsigned int)strlen(text);
}
}
onTextChanged();
onCursorChanged();
}
void TextEditComponent::startEditing()
{
SDL_StartTextInput();
mEditing = true;
updateHelpPrompts();
}
void TextEditComponent::stopEditing()
{
SDL_StopTextInput();
mEditing = false;
updateHelpPrompts();
}
bool TextEditComponent::input(InputConfig* config, Input input)
{
bool const cursor_left = (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("left", input)) ||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_LEFT);
bool const cursor_right = (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("right", input)) ||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RIGHT);
if(input.value == 0)
{
if(cursor_left || cursor_right)
mCursorRepeatDir = 0;
return false;
}
if((config->isMappedTo("a", input) || (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)) && mFocused && !mEditing)
{
startEditing();
return true;
}
if(mEditing)
{
if(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)
{
if(isMultiline())
{
textInput("\n");
}else{
stopEditing();
}
return true;
}
if((config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_ESCAPE) || (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("b", input)))
{
stopEditing();
return true;
}
if(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("up", input))
{
// TODO
}else if(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("down", input))
{
// TODO
}else if(cursor_left || cursor_right)
{
mCursorRepeatDir = cursor_left ? -1 : 1;
mCursorRepeatTimer = -(CURSOR_REPEAT_START_DELAY - CURSOR_REPEAT_SPEED);
moveCursor(mCursorRepeatDir);
} else if(config->getDeviceId() == DEVICE_KEYBOARD)
{
switch(input.id)
{
case SDLK_HOME:
setCursor(0);
break;
case SDLK_END:
setCursor(std::string::npos);
break;
case SDLK_DELETE:
if(mCursor < mText.length())
{
// Fake as Backspace one char to the right
moveCursor(1);
textInput("\b");
}
break;
}
}
//consume all input when editing text
return true;
}
return false;
}
void TextEditComponent::update(int deltaTime)
{
updateCursorRepeat(deltaTime);
GuiComponent::update(deltaTime);
}
void TextEditComponent::updateCursorRepeat(int deltaTime)
{
if(mCursorRepeatDir == 0)
return;
mCursorRepeatTimer += deltaTime;
while(mCursorRepeatTimer >= CURSOR_REPEAT_SPEED)
{
moveCursor(mCursorRepeatDir);
mCursorRepeatTimer -= CURSOR_REPEAT_SPEED;
}
}
void TextEditComponent::moveCursor(int amt)
{
mCursor = (unsigned int)Utils::String::moveCursor(mText, mCursor, amt);
onCursorChanged();
}
void TextEditComponent::setCursor(size_t pos)
{
if(pos == std::string::npos)
mCursor = (unsigned int)mText.length();
else
mCursor = (int)pos;
moveCursor(0);
}
void TextEditComponent::onTextChanged()
{
std::string wrappedText = (isMultiline() ? mFont->wrapText(mText, getTextAreaSize().x()) : mText);
mTextCache = std::unique_ptr<TextCache>(mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity()));
if(mCursor > (int)mText.length())
mCursor = (unsigned int)mText.length();
}
void TextEditComponent::onCursorChanged()
{
if(isMultiline())
{
Vector2f textSize = mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);
if(mScrollOffset.y() + getTextAreaSize().y() < textSize.y() + mFont->getHeight()) //need to scroll down?
{
mScrollOffset[1] = textSize.y() - getTextAreaSize().y() + mFont->getHeight();
}else if(mScrollOffset.y() > textSize.y()) //need to scroll up?
{
mScrollOffset[1] = textSize.y();
}
}else{
Vector2f cursorPos = mFont->sizeText(mText.substr(0, mCursor));
if(mScrollOffset.x() + getTextAreaSize().x() < cursorPos.x())
{
mScrollOffset[0] = cursorPos.x() - getTextAreaSize().x();
}else if(mScrollOffset.x() > cursorPos.x())
{
mScrollOffset[0] = cursorPos.x();
}
}
}
void TextEditComponent::render(const Transform4x4f& parentTrans)
{
Transform4x4f trans = getTransform() * parentTrans;
renderChildren(trans);
// text + cursor rendering
// offset into our "text area" (padding)
trans.translation() += Vector3f(getTextAreaPos().x(), getTextAreaPos().y(), 0);
Vector2i clipPos((int)trans.translation().x(), (int)trans.translation().y());
Vector3f dimScaled = trans * Vector3f(getTextAreaSize().x(), getTextAreaSize().y(), 0); // use "text area" size for clipping
Vector2i clipDim((int)(dimScaled.x() - trans.translation().x()), (int)(dimScaled.y() - trans.translation().y()));
Renderer::pushClipRect(clipPos, clipDim);
trans.translate(Vector3f(-mScrollOffset.x(), -mScrollOffset.y(), 0));
Renderer::setMatrix(trans);
if(mTextCache)
{
mFont->renderTextCache(mTextCache.get());
}
// pop the clip early to allow the cursor to be drawn outside of the "text area"
Renderer::popClipRect();
// draw cursor
if(mEditing)
{
Vector2f cursorPos;
if(isMultiline())
{
cursorPos = mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);
}else{
cursorPos = mFont->sizeText(mText.substr(0, mCursor));
cursorPos[1] = 0;
}
float cursorHeight = mFont->getHeight() * 0.8f;
Renderer::drawRect(cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2, 2.0f, cursorHeight, 0x000000FF, 0x000000FF);
}
}
bool TextEditComponent::isMultiline()
{
return (getSize().y() > mFont->getHeight() * 1.25f);
}
Vector2f TextEditComponent::getTextAreaPos() const
{
return Vector2f(TEXT_PADDING_HORIZ / 2.0f, TEXT_PADDING_VERT / 2.0f);
}
Vector2f TextEditComponent::getTextAreaSize() const
{
return Vector2f(mSize.x() - TEXT_PADDING_HORIZ, mSize.y() - TEXT_PADDING_VERT);
}
std::vector<HelpPrompt> TextEditComponent::getHelpPrompts()
{
std::vector<HelpPrompt> prompts;
if(mEditing)
{
prompts.push_back(HelpPrompt("up/down/left/right", "move cursor"));
prompts.push_back(HelpPrompt("b", "stop editing"));
}else{
prompts.push_back(HelpPrompt("a", "edit"));
}
return prompts;
}
| true |
cecd79b6a800b03c92d1c8415676b5506ca760a8 | C++ | Uniyalatul/tic-tac-toe | /tictac.cpp | UTF-8 | 5,238 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
char ttt[9]; // for the array
char x[20]; //first player name
char y[20]; // second player name
char fst[20]; // name(who'll play first)
int count=0 ; // counting index filled in array
int pos; // position to enter the move
char tem ; //temporary variable
int mx = 1; // temporary variable
int my = 1; // temporary variable
cout<<"\nEnter name of first player(who use SYMBOL X) : ";
cin>>x;
// while(( getchar() ) != '\n') ;
cout<<"\nEnter name of second player(who use SYMBOL O) : ";
cin>>y;
// while(( getchar() ) != '\n') ;
/* Initialising each position of the array with ' ' */
for(int i=0 ; i<9 ; i++)
ttt[i] =' ';
/* Name of one of the 2 registered players who will start the game . */
cout<<"Enter who will play first : ";
cin>>fst;
//while(( getchar() ) != '\n') ;
/* Tic Tac Toe board */
while(count<9)
{
cout<<"\n\n";
cout<<"\t\t\t "<<ttt[0]<<" | "<<ttt[1]<<" | "<<ttt[2]<<" \n";
cout<<"\t\t\t----+----+----\n";
cout<<"\t\t\t "<<ttt[3]<<" | "<<ttt[4]<<" | "<<ttt[5]<<" \n";
cout<<"\t\t\t----+----+---\n";
cout<<"\t\t\t "<<ttt[6]<<" | "<<ttt[7]<<" | "<<ttt[8]<<" \n";
if(count==0)
{
mx = strcmp(x,fst);
my = strcmp(y,fst);
}
if(my!=0 )
{
my=-10;
if(mx%2 == 0 )
{ cout<<"\n"<<x<<" !!!!!Enter ur move (1-9) ";
mx++;
}
else
{ cout<<"\n"<<y<<" !!!!!Enter ur move (1-9) ";
mx++ ;
}
}
else if(mx!=0)
{ mx=-10;
if(my%2 == 0 )
{ cout<<"\n"<<y<<" !!!!!Enter ur move (1-9) ";
my++; }
else
{ cout<<"\n"<<x<<" !!!!!Enter ur move (1-9) ";
my++ ; }
}
/* If the player who wants to play first does not match any of the registered players */
else if(mx == my)
{
cout<<"No such person is playing !!!!";
exit(0);
}
cin>>pos;
pos = pos-1 ;
system("clear");
if(count==0)
{ //1
if(!(strcmp(x,fst)))
{
ttt[pos]='X' ;
tem ='X';
}
else if(!(strcmp(y,fst)))
{ ttt[pos]='O' ;
tem = 'O' ;
}
} //-1
else
{ //a
if(tem=='X' && ttt[pos]==' ')
{
ttt[pos] = 'O';
tem = 'O';
}
else if(tem=='O' && ttt[pos]==' ')
{
ttt[pos] = 'X' ;
tem = 'X' ;
}
/* If the position in which a player wants to mark his symbol was already filled !!!!!!*/
else{
cout<<"\nWRONG MOVE ( position already filled ) !!!! \n PLAY AGAIN ------>>>>>\n";
if(mx>my)
mx--;
else
my--;
count--;
}
}
//-a
int flag=10 ;
for(int i=0 ; i<7 ; i++)
{
if(i==4 || i==5);
else if( ttt[0]!=' ' && ((ttt[0]==ttt[1] && ttt[1] == ttt[2]) || (ttt[0]==ttt[3] && ttt[3] == ttt[6]) || (ttt[0]==ttt[4] && ttt[4] == ttt[8]) ))
{
flag = 0 ;
break;
}
else if(ttt[1]!=' ' && (ttt[1]==ttt[4] && ttt[4] == ttt[7]) )
{
flag =1 ;
break;
}
else if(ttt[2]!=' ' && ( (ttt[2]==ttt[5] && ttt[5] == ttt[8]) || (ttt[2]==ttt[4] && ttt[4] == ttt[6]) ) )
{
flag = 2;
break;
}
else if(ttt[i]!=' ' && (i==3 || i==6) )
{
if( ttt[i] == ttt[i+1] && ttt[i+1] == ttt[i+2] )
{
flag = i ;
break;
}
}
}
if(flag<10)
{
cout<<"\t\t\t "<<ttt[0]<<" | "<<ttt[1]<<" | "<<ttt[2]<<" \n";
cout<<"\t\t\t----+----+----\n";
cout<<"\t\t\t "<<ttt[3]<<" | "<<ttt[4]<<" | "<<ttt[5]<<" \n";
cout<<"\t\t\t----+----+---\n";
cout<<"\t\t\t "<<ttt[6]<<" | "<<ttt[7]<<" | "<<ttt[8]<<" \n";
/* Displaying the WINNER !!!!! */
if(ttt[flag] == 'X')
cout<<"\n"<<x<<" is winner !!!!\n\n";
else if(ttt[flag] == 'O')
cout<<"\n"<<y<<" is winner !!!!\n\n";
exit(0);
}
/* If both player failed to make the wining combination , the game results to a tie !!!!! */
if(count==8)
cout<<"\nDRAW :) , better luck next time !!!!!!!!!!";
count++ ;
}//-while
return 0 ;
} | true |
6f98b4b68154f5bf41928a4d16c1e2280784f8a7 | C++ | noliaoliao/leetcode | /219/219.cpp | UTF-8 | 463 | 2.953125 | 3 | [] | no_license | class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> hashmap;
unordered_map<int,int>::iterator it;
int count = 0;
for(int i = 0; i < nums.size(); i++){
it = hashmap.find(nums[i]);
if(it != hashmap.end()){
if(i - it->second <= k) count++;
}
hashmap[nums[i]] = i;
}
return count == 1;
}
}; | true |
5849a43a63de278ddd3e92bb3e51c949d394f7ec | C++ | KuibinZhao/MonocularSfM | /include/Reconstruction/Initializer.h | UTF-8 | 6,660 | 2.75 | 3 | [] | no_license | #ifndef __INITIALIZER_H__
#define __INITIALIZER_H__
#include <cstddef>
#include <vector>
#include <opencv2/opencv.hpp>
namespace MonocularSfM
{
class Initializer
{
public:
struct Parameters
{
size_t rel_pose_min_num_inlier = 100; // 2D-2D点对应的内点数量的阈值
double rel_pose_ransac_confidence = 0.9999; // 求矩阵(H,E)时ransac的置信度
double rel_pose_essential_error = 4.0; // 求解决矩阵E的误差阈值
double rel_pose_homography_error = 12.0; // 求解决矩阵H的误差阈值
double init_tri_max_error = 2.0; // 三角测量时,重投影误差阈值
double init_tri_min_angle = 4.0; // 三角测量时, 角度阈值
};
struct Statistics
{
bool is_succeed = false; // 初始化是否成功
std::string method = "None"; // 初始化使用了何种方法
std::string fail_reason = "None";
size_t num_inliers_H = 0; // 估计单应矩阵时,符合单应矩阵的内点的数量
size_t num_inliers_F = 0; // 估计基础矩阵时,符合基础矩阵的内点的数量
double H_F_ratio = 0; // 单应矩阵的内点的数量 除以 基础矩阵的内点的数量
size_t num_inliers = 0; // 成功三角测量的3D点数(重投影误差小于阈值)
double median_tri_angle = 0; // 成功三角测量的3D点角度的中位数
double ave_tri_angle = 0; // 成功三角测量的3D点角度的平均值
double ave_residual = 0; // 平均重投影误差
cv::Mat R1; // 旋转矩阵1(单位矩阵)
cv::Mat t1; // 平移向量1(零向量)
cv::Mat R2; // 旋转矩阵2
cv::Mat t2; // 平移向量2
std::vector<cv::Vec3d> points3D; // 所有2D点所测量出来的3D点,包含了inlier和outlier
std::vector<double> tri_angles; // 每个3D点的角度
std::vector<double> residuals; // 每个3D点的重投影误差
std::vector<bool> inlier_mask; // 标记哪个3D点是内点
};
public:
Initializer(const Parameters& params, const cv::Mat& K);
/**
* 对于传进来两张图像已经对齐好的特征点,并尝试进行初始化
* 返回初始化的统计信息
*/
Statistics Initialize(const std::vector<cv::Vec2d>& points2D1,
const std::vector<cv::Vec2d>& points2D2);
void PrintStatistics(const Statistics& statistics);
private:
/**
* 使用RANSAC寻找满足points2D1和points2D2这两组点集对应关系的单应矩阵H
* @param points2D1 : 点集1
* @param points2D2 : 点集2
* @param H : [output] 单应矩阵
* @param inlier_mask : [output] 标志哪个是内点
* @param num_inliers : [output] 有多少个内点
*/
void FindHomography(const std::vector<cv::Vec2d>& points2D1,
const std::vector<cv::Vec2d>& points2D2,
cv::Mat& H,
std::vector<bool>& inlier_mask,
size_t& num_inliers);
/**
* 使用RANSAC寻找满足points2D1和points2D2这两组点集对应关系的基础矩阵F
* @param points2D1 : 点集1
* @param points2D2 : 点集2
* @param H : [output] 基础矩阵
* @param inlier_mask : [output] 标志哪个是内点
* @param num_inliers : [output] 有多少个内点
*/
void FindFundanmental(const std::vector<cv::Vec2d>& points2D1,
const std::vector<cv::Vec2d>& points2D2,
cv::Mat& F,
std::vector<bool>& inlier_mask,
size_t& num_inliers);
/**
* 分解单应矩阵H,从而得到初始位姿, 并进行三角测量,存到statistics_中
* @param H : 单应矩阵
* @param points2D1 : 点集1
* @param points2D2 : 点集2
* @param inlier_mask_H : 调用FindHomography时,得到的inlier_mask
* @return : true, 初始化成功; false,失败
*/
bool RecoverPoseFromHomography(const cv::Mat& H,
const std::vector<cv::Vec2d>& points2D1,
const std::vector<cv::Vec2d>& points2D2,
const std::vector<bool>& inlier_mask_H);
/**
* 分解基础矩阵F(实际上是分解本质矩阵E),从而得到初始位姿, 并进行三角测量,存到statistics_中
* @param F : 单应矩阵
* @param points2D1 : 点集1
* @param points2D2 : 点集2
* @param inlier_mask_F : 调用FindFundanmental时,得到的inlier_mask
* @return : true, 初始化成功; false,失败
*/
bool RecoverPoseFromFundanmental(const cv::Mat& F,
const std::vector<cv::Vec2d>& points2D1,
const std::vector<cv::Vec2d>& points2D2,
const std::vector<bool>& inlier_mask_F);
cv::Vec3d Triangulate(const cv::Mat& P1,
const cv::Mat& P2,
const cv::Vec2d& point2D1,
const cv::Vec2d& point2D2);
/**
* 根据statistics_, 得到初始化失败的信息
* [note] : 只有当statistics_.is_succeed == false
* 并且statistics_.num_inliers
* statistics_.median_tri_angle
* statistics_.ave_tri_angle
* statistics_.ave_residual
* 不为空时,才能调用这个函数
*/
std::string GetFailReason();
// bool CheckCheirality(std::vector<cv::Vec3d>& points3D,
// const std::vector<cv::Vec2d>& points2D1,
// const std::vector<cv::Vec2d>& points2D2,
// const cv::Mat& R1,
// const cv::Mat& t1,
// const cv::Mat& R2,
// const cv::Mat& t2);
private:
Parameters params_;
Statistics statistics_;
cv::Mat K_;
};
} //namespace MonocularSfM
#endif //__INITIALIZER_H__
| true |
f6b8b53cb592a27d2b5c0a9869aa830a4fbb7500 | C++ | sora-k/coding-problems | /551-student-attendance-record-i-[easy]/solution.cpp | UTF-8 | 717 | 3.125 | 3 | [] | no_license | // 4/22/17 6:17PM - 6:40PM
class Solution {
public:
bool checkRecord(string s) {
bool condition_1 = false; //more than one 'A' (absent)
bool condition_2 = false; //more than two continuous 'L' (late).
int a_count = 0;
int l_count = 0;
string::iterator it;
for(it = s.begin(); it != s.end(); ++it){
if(*it == 'A')
a_count++;
if(*it == 'L')
l_count++;
if((*it != 'L') && (l_count < 3))
l_count = 0;
}
condition_1 = a_count > 1;
condition_2 = l_count > 2;
return (condition_1 == false) && (condition_2 == false);
}
};
/*
"PPALLP"
"PPALLL"
"LALL"
*/ | true |
feb02414605fee4eb8f2b3b3f646e0aa37ec2739 | C++ | igordotsenko/Army-CPP | /Abilities/Ability.h | UTF-8 | 471 | 2.75 | 3 | [] | no_license | #ifndef ABILITY_H
#define ABILITY_H
#include "../Units/Unit.h"
#include "../States/State.h"
class Unit;
class Spell;
class Ability {
protected:
Unit* actionUnit;
public:
Ability(Unit* actionUnit);
virtual ~Ability() = 0;
virtual void attack(Unit* actionUnit);
virtual void counterAttack(Unit* actionUnit);
virtual void takeMagicDamage(int dmg);
virtual void castSpell(Unit* target, Spell* spell);
virtual void changeState();
};
#endif // ABILITY_H
| true |
751ddb222e2b78400d0ed0b55ece1da0ef5eb874 | C++ | PatrikOkanovic/ETH-AlgoLab-2020 | /week10/Worldcup/world_cup.cpp | UTF-8 | 2,692 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <CGAL/QP_models.h>
#include <CGAL/QP_functions.h>
#include <CGAL/Gmpz.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_2.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Delaunay_triangulation_2<K> Triangulation;
typedef CGAL::Gmpq IT;
typedef CGAL::Gmpq ET;
typedef CGAL::Quadratic_program<IT> Program;
typedef CGAL::Quadratic_program_solution<ET> Solution;
typedef CGAL::Quotient<ET> SolT;
long floor_to_double(const SolT &x) {
double a = std::floor(CGAL::to_double(x));
while (a > x) a -= 1;
while (a+1 <= x) a += 1;
return a;
}
void test_case() {
int n, m, c;
std::cin >> n >> m >> c;
std::vector<K::Point_2> s_w(n+m);
std::vector<IT> warehouses(n);
Program lp(CGAL::SMALLER, true, 0, false, 0);
for(int i = 0; i < n; ++i) {
IT s;
std::cin >> s_w[i] >> s >> warehouses[i];
lp.set_b(i, s);
}
for(int i = 0; i < m; ++i) {
IT d, u;
std::cin >> s_w[i+n] >> d >> u;
u *= 100;
lp.set_b(n + i, d);
lp.set_b(n + m + i, -d);
lp.set_b(n + 2*m + i, u);
}
int counter = 0;
std::vector<std::vector<std::pair<int, double>>> revenues(n, std::vector<std::pair<int, double>>(m));
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
counter++;
double revenue; std::cin >> revenue;
revenues[i][j] = std::make_pair(counter, -revenue);
lp.set_a(counter, i, 1);
lp.set_a(counter, n + j, 1);
lp.set_a(counter, n + m + j, -1);
lp.set_a(counter, n + 2*m + j, warehouses[i]);
}
}
Triangulation tri;
tri.insert(s_w.begin(), s_w.end());
for(int i = 0; i < c; ++i) {
K::Point_2 contour;
long r;
std::cin >> contour >> r;
long r2 = r*r;
if(CGAL::squared_distance(tri.nearest_vertex(contour)->point(), contour) <= r2) {
for(int i = 0; i < n; ++i) {
bool sign1 = CGAL::squared_distance(contour, s_w[i]) <= r2;
for(int j = 0; j < m; ++j) {
bool sign2 = CGAL::squared_distance(contour, s_w[n+j]) <= r2;
if(sign1 != sign2) {
revenues[i][j].second += 0.01;
}
}
}
}
}
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
lp.set_c(revenues[i][j].first, revenues[i][j].second);
}
}
Solution s = CGAL::solve_linear_program(lp, ET());
if(s.is_infeasible()) std::cout << "RIOT!\n";
else std::cout << floor_to_double(-s.objective_value()) << "\n";
}
int main() {
std::ios_base::sync_with_stdio(false);
int t; std::cin >> t;
for(int i = 0; i < t; ++i) {
test_case();
}
return 0;
}
| true |
48a05d30c516fe117b4a06702a3bca972328473b | C++ | devilzCough/Algorithm | /Algorithm_xcode/Algorithm_c++/Algorithm_c++/BFS/acm5427.cpp | UTF-8 | 2,918 | 3.25 | 3 | [] | no_license | //
// acm5427.cpp
// Algorithm_c++
//
// Created by 이승진 on 2021/06/01.
//
#include <iostream>
#include <queue>
using namespace std;
int N, w, h;
char map[1005][1005];
bool canEscape;
// up, down, left, right
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
int bfs();
void expandFire();
void move();
queue<pair<int, int>> fireQueue;
queue<pair<int, int>> moveQueue;
//void printMap() {
// for (int i = 0; i < h; i++) {
// for (int j = 0; j < w; j++) {
// printf("%c ", map[i][j]);
// }
// printf("\n");
// }
// printf("\n");
//}
int main()
{
scanf("%d", &N);
while (N--) {
canEscape = false;
fireQueue = {};
moveQueue = {};
scanf("%d %d", &w, &h);
for (int i = 0; i < h; i++) {
scanf("%s", map[i]);
for (int j = 0; j < w; j++) {
if (map[i][j] == '*') {
fireQueue.push(make_pair(j, i));
} else if (map[i][j] == '@') {
moveQueue.push(make_pair(j, i));
}
}
}
int movedCount = bfs();
if (canEscape) {
printf("%d\n", movedCount);
} else {
printf("IMPOSSIBLE\n");
}
}
return 0;
}
int bfs() {
int count = 0;
while (!moveQueue.empty()) {
// printMap();
count++;
// 순서 중요!!
expandFire();
move();
}
return count;
}
void expandFire() {
int size = fireQueue.size();
for (int i = 0; i < size; i++) {
int fire_x = fireQueue.front().first;
int fire_y = fireQueue.front().second;
fireQueue.pop();
for (int j = 0; j < 4; j++) {
int new_x = fire_x + dx[j];
int new_y = fire_y + dy[j];
if (new_x < 0 || new_x >= w || new_y < 0 || new_y >= h) continue;
if (map[new_y][new_x] == '.') {
map[new_y][new_x] = '*';
fireQueue.push(make_pair(new_x, new_y));
}
}
}
}
void move() {
int size = moveQueue.size();
for (int i = 0; i < size; i++) {
if (canEscape) break;
int x_pos = moveQueue.front().first;
int y_pos = moveQueue.front().second;
moveQueue.pop();
for (int j = 0; j < 4; j++) {
int cur_x = x_pos + dx[j];
int cur_y = y_pos + dy[j];
if (cur_x < 0 || cur_x >= w || cur_y < 0 || cur_y >= h) {
canEscape = true;
moveQueue = {};
break;
}
if (map[cur_y][cur_x] == '.') {
map[cur_y][cur_x] = '@';
moveQueue.push(make_pair(cur_x, cur_y));
}
}
}
}
| true |
cf36358de6a46939bd55286eb8e82996feb0b23f | C++ | darlinghq/xcbuild | /Libraries/plist/Tests/test_String.cpp | UTF-8 | 1,385 | 2.6875 | 3 | [
"LicenseRef-scancode-philippe-de-muyter",
"BSD-3-Clause",
"NCSA",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <gtest/gtest.h>
#include <plist/Objects.h>
using plist::String;
using plist::Boolean;
using plist::Real;
using plist::Integer;
using plist::Array;
TEST(String, New)
{
auto s1 = String::New("test");
EXPECT_EQ(s1->value(), "test");
auto s2 = String::New("");
EXPECT_EQ(s2->value(), "");
}
TEST(String, Coerce)
{
auto b1 = Boolean::New(false);
auto s1 = String::Coerce(b1.get());
EXPECT_EQ(s1->value(), "NO");
auto b2 = Boolean::New(true);
auto s2 = String::Coerce(b2.get());
EXPECT_EQ(s2->value(), "YES");
auto r3 = Real::New(1.0);
auto s3 = String::Coerce(r3.get());
EXPECT_EQ(s3->value(), "1");
auto r4 = Real::New(3.14);
auto s4 = String::Coerce(r4.get());
EXPECT_EQ(s4->value(), "3.14");
auto i5 = Integer::New(1);
auto s5 = String::Coerce(i5.get());
EXPECT_EQ(s5->value(), "1");
auto i6 = Integer::New(65536);
auto s6 = String::Coerce(i6.get());
EXPECT_EQ(s6->value(), "65536");
auto a7 = Array::New();
auto s7 = String::Coerce(a7.get());
EXPECT_EQ(s7, nullptr);
}
| true |
bb79fb120069cfd2be7d3187cd3fffa6dd811aad | C++ | YoungHJ203/NumericalAnalysis | /Structure Analysis/201110756_정영훈/Polynominal.h | UHC | 1,518 | 3.640625 | 4 | [] | no_license | #pragma once
#include<iostream>
#define FMAX 3.402823466e+38 // float ڷ ִ ִ
using namespace std;
class Polynominal {
public:
// n
Polynominal(int);
// n
Polynominal(float[]);
// copy
Polynominal(Polynominal&);
// Ҹ
~Polynominal();
// Լ ( Էؼ )
void makePoly();
// ̺
void diffPoly();
// ϴ Լ
void setPoly(int);
// Լ ȯϴ Լ
float value(float);
// ȯ
int getOrder() {
return this->order;
}
// ȯ
float getCoef(int n) {
float coef = 0;
try {
coef=this->poly[this->order-n];
}
catch (out_of_range e) {
cout << "The order enterd exceeds the maximun of range" << endl;
// error float ִ ִ retrun
return FMAX;
}
return coef;
}
private:
// private default
Polynominal() {};
int order; //
float* poly; // 迭
// ŵ ( ŵ n 0 )
float expo(float a, int n) {
if (n >= 0) {
float result = 1;
for (int i = 0; i < n; i++)
result = result*a;
return result;
}
cout << "The order enterd is smaller than zero" << endl;
return FMAX;
}
};
| true |
3ffd6db500c25e615e841f172c4430873934dbf6 | C++ | RealChaser/Rasterizer | /xtozero/Texture.cpp | UHC | 4,544 | 2.6875 | 3 | [] | no_license | #include "stdafx.h"
#include "Texture.h"
#include "FileHandler.h"
#include <iostream>
namespace xtozero
{
CTexture::CTexture( const unsigned int width, const unsigned int height )
: m_width( width ), m_height( height )
{
assert( width > 0 && height > 0 );
m_texture.resize( width * height );
}
CTexture::CTexture()
{
}
CTexture::~CTexture()
{
}
void CTexture::SetSize( const unsigned int width, const unsigned int height )
{
m_width = width;
m_height = height;
m_texture.resize( width * height );
}
CBitmap::CBitmap( const unsigned int width, const unsigned int height ) : CTexture( width, height )
{
}
CBitmap::CBitmap( )
{
}
CBitmap::~CBitmap( )
{
}
void CBitmap::Load( const char *pfileName )
{
CFileHandler bitmapFile( pfileName, std::ios::in | std::ios::binary );
if ( bitmapFile.is_open() )
{
bitmapFile.read( reinterpret_cast<char*>(&m_bitmapHeader), sizeof(BITMAPFILEHEADER) );
bitmapFile.read( reinterpret_cast<char*>(&m_bitmapInfoHeader), sizeof(BITMAPINFOHEADER) );
if ( m_bitmapHeader.bfType == 0x4D42 ) // 'BM' ƽŰ ڵ. ̰ɷ Ʈ θ ִ.
{
if ( m_bitmapInfoHeader.biBitCount > 8 )
{
//ٷ ȼ
SetSize( m_bitmapInfoHeader.biWidth, m_bitmapInfoHeader.biHeight );
if ( m_bitmapInfoHeader.biBitCount == 24 )
{
// Ǿ Ƿ Ųٷ д´.
for ( int i = m_bitmapInfoHeader.biHeight - 1; i >= 0; --i )
{
for ( int j = 0; j < m_bitmapInfoHeader.biWidth; ++j )
{
int index = i * m_bitmapInfoHeader.biWidth + j;
bitmapFile.read( reinterpret_cast<char*>(&m_texture[index].m_color[BLUE]), sizeof(unsigned char) );
bitmapFile.read( reinterpret_cast<char*>(&m_texture[index].m_color[GREEN]), sizeof(unsigned char) );
bitmapFile.read( reinterpret_cast<char*>(&m_texture[index].m_color[RED]), sizeof(unsigned char) );// bmp bgr Ǿ ִ.
}
}
}
}
else
{
//8 Ʈ Ʒ ʹ ķƮ
}
}
else
{
std::cout << "BMP ƴ" << std::endl;
}
}
}
CTextureManager::CTextureManager( )
{
}
CTextureManager::~CTextureManager( )
{
}
std::shared_ptr<CTexture> CTextureManager::Load( const char *pfileName )
{
std::string fileName( pfileName );
std::map<std::string, std::shared_ptr<CTexture> >::iterator findedTex = m_textureMap.find( fileName );
if ( findedTex == m_textureMap.end() )
{
const char* exten = nullptr;
exten = strrchr( pfileName, '.' );
if ( exten )
{
if ( strncmp( exten, ".bmp", 4 ) == 0 )
{
std::shared_ptr<CTexture> texture( new CBitmap( ) );
texture->Load( pfileName );
m_textureMap.insert( make_pair( fileName, texture ) );
return texture;
}
else
{
return nullptr;
}
}
else
{
return nullptr;
}
}
else
{
return findedTex->second;
}
}
unsigned int CBitmap::GetTexel( const float u, const float v )
{
int texX = static_cast<int>( u * ( m_bitmapInfoHeader.biWidth - 1 ) );
int texY = static_cast<int>( v * ( m_bitmapInfoHeader.biHeight - 1 ) );
int index = texY * m_bitmapInfoHeader.biWidth + texX;
return PIXEL_COLOR( m_texture[index].m_color[RED],
m_texture[index].m_color[GREEN],
m_texture[index].m_color[BLUE] );
}
unsigned int CBitmap::GetTexel( const Vector2& texCoord )
{
int texX = static_cast<int>(texCoord.GetU() * (m_bitmapInfoHeader.biWidth - 1));
int texY = static_cast<int>(texCoord.GetV() * (m_bitmapInfoHeader.biHeight - 1));
int index = texY * m_bitmapInfoHeader.biWidth + texX;
index = (index >= m_texture.size()) ? m_texture.size() - 1 : index;
index = (index < 0) ? 0 : index;
return PIXEL_COLOR( m_texture[index].m_color[RED],
m_texture[index].m_color[GREEN],
m_texture[index].m_color[BLUE] );
}
void CBitmap::DrawTexture( void* buffer, int width, int height, int dpp )
{
size_t size = dpp / 8;
unsigned char* frameBuffer = static_cast<unsigned char*>(buffer);
for ( int i = 0; i < m_bitmapInfoHeader.biWidth; ++i )
{
for ( int j = 0; j < m_bitmapInfoHeader.biHeight; ++j )
{
unsigned char* pixel = frameBuffer + ((width * j) + i) * size;
int index = j * m_bitmapInfoHeader.biWidth + i;
pixel[0] = m_texture[index].m_color[RED];
pixel[1] = m_texture[index].m_color[GREEN];
pixel[2] = m_texture[index].m_color[BLUE];
}
}
}
} | true |
10a8c11477ac79e25f2ca51e8407cd1d8592fe71 | C++ | Mshardul/gfg | /01. Data Structure/02. TopicWise DS/03. stack/01. Design and Implementation/008. Design a stack that supports getMin() in O(1) time and O(1) extra space.cpp | UTF-8 | 926 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <stack>
using namespace std;
void Display(stack<int> temp){
while(!temp.empty()){
cout<<temp.top()<<" ";
temp.pop();
}
cout<<endl;
}
int main(int argc, char const *argv[])
{
stack<int> s;
int temp, minEle, ch, ele=0;
cin>>temp;
s.push(temp);
minEle=temp;
while(1){
cout<<"1.push\t2.pop\t3.minEle\t4.Display:\t";
cin>>ch;
if(ch==1){
ele++;
cin>>temp;
if(temp>minEle)
s.push(minEle);
else{
s.push(2*temp-minEle);
minEle=temp;
}
}
else if(ch==2){
if(ele==0){
cout<<"Stack is empty";
continue;
}
cout<<"element popped: ";
if(s.top()>minEle)
cout<<s.top();
else if(s.top()<minEle){
cout<<minEle;
minEle=((2*minEle)-s.top());
}
else
cout<<minEle;
s.pop();
cout<<endl;
}
else if(ch==3)
cout<<"min element: "<<minEle<<endl;
else if(ch==4)
Display(s);
else
break;
}
return 0;
} | true |
9142ed0d0117000955cbd4595a2ca116fabb2fde | C++ | luisenriquelemals/Board-game | /Board.cpp | UTF-8 | 7,493 | 3.34375 | 3 | [] | no_license | /**
* Name: Luis Lema Date: 6/10/2020
* project: game
*/
#include "Board.h"
#include "Exceptions.h"
#include <typeinfo>
#define MIN(a,b) (((a)< (b)? (a) : (b) ))
Board * Board::theBoard = NULL;
Board::Board( ) : nRows(NROWS), nCols(NCOLS), currentTurn(1) {
// Initiliaze the whole table
for (int r = 0; r < nRows; r++){
for ( int c = 0; c < nCols; c++){
pieces[r][c] = new Space();
lastTurnPlayed[r][c] = 0;
}
}
// generate some random robots and bricks
int nRobots = MIN(nCols, 2 + rand() %10); // generate between 2 and 11
int nMines = MIN(nCols, 2 + rand() %10); // generate between 2 and 11
int nBricks = MIN(nCols, 2 + rand() %10); // generate between 2 and 11
if (nRows < 4) {
cerr << "Not Enough rows! I can't play on a board small\n" ;
exit(0);
}
// player on a row[0]
delete pieces[0][0];
pieces[0][0] = new Player();
// robots on row 1
for (int i = 0; i < nRobots; i++){
delete pieces[1][i];
pieces[1][i] = new Robot();
}
// new Mines on row 2
for (int i = 0; i < nMines; i++){
delete pieces[2][i];
pieces[2][i] = new Mine();
}
// new bricks on row 3
for (int i = 0; i < nBricks; i++){
delete pieces[3][i];
pieces[3][i] = new Brick();
}
int randRow, randCol;
Piece * temp;
for (int r = 0; r < nRows ; r++){
for (int c = 0; c < nCols ; c++){
if( r + c <= 0) continue;
randRow = rand() % nRows;
randCol = rand() % nCols;
if( randRow + randCol <= 0)
continue;// we skip player
//swap this Piece with randomly chosen piece
temp = pieces [r][c];
pieces [r][c] = pieces [randRow][randCol];
pieces[randRow][randCol] = temp;
}
}
//And finally scramble the player
playerRow = randRow = rand() % nRows;
playerCol = randCol = rand() % nCols;
temp = pieces[0][0];
pieces [0][0] = pieces[randRow][randCol];
pieces [randRow][randCol] = temp;
}
Board::~Board( ) {
for (int i = 0; i < nRows ; i++){
for (int j = 0; j < nCols; j++){
delete pieces[i][j] ;
}
}
} // Destructor
Board * Board::getBoard( ) {
if (!theBoard) {
theBoard = new Board();
}
return theBoard;
}
void Board::display( ) {
cout << "+========================================+ \n" ;
for (int i = 0; i < nRows; i++){
cout << "|" ;
for (int j = 0; j < nCols; j++) {
cout << pieces[i][j]->display()<< "-";
}
cout << "|\n";
}
cout << "+========================================+ \n" ;
}
void Board::play( ) {
while (true) {
/*Display the Board*/
display();
/*Move the Player */
row = playerRow;
col = playerCol;
/*can the player make a valid move*/
try {
pieces[row][col]->move(row, col);
}catch(Collision & e) {
int collRow, collCol;
e.getLocation(collRow, collCol);
cerr << "Collision caught: "<< e.getDescription() << endl;
cout << "Your are into a "
<< typeid(* pieces[collRow][collCol]).name()
<< "Your lose!\n\n";
return;
}catch (Exception & e) {
cerr << "Exception caught: " << e.getDescription() << endl;
}
// update player's lastTurnedPlayed
lastTurnPlayed [playerRow][ playerCol] = currentTurn;
// Move robots
for (int row = 0; row < nRows; row++){
for (int col = 0; col < nCols; col++){
// do not allow extra turn
if (lastTurnPlayed[row][col] >= currentTurn)
continue;
// Can the piece make a valid move
try{
pieces[row][col]->move(row, col);
}catch(Collision & e) {
int collRow, collCol;
e.getLocation(collRow, collCol);
cerr << "Collision caught: "<< e.getDescription() << endl;
// Collison occur on the player
if (collRow == playerRow && collCol == playerCol){
cout << "A robot got you! you Lose! \n\n";
return;
}
// else robot can run into a mines or another robot
// delete new and old location, insert space and mine
// how many robot are left
delete pieces[row][col];
pieces [row][col] = new Space();
delete pieces[collRow][collCol];
pieces [collRow][collCol] = new Mine();
if (Robot::getRobots() <= 0) {
cout << "Congratulations: No More robots left!\n\n";
return;
}
}catch (Exception & e) {
cerr << "Exception caught: " << e.getDescription() << endl;
// update the lastTurnPlayed flag so they don't get to go again
lastTurnPlayed [row][col] = currentTurn;
}
}// forloop
}// forlloop
currentTurn++;
}// end while
}
void Board::moveMeTo( int newRow, int newCol ) {
if (abs(row - newRow) > 1 || abs(col - newCol) > 1)
throw InvalidMove("New Position too far from old position");
// chewck for bound and negative values
if(newRow < 0) throw SpaceUnavailable("Negative Row");
if(newRow >= nRows)throw SpaceUnavailable("Row Exceeds bounds");
if(newCol < 0) throw SpaceUnavailable("Negative Column");
if(newCol >= nCols)throw SpaceUnavailable("Column Exceeds bounds");
// is there on inmovable barrier in the way? if so, i cannot move you
if(pieces [newRow][newCol]->isBarrier())
throw SpaceUnavailable("Barrier Encountered!") ;
//if the destinartination is not space or a barrier
if(!pieces[newRow][newCol]->isSpace())
throw Collision("Collision encountered", newRow, newCol);
//the destination is valid
Piece * temp = pieces[row][col];
pieces[row][col] = pieces[newRow][newCol];
pieces [newRow][newCol] = temp;
// update the last turned played
lastTurnPlayed[newRow][ newCol] == currentTurn;
if (row == playerRow && col == playerCol) {
playerRow = newRow;
playerCol = newCol;
}
return;
}
/*getting the location of the player*/
void Board::getPlayerPosition( int & row, int & col ) {
row = playerRow;
col = playerCol;
return;
}// end of getPlayerPosition
| true |
f4792dd9d3bde997d7f898ad543fa931eabf092c | C++ | dylanmpeck/CPP-Piscine | /rush00/StaticEntity.cpp | UTF-8 | 951 | 2.96875 | 3 | [] | no_license | #include "StaticEntity.hpp"
StaticEntity::StaticEntity()
{
this->speed = 1;
lastmove = 0;
}
StaticEntity::StaticEntity(int speed)
{
this->speed = speed;
lastmove = 0;
}
StaticEntity::StaticEntity(int speed, Vector & position)
{
this->speed = speed;
this->position = position;
}
StaticEntity::StaticEntity(const StaticEntity& staticentity)
{
*this = staticentity;
}
StaticEntity::~StaticEntity()
{
return;
}
StaticEntity &StaticEntity::operator=(const StaticEntity& staticentity)
{
if (this != & staticentity)
{
GameEntity::operator=(staticentity);
this->lastmove = staticentity.lastmove;
this->speed = staticentity.speed;
}
return *this;
}
void StaticEntity::tick()
{
if (clock() - lastmove > BASESPEED / speed)
{
lastmove = clock();
this->position += Vector(0, 1);
}
}
GameEntity * StaticEntity::clone()
{
return (new StaticEntity(*this));
}
void StaticEntity::setSpeed(unsigned long speed) { this->speed = speed; } | true |
40808d6ee24ec993311ff3b93ed23aa032269ca8 | C++ | JayBeavers/bigbird | /capture/capture.cpp | UTF-8 | 540 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
VideoCapture capture(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH, 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
if(!capture.isOpened()){
cout << "Failed to connect to the camera." << endl;
return -1;
}
Mat frame;
capture >> frame;
if(frame.empty()){
cout << "Failed to capture an image" << endl;
return -2;
}
imwrite("capture.png", frame);
return 0;
} | true |
1da2f987601b0027865757016fa46ebb3f3a27f8 | C++ | jooyoung0525/Algorithm_Study | /20201013/수영대회결승전.cpp | UHC | 2,103 | 2.859375 | 3 | [] | no_license | //ּҽð ϱ.
/*
BFS (ġ,ð,ҿ뵹̱ٸ)
1. BFS¿ -
*/
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
# define MAX 987654321
using namespace std;
struct info { int x, y; };
struct info2 { int x, y, time; bool storm; };
int T;
int N;
int Map[20][20];
bool check[20][20];
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
info startpoint, endpoint;
void solve();
void initialize();
void Input();
int go();
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}
void solve() {
cin >> T;
for (int tc = 1; tc <= T; tc++) {
initialize();
Input();
int result = go();
cout << '#' << tc << ' ' << result<<"\n";
}
}
void initialize() {
N = 0;
memset(Map, 0, sizeof(Map));
memset(check, false, sizeof(check));
startpoint = { 0,0 };
endpoint = { 0,0 };
}
void Input() {
cin >> N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> Map[i][j];
}
}
cin>>startpoint.x;
cin>>startpoint.y;
cin>>endpoint.x;
cin>>endpoint.y;
//cout << endpoint.x << " " << endpoint.y << "\n";
}
int go() {
queue<info2>Q;
Q.push({ startpoint.x,startpoint.y,0,false});
check[startpoint.x][startpoint.y] = true;
while (!Q.empty()) {
int cx = Q.front().x;
int cy = Q.front().y;
int ct = Q.front().time;
bool storm = Q.front().storm;
//cout << cx << " " << cy << " "<<ct<<"\n";
Q.pop();
if (cx == endpoint.x && cy == endpoint.y) {
return ct;
}
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (nx < 0 || ny < 0 || nx >= N || ny >= N|| check[nx][ny])continue;
if (Map[nx][ny] == 0) {
check[nx][ny] = true;
Q.push({ nx,ny,ct + 1,storm});
}
else if (Map[nx][ny] == 2) {
if ((ct+1) % 3 == 0 && ct>0) { //ҿ뵹
check[nx][ny] = true;
Q.push({ nx,ny,ct+1,true});
}
else { //
Q.push({ cx,cy,ct + 1,storm});//ġ ״ ð
}
}
}
}
return -1;
} | true |
4417202191227540f6e030ad8544a144ba5dcb9a | C++ | theJinFei/C-Test | /PAT-Advanced/Spell It Right/main.cpp | UTF-8 | 597 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string N;
cin>>N;
string str[10]={"zero","one","two","three","four","five","six","seven","eight","nine"};
int sum = 0;
vector<string> v1;
for(int i=0;i<N.size();i++){
sum+=N[i]-'0';
}
while(sum!=0){
v1.push_back(str[sum%10]);
sum = sum/10;
}
if(v1.size()==0){
cout<<str[0];
return 0;
}
reverse(v1.begin(),v1.end());
cout<<v1[0];
for(int i=1;i<v1.size();i++){
cout<<" "<<v1[i];
}
return 0;
}
| true |
b9b7411673093b510bdf396948fc2f1827ce51d8 | C++ | TheMarlboroMan/platformer-astronaut | /class/base_proyecto/cargador_recursos_base.h | UTF-8 | 2,148 | 2.734375 | 3 | [
"Unlicense"
] | permissive | #ifndef CARGADOR_RECURSOS_BASE_H
#define CARGADOR_RECURSOS_BASE_H
/*Un cargador de recursos gráficos y de audio. Para cargar los recursos usa
ficheros en disco, localizados en las rutas de turno. Tiene un rollo autoload,
bien para proyectos pequeños, mal para proyectos grandes, puesto que lo que
cargas se queda para siempre cargado.
Estos ficheros tienen una estructura concreta, N valores separados por
tabuladores.
Aunque se pueden generar texturas a partir de superficies, lo vamos a separar
todo por aquí. Para proyectos más grandes haríamos gestores custom :).
Para graficos (texturas y superficies).
#indice ruta transparencia rtrans gtrans btrans
1 data/imagenes/fuente_defecto.png 1 0 0 0
Donde "transparencia" indica si hay transparencia y r, g y btrans indican el
color de pixel transparente.
Para audio:
#indice #ruta
1 data/sonidos/defecto.ogg
Al usar este cargador se cargan todos los recursos directamente en memoria. Esto
puede estar bien para aplicaciones pequeñas, pero si hay muchos gráficos mejor
que usemos métodos alternativos para cargarlos y descargarlos según sea
necesario.
Otra cosa más, si vamos a usarlo no deberíamos almacenar nunca referencias
ni punteros a los recursos, puesto que pueden vaciarse. En su lugar, los
obtenemos siempre mediante los gestores de turno.
*/
#include "../../libdan2/libDan2.h"
extern DLibH::Log_base LOG;
class Cargador_recursos_base
{
private:
DLibV::Pantalla &pantalla;
protected:
virtual std::string obtener_ruta_audio() const=0;
virtual std::string obtener_ruta_texturas() const=0;
virtual std::string obtener_ruta_superficies() const=0;
private:
void procesar_entrada_audio(const std::vector<std::string>&);
void procesar_entrada_textura(const std::vector<std::string>&);
void procesar_entrada_superficie(const std::vector<std::string>&);
void procesar(std::ifstream&, void (Cargador_recursos_base::*)(const std::vector<std::string>&));
public:
Cargador_recursos_base(DLibV::Pantalla& p);
~Cargador_recursos_base();
void generar_recursos_texturas();
void generar_recursos_superficies();
void generar_recursos_audio();
};
#endif
| true |
4bc3fe754d74f96d5fe958aa7158caad44a6dc5f | C++ | tortoisedoc/calculator | /src/Parser.h | UTF-8 | 568 | 2.515625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "Errorclass.h"
class Parser: public ErrorClass
{
private:
t_token PopList(t_token_list * _token_list);
bool isAddOp(char _digit);
int ParseNumber(t_token_list * _token_list);
int ParseAddOp(t_token_list * _token_list);
int ParseExpression(t_token_list * _token_list);
int ParseTerm(t_token_list * _token_list);
int ParseFactor(t_token_list * _token_list);
public:
Parser(std::string _id, t_token_list &_error_list);
~Parser(void);
void Parse(t_token_list * list);
};
| true |
42ab7cb23fbe49fb90cd3e3c6de31693dbaf00ce | C++ | diptu/Teaching | /CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Assignment(Student Database)/main(16).cpp | UTF-8 | 479 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <string>
#include <iostream>
using namespace std;
#include "student.h"
int main()
{
StudentDB s(6);
string name;
cout << "Enter name to search: ";
cin >> name;
int t=s.searchStudent(name);
if(t>=0)
s.st[t].print();
else cout<<"student not found\n";
int id;
cout << "Enter id to search: ";
cin >> id;
t=s.searchStudent(id);
if(t>=0)
s.st[t].print();
else cout<<"student not found\n";
return 0;
}
| true |
5d493e8530931c299167e12546f7d8172c95de67 | C++ | Roout/acst | /common/SwitchBuffer.hpp | UTF-8 | 1,499 | 3.34375 | 3 | [
"MIT"
] | permissive | #include <string>
#include <array>
#include <vector>
#include <boost/asio.hpp>
class SwitchBuffer {
public:
SwitchBuffer(size_t reserved = 10) {
m_buffers[0].reserve(reserved);
m_buffers[1].reserve(reserved);
m_bufferSequence.reserve(reserved);
}
/**
* Queue data to passibe buffer.
*/
void Enque(std::string&& data) {
m_buffers[m_activeBuffer ^ 1].emplace_back(std::move(data));
}
/**
* Swap buffers and update @m_bufferSequence.
*/
void SwapBuffers() {
m_bufferSequence.clear();
m_buffers[m_activeBuffer].clear();
m_activeBuffer ^= 1;
for (const auto& buf: m_buffers[m_activeBuffer]) {
m_bufferSequence.emplace_back(boost::asio::const_buffer(buf.c_str(), buf.size()));
}
}
size_t GetQueueSize() const noexcept {
return m_buffers[m_activeBuffer ^ 1].size();
}
const std::vector<boost::asio::const_buffer>& GetBufferSequence() const noexcept {
return m_bufferSequence;
}
private:
using DoubleBuffer = std::array<std::vector<std::string>, 2>;
/**
* Represent two sequences of some buffers
* One sequence is active, another one is passive.
* They can be swapped when needed.
**/
DoubleBuffer m_buffers;
/**
* View const buffer sequence used by write operations.
*/
std::vector<boost::asio::const_buffer> m_bufferSequence;
size_t m_activeBuffer { 0 };
}; | true |
df58ef50f315782d4f2c330144e0cb2ca3bb03bd | C++ | Red-Portal/nast_hpx | /src/util/triple.hpp | UTF-8 | 1,209 | 3.265625 | 3 | [] | no_license | #ifndef NAST_HPX_UTIL_TRIPLE_HPP_
#define NAST_HPX_UTIL_TRIPLE_HPP_
#include <iostream>
namespace nast_hpx {
template<typename T>
struct triple {
triple() : x(), y(), z() {}
triple(T value) : x(value), y(value), z(value) {}
triple(T x_value, T y_value, T z_value) : x(x_value), y(y_value), z(z_value) {}
triple(triple<T> const& other) : x(other.x), y(other.y), z(other.z) {}
triple(triple<T>&& other) : x(std::move(other.x)), y(std::move(other.y)), z(std::move(other.z)) {}
triple<T>& operator=(triple<T> const& other)
{
x = other.x;
y = other.y;
z = other.z;
return *this;
}
triple<T>& operator=(triple<T>&& other)
{
x = std::move(other.x);
y = std::move(other.y);
z = std::move(other.z);
return *this;
}
T x, y, z;
template <typename Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & x & y & z;
}
friend std::ostream& operator<<(std::ostream& os, triple<T> const& triple)
{
os << "{" << triple.x << "," << triple.y << "," << triple.z << "}";
return os;
}
};
typedef triple<std::size_t> index;
}
#endif
| true |
fce44eecf18c44fbd225d602d9b09781f9397c84 | C++ | iZhangHui/CppPrimer | /CH16_TemplatesAndGenericProgramming/exercises/ex16_12_13.h | UTF-8 | 6,535 | 3.671875 | 4 | [
"Unlicense"
] | permissive | #include <vector>
#include <memory>
#include <initializer_list>
#include <iterator>
// forward declarations needed for friend decalarations in Blob
template <typename>
class BlobPtr;
template <typename>
class Blob; // needed for parameters in operator==
template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob
{
// each instantiation of Blob grants access to the version of
// BlobPtr and the equality operator instantiated with the same type
friend class BlobPtr<T>;
friend bool operator==<T>(const Blob<T>&, const Blob<T>&);
public:
using size_type = typename std::vector<T>::size_type;
// constructors
Blob() : data(std::make_shared<std::vector<T>>()) { }
Blob(std::initializer_list<T> il)
: data(std::make_shared<std::vector<T>>(il)) { }
Blob(T* p, std::size_t n) : data(std::make_shared<std::vector<T>>(p, p + n)) { };
template <typename It>
Blob(It b, It e) : data(std::make_shared<std::vector<T>>(b, e)) { };
// number of elements in the Blob
size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
// add and remove elements
// void push_back(const T& t) { data->push_back(t); }
// void push_back(T&& t) { data->push_back(std::move(t)); }
void push_back(T&& t) { data->push_back(std::forward<T>(t)); }
void pop_back();
// element access
T& front();
T& back();
T& at(size_type);
T& operator[](size_type i);
const T& front() const;
const T& back() const;
const T& at(size_type) const;
const T& operator[](size_type i) const;
void swap(Blob& b) { data.swap(b.data); }
// return BlobPtr to the first and one past the last elements
BlobPtr<T> begin() { return BlobPtr<T>(*this); }
BlobPtr<T> end() { return BlobPtr<T>(*this, data->size()); }
private:
std::shared_ptr<std::vector<T>> data;
// throw msg if data[i] isn't valid
void check(size_type i, const std::string& msg) const;
};
// check member
template <typename T>
void Blob<T>::check(size_type i, const std::string& msg) const
{
if (i >= data->size()) {
throw std::out_of_range(msg);
}
}
template <typename T>
void Blob<T>::pop_back()
{
check(0, "pop_back on empty Blob");
data->pop_back();
}
// element access members
template <typename T>
T& Blob<T>::back()
{
check(0, "back on empty Blob");
return data->back();
}
template <typename T>
const T& Blob<T>::back() const
{
check(0, "back on empty Blob");
return data->back();
}
template <typename T>
T& Blob<T>::front()
{
// if the vector is empty, check will throw
check(0, "front on empty Blob");
return data->front();
}
template <typename T>
const T& Blob<T>::front() const
{
check(0, "front on empty Blob");
return data->front();
}
template <typename T>
T& Blob<T>::operator[](size_type i)
{
// if i is too big, check will throw, preventing access to a nonexistent element
check(i, "subscript out of range");
return (*data)[i]; // (*data) is the vector to which this object points
}
template <typename T>
const T& Blob<T>::operator[](size_type i) const
{
check(i, "subscript out of range");
return (*data)[i];
}
template <typename T>
T& Blob<T>::at(size_type i)
{
// if i is too big, check will throw, preventing access to a nonexistent element
check(i, "subscript out of range");
return (*data)[i];
}
template <typename T>
const T& Blob<T>::at(size_type i) const
{
check(i, "subscript out of range");
return (*data)[i];
}
// operators
template <typename T>
std::ostream& operator<<(std::ostream& os, const Blob<T>& a)
{
os << "< ";
for (size_t i = 0; i != a.size(); ++i)
os << a[i] << " ";
os << " >";
return os;
}
template <typename T>
bool operator==(const Blob<T>& lhs, const Blob<T>& rhs)
{
if (rhs.size() != lhs.size())
return false;
for (size_t i = 0; i < lhs.size(); ++i)
if (lhs[i] != rhs[i])
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////
// BlobPtr throws an exception on attempts to access a nonexistent element
template <typename T>
bool operator==(const BlobPtr<T>&, const BlobPtr<T>&);
template <typename T>
class BlobPtr //: public std::iterator<std::bidirectional_iterator_tag, T>
{
friend bool operator==<T>(const BlobPtr<T>&, const BlobPtr<T>&);
public:
BlobPtr() : curr(0) { }
BlobPtr(Blob<T>& a, size_t sz = 0):
wptr(a.data), curr(sz) { }
T& operator[](std::size_t i)
{
auto p = check(i, "subscript out of range");
return (*p)[i];
}
const T& operator[](std::size_t i) const
{
auto p = check(i, "subscript out of range");
return (*p)[i];
}
T& operator*() const
{
auto p = check(curr, "dereference past end");
return (*p)[curr];
}
T* operator->()
{
// delegate the real work to the dereference operator
return & this->operator*();
}
// increment and decrement
// prefix
BlobPtr& operator++();
BlobPtr& operator--();
// postfix
BlobPtr operator++(int);
BlobPtr operator--(int);
private:
std::shared_ptr<std::vector<T>> check(std::size_t, const std::string&) const;
std::weak_ptr<std::vector<T>> wptr;
std::size_t curr;
};
// equality operators
template <typename T>
bool operator==(const BlobPtr<T>& lhs, const BlobPtr<T>& rhs)
{
// std::shared_ptr<T> lock() const;(since C++11)
// Creates a new std::shared_ptr that shares ownership of the managed object.
// If there is no managed object, i.e. *this is empty, then the returned shared_ptr also is empty.
// Effectively returns expired() ? shared_ptr<T>() : shared_ptr<T>(*this), executed atomically.
return lhs.wptr.lock().get() == rhs.wptr.lock().get() && lhs.curr == rhs.curr;
}
template <typename T>
bool operator!=(const BlobPtr<T>& lhs, const BlobPtr<T>& rhs)
{
return !(lhs == rhs);
}
template <typename T>
std::shared_ptr<std::vector<T>> BlobPtr<T>::check(std::size_t i, const std::string& msg) const
{
// is the vector still around?
auto ret = wptr.lock();
if (!ret)
throw std::runtime_error("unbound StrBlobPtr");
if (i >= ret->size())
throw std::out_of_range(msg);
// otherwise, return a shared_ptr to the vector
return ret;
}
template <typename T>
BlobPtr<T>& BlobPtr<T>::operator++()
{
check(curr, "increment past end of BlobPtr");
++curr;
return *this;
}
template <typename T>
BlobPtr<T>& BlobPtr<T>::operator--()
{
--curr;
check(curr, "decrement past begin of BlobPtr");
return *this;
}
template <typename T>
BlobPtr<T> BlobPtr<T>::operator++(int)
{
BlobPtr ret = *this;
++*this;
return ret;
}
template <typename T>
BlobPtr<T> BlobPtr<T>::operator--(int)
{
BlobPtr ret = *this;
--*this;
return ret;
} | true |
ce98e6044228e46ec4ca876b06bdc41b5408eee1 | C++ | iridium-browser/iridium-browser | /buildtools/third_party/libc++/trunk/test/std/utilities/expected/expected.void/ctor/ctor.move.pass.cpp | UTF-8 | 3,376 | 2.84375 | 3 | [
"BSD-3-Clause",
"NCSA",
"MIT",
"LLVM-exception",
"Apache-2.0"
] | permissive | //===----------------------------------------------------------------------===//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
// constexpr expected(expected&& rhs) noexcept(is_nothrow_move_constructible_v<E>);
//
// Constraints: is_move_constructible_v<E> is true.
//
// Effects: If rhs.has_value() is false, direct-non-list-initializes unex with std::move(rhs.error()).
//
// Postconditions: rhs.has_value() is unchanged; rhs.has_value() == this->has_value() is true.
//
// Throws: Any exception thrown by the initialization of unex.
//
// Remarks: This constructor is trivial if is_trivially_move_constructible_v<E> is true.
#include <cassert>
#include <expected>
#include <type_traits>
#include <utility>
#include "test_macros.h"
struct NonMovable {
NonMovable(NonMovable&&) = delete;
};
struct MovableNonTrivial {
int i;
constexpr MovableNonTrivial(int ii) : i(ii) {}
constexpr MovableNonTrivial(MovableNonTrivial&& o) : i(o.i) { o.i = 0; }
friend constexpr bool operator==(const MovableNonTrivial&, const MovableNonTrivial&) = default;
};
struct MoveMayThrow {
MoveMayThrow(MoveMayThrow&&) {}
};
// Test Constraints:
// - is_move_constructible_v<E> is true.
static_assert(std::is_move_constructible_v<std::expected<void, int>>);
static_assert(std::is_move_constructible_v<std::expected<void, MovableNonTrivial>>);
static_assert(!std::is_move_constructible_v<std::expected<void, NonMovable>>);
// Test: This constructor is trivial if is_trivially_move_constructible_v<E> is true.
static_assert(std::is_trivially_move_constructible_v<std::expected<void, int>>);
static_assert(!std::is_trivially_move_constructible_v<std::expected<void, MovableNonTrivial>>);
// Test: noexcept(is_nothrow_move_constructible_v<E>)
static_assert(std::is_nothrow_move_constructible_v<std::expected<int, int>>);
static_assert(!std::is_nothrow_move_constructible_v<std::expected<MoveMayThrow, int>>);
static_assert(!std::is_nothrow_move_constructible_v<std::expected<int, MoveMayThrow>>);
static_assert(!std::is_nothrow_move_constructible_v<std::expected<MoveMayThrow, MoveMayThrow>>);
constexpr bool test() {
// move the error non-trivial
{
std::expected<void, MovableNonTrivial> e1(std::unexpect, 5);
auto e2 = std::move(e1);
assert(!e2.has_value());
assert(e2.error().i == 5);
assert(!e1.has_value());
assert(e1.error().i == 0);
}
// move the error trivial
{
std::expected<void, int> e1(std::unexpect, 5);
auto e2 = std::move(e1);
assert(!e2.has_value());
assert(e2.error() == 5);
assert(!e1.has_value());
}
return true;
}
void testException() {
#ifndef TEST_HAS_NO_EXCEPTIONS
struct Except {};
struct Throwing {
Throwing() = default;
Throwing(Throwing&&) { throw Except{}; }
};
// throw on moving error
{
std::expected<void, Throwing> e1(std::unexpect);
try {
[[maybe_unused]] auto e2 = std::move(e1);
assert(false);
} catch (Except) {
}
}
#endif // TEST_HAS_NO_EXCEPTIONS
}
int main(int, char**) {
test();
static_assert(test());
testException();
return 0;
}
| true |
1c8d2e3869c4b188dc5f3fc0488b1d0143aefc6a | C++ | q4a/GLKeeper | /src/GuiHierarchy.h | UTF-8 | 2,143 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "GuiDefs.h"
class GuiHierarchy: public cxx::noncopyable
{
public:
// readonly
GuiWidget* mRootWidget = nullptr;
public:
~GuiHierarchy();
// load widgets hierarchy from json document
// @param fileName: File name
bool LoadFromFile(const std::string& fileName);
bool LoadFromJson(const cxx::json_document& jsonDocument);
void Cleanup();
// render hierarchy
void RenderFrame(GuiRenderer& renderContext);
// process hierarchy
void UpdateFrame();
// show or hire, enable or disable hierarchy
void SetVisible(bool isVisible);
void SetEnabled(bool isEnabled);
// handle screen resolution changed during runtime
void FitLayoutToScreen(const Point& screenDimensions);
// pick visible and interactive widget at specified screen coordinate
// @param screenPosition: Screen coordinate
GuiWidget* PickWidget(const Point& screenPosition) const;
// find widget by specific location within hierarchy
// @param widgetPath: Path, includes root
GuiWidget* GetWidgetByPath(const std::string& widgetPath) const;
// get first widget withing hierarchy with specific name
GuiWidget* SearchForWidget(const cxx::unique_string& name) const;
GuiWidget* SearchForWidget(const std::string& name) const;
// construct new template widget of specified class
// @param className: Template widget class name
GuiWidget* CreateTemplateWidget(cxx::unique_string className) const;
private:
// destroy template widgets
void FreeTemplateWidgets();
GuiWidget* DeserializeWidgetWithChildren(cxx::json_node_object objectNode);
GuiWidget* DeserializeTemplateWidget(cxx::json_node_object objectNode);
void LoadChildrenWidgetProperties(GuiWidget* parentWidget, cxx::json_node_object objectNode);
bool LoadTemplateWidgets(cxx::json_node_object objectNode);
bool LoadHierarchy(cxx::json_node_object objectNode);
private:
using GuiTemplateWidgetsMap = std::map<cxx::unique_string, GuiWidget*>;
GuiTemplateWidgetsMap mTemplateWidgetsClasses;
}; | true |
f0c2062b8eea7a77ffd853394379b0ed4512f7c5 | C++ | AndreiGolovatskii/sportprog | /lksh2017/Day12/C.cpp | UTF-8 | 1,944 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Vector{
long double x, y;
Vector() {}
Vector(long double cx, long double cy) {
x = cx;
y = cy;
}
long double len() const {
return hypot(x, y);
}
long double dot_product(Vector b) {
return x * b.x + y * b.y;
}
long double cross_product(Vector b) {
return x * b.y - y * b.x;
}
long double angle(Vector b) {
return abs(atan2(cross_product(b), dot_product(b)));
}
Vector r_vector() const {
return Vector(-x, -y);
}
Vector n_vector() const {
return Vector(x / hypot(x, y), y / hypot(x, y));
}
const Vector operator-(const Vector &a) const {
return Vector(x - a.x, y - a.y);
}
const Vector operator+(const Vector &a) const {
return Vector(x + a.x, y + a.y);
}
const Vector operator*(const long double &a) const {
return Vector(x * a, y * a);
}
const bool operator==(const Vector &a) const {
return y == a.y && x == a.x;
}
const bool operator<(const Vector &a) const {
return x < a.x || x == a.x && y < a.y;
}
};
const long double EPS = 1e-5;
int main() {
int n;
cin >> n;
vector<Vector> dots(n);
for (int i = 0; i < n; ++i) {
cin >> dots[i].x >> dots[i].y;
}
Vector sides[n];
for (int i = 0; i < n; ++i) {
int ni = i + 1;
if (ni == n) {
ni = 0;
}
Vector side = dots[ni] - dots[i];
sides[i] = side;
}
long double len = sides[0].len();
long double an = (long double) M_PI * (n - 2) / n;
for (int i = 0; i < n; ++i) {
int ni = i + 1;
if (ni == n) {
ni = 0;
}
if (abs(len - sides[i].len()) > EPS || abs(sides[i].r_vector().angle(sides[ni]) - an) > EPS) {
cout << "NO";
return 0;
}
}
cout << "YES";
} | true |
632f5964eb520754a4582edbf19e2e7987473d12 | C++ | SavaDtrv/Object-oriented-programming-school-works | /Project made during the semester/Deck.cpp | UTF-8 | 758 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "Deck.h"
using namespace std;
const int DEFAULT_CAPACITY = 10;
const int DEFFAULT_CURRENTCARD = 0;
Deck::Deck()
{
capacity = DEFAULT_CAPACITY;
currentCard = DEFFAULT_CURRENTCARD;
cards = new Card*[capacity];
}
Deck::Deck(const Deck& other) {
copyDeck(other);
}
Deck& Deck::operator=(const Deck& other) {
if (this != &other) {
removeDeck();
copyDeck(other);
}
return *this;
}
Deck::~Deck() {
removeDeck();
}
void Deck::addCard(Card & newCard)
{
add(newCard);
}
void Deck::removeSpecCardFromDeck(int index)
{
for (int i = index; i < currentCard; i++)
{
cards[i] = cards[i + 1];
}
currentCard--;
}
Card * Deck::getAt(int index)
{
return cards[index];
}
| true |
f8c945402b4d99d41c5af161172005c15018f626 | C++ | rharel/cpp-efficient-reformation | /demo/sources/model/World.cpp | UTF-8 | 1,230 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <assert.h>
#include <glm/geometric.hpp>
#include "World.h"
using namespace rharel::efficient_reformation::demo;
World::World(const unsigned int vehicle_count)
: vehicles(vehicle_count)
{}
void World::step(const float duration)
{
if (duration <= 0) { return; }
for (auto& vehicle : vehicles)
{
step_vehicle(vehicle, duration);
}
}
void World::step_vehicle(Vehicle& vehicle, const float duration)
{
assert(vehicle.speed >= 0);
assert(duration > 0);
if (vehicle.position == vehicle.target) { return; }
const glm::vec2 path = vehicle.target - vehicle.position;
const float path_length = glm::length(path),
distance_covered = vehicle.speed * duration;
if (path_length <= distance_covered)
{
vehicle.position = vehicle.target;
}
else
{
vehicle.position += path * (distance_covered / path_length);
}
}
unsigned int World::get_vehicle_count() const
{
return vehicles.size();
}
const Vehicle& World::get_vehicle(const unsigned int index) const
{
return vehicles.at(index);
}
Vehicle& World::get_vehicle(const unsigned int index)
{
return vehicles.at(index);
}
| true |
3e85fa8d52ad707e3aa8614b7ccd9d39e6c1fdaf | C++ | biqar/interviewbit | /Math/Adhoc/Prime Sum/prime_sum.cpp | UTF-8 | 418 | 3 | 3 | [
"MIT"
] | permissive | //
// Created by aislam6 on 11/27/19.
//
bool is_prime(int a) {
for(int i=2; i*i<=a; i+=1) {
if(a % i == 0) return false;
}
return true;
}
vector<int> Solution::primesum(int A) {
vector<int> ret;
for(int i=2; i<=(A/2)+1; i+=1) {
if(is_prime(i) && is_prime(A-i)) {
ret.push_back(i);
ret.push_back(A-i);
break;
}
}
return ret;
}
| true |
334da48783c0073ef1131b1ce514ddc471786e2e | C++ | TimoninaDaria/msu_cpp_spring_2020 | /09/test.cpp | UTF-8 | 1,102 | 2.796875 | 3 | [] | no_license | #include "merge.h"
#include <cassert>
using namespace std;
void generator(const string& namefile){
ofstream fout;
uint64_t v;
fout.open(namefile, ios::binary);
for (int i = 0; i < 100001; ++i){
v = std::rand() + 1;
fout.write(reinterpret_cast<char *>(&v), sizeof(uint64_t));
}
}
void test(const string& inputfile, const string& outputfile){
ifstream f1(inputfile, ios::binary);
ifstream f2(outputfile, ios::binary);
int len_input = 0;
int len_output = 1;
uint64_t x, y;
while(!f1.eof())
{
f1.read(reinterpret_cast<char*>(&y), sizeof(uint64_t));
++len_input;
}
f2.read(reinterpret_cast<char*>(&x), sizeof(uint64_t));
while(!f2.eof())
{
f2.read(reinterpret_cast<char*>(&y), sizeof(uint64_t));
++len_output;
assert(x <= y);
x = y;
}
assert(len_input == len_output);
}
int main(){
generator("numbers.dat"); //let's generate input file
int isok = sort_by_merge("numbers.dat");
assert(isok == 0);
test("numbers.dat", "result.dat"); //check output file
return 0;
}
| true |
615526e0583b49fca6d4b058270083e49d782166 | C++ | glynos/url | /include/skyr/v2/unicode/ranges/views/unchecked_u8_view.hpp | UTF-8 | 3,904 | 2.546875 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright 2019-20 Glyn Matthews.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SKYR_V2_UNICODE_RANGES_VIEWS_UNCHECKED_U8_VIEW_HPP
#define SKYR_V2_UNICODE_RANGES_VIEWS_UNCHECKED_U8_VIEW_HPP
#include <iterator>
#include <algorithm>
#include <cassert>
#include <tl/expected.hpp>
#include <skyr/v2/unicode/code_point.hpp>
#include <skyr/v2/unicode/core.hpp>
#include <skyr/v2/unicode/errors.hpp>
#include <skyr/v2/unicode/traits/range_iterator.hpp>
#include <skyr/v2/unicode/ranges/sentinel.hpp>
namespace skyr::inline v2::unicode {
///
/// \tparam OctetIterator
template <class OctetIterator>
class unchecked_u8_range_iterator {
public:
///
using iterator_category = std::forward_iterator_tag;
///
using value_type = u8_code_point_view<OctetIterator>;
///
using const_reference = value_type;
///
using reference = const_reference;
///
using const_pointer = const value_type *;
///
using pointer = const_reference;
///
using difference_type = std::ptrdiff_t;
///
using size_type = std::size_t;
///
/// \param it
/// \param last
constexpr unchecked_u8_range_iterator(OctetIterator it, OctetIterator last) : it_(it), last_(last) {
}
///
/// \return
constexpr auto operator++(int) noexcept -> unchecked_u8_range_iterator {
assert(it_ != last_);
auto result = *this;
increment();
return result;
}
///
/// \return
constexpr auto operator++() noexcept -> unchecked_u8_range_iterator & {
assert(it_ != last_);
increment();
return *this;
}
///
/// \return
[[nodiscard]] constexpr auto operator*() const noexcept -> const_reference {
assert(it_ != last_);
auto last = it_;
std::advance(last, sequence_length(*it_));
return u8_code_point_view<OctetIterator>(it_, last);
}
///
/// \param sentinel
/// \return
[[nodiscard]] constexpr auto operator==([[maybe_unused]] sentinel sentinel) const noexcept {
return it_ == last_;
}
///
/// \param sentinel
/// \return
[[nodiscard]] constexpr auto operator!=(sentinel sentinel) const noexcept {
return !(*this == sentinel);
}
private:
constexpr void increment() {
std::advance(it_, sequence_length(*it_));
}
OctetIterator it_, last_;
};
///
/// \tparam OctetRange
template <class OctetRange>
class view_unchecked_u8_range {
using octet_iterator_type = traits::range_iterator_t<OctetRange>;
using iterator_type = unchecked_u8_range_iterator<octet_iterator_type>;
public:
///
using value_type = u8_code_point_view<octet_iterator_type>;
///
using const_reference = value_type;
///
using reference = const_reference;
///
using const_iterator = iterator_type;
///
using iterator = const_iterator;
///
using size_type = std::size_t;
///
/// \param range
explicit constexpr view_unchecked_u8_range(const OctetRange &range) : it_(std::begin(range), std::end(range)) {
}
///
/// \return
[[nodiscard]] constexpr auto cbegin() const noexcept {
return it_;
}
///
/// \return
[[nodiscard]] constexpr auto cend() const noexcept {
return sentinel{};
}
///
/// \return
[[nodiscard]] constexpr auto begin() const noexcept {
return cbegin();
}
///
/// \return
[[nodiscard]] constexpr auto end() const noexcept {
return cend();
}
///
/// \return
[[nodiscard]] constexpr auto empty() const noexcept {
return begin() == end();
}
private:
iterator_type it_;
};
namespace views {
///
/// \tparam OctetRange
/// \param range
/// \return
template <typename OctetRange>
[[maybe_unused]] constexpr inline auto unchecked_u8(const OctetRange &range) {
return view_unchecked_u8_range{range};
}
} // namespace views
} // namespace skyr::inline v2::unicode
#endif // SKYR_V2_UNICODE_RANGES_VIEWS_UNCHECKED_U8_VIEW_HPP
| true |
7aea2d89e8bf4c61f6ccd75008923ef53a9d5a41 | C++ | GRBurst/gates | /src/DeferredShading.cpp | UTF-8 | 6,467 | 2.671875 | 3 | [] | no_license | #include "DeferredShading.h"
DeferredShading::DeferredShading(const GLint& gBufferProgram, const GLint& deferredShadingProgram, Camera *const camera)
: mGBufferProgram(gBufferProgram)
, mDeferredShadingProgram(deferredShadingProgram)
, mGBuffer(0)
, mGDepth(0)
/* , mCamera(camera) */
, mGPosition()
, mGNormal()
, mGAlbedo()
, mResolutionX(1280)
, mResolutionY(1024)
, mNumLights(32)
{
this->mCamera = camera;
/* std::vector<glm::vec3> lightPositions; */
/* std::vector<glm::vec3> lightColors; */
}
DeferredShading::~DeferredShading()
{}
void DeferredShading::init()
{
glGenFramebuffers(1, &mGBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, mGBuffer);
mGPosition.bind();
mGPosition.setResolution(mResolutionX, mResolutionY);
mGPosition.loadGDepthPositionOptions();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mGPosition.getTexture(), 0);
mGNormal.bind();
mGNormal.setResolution(mResolutionX, mResolutionY);
mGNormal.loadGNormalOptions();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, mGNormal.getTexture(), 0);
mGAlbedo.bind();
mGAlbedo.setResolution(mResolutionX, mResolutionY);
mGAlbedo.loadGAlbedoOptions();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, mGAlbedo.getTexture(), 0);
/* glGenTextures(1, &gAlbedoSpec); */
/* glBindTexture(GL_TEXTURE_2D, gAlbedoSpec); */
/* glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mResolutionX, mResolutionY, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); */
/* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); */
/* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); */
/* glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, gAlbedoSpec, 0); */
GLuint drawBuffers[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, drawBuffers);
glGenRenderbuffers(1, &mGDepth);
glBindRenderbuffer(GL_RENDERBUFFER, mGDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, mResolutionX, mResolutionY);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mGDepth);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
std::cout << "Framebuffer not complete!" << std::endl;
}
void DeferredShading::linkTextures()
{
linkTextures(mDeferredShadingProgram);
}
void DeferredShading::linkTextures(const GLint& shader)
{
/* glUseProgram(mDeferredShadingShaderProgram); */
/* glUniform1i(glGetUniformLocation(shader, "uGPosition"), 10); */
/* glUniform1i(glGetUniformLocation(shader, "uGNormal"), 11); */
/* glUniform1i(glGetUniformLocation(shader, "uGAlbedo"), 12); */
mGPosition.linkTexture(shader, "uGPosition");
mGNormal.linkTexture(shader, "uGNormal");
mGAlbedo.linkTexture(shader, "uGAlbedo");
}
void DeferredShading::initRandomLights()
{
srand(100);
for (int i = 0; i < mNumLights; i++)
{
// Calculate slightly random offsets
GLfloat xPos = ((rand() % 50)) - 25.0;
GLfloat yPos = 10.0;
GLfloat zPos = ((rand() % 50)) - 25.0;
lightPositions.push_back(glm::vec3(xPos, yPos, zPos));
// Also calculate random color
GLfloat rColor = ((rand() % 100) / 200.0f) + 0.5; // Between 0.5 and 1.0
GLfloat gColor = ((rand() % 100) / 200.0f) + 0.5; // Between 0.5 and 1.0
GLfloat bColor = ((rand() % 100) / 200.0f) + 0.5; // Between 0.5 and 1.0
lightColors.push_back(glm::vec3(rColor, gColor, bColor));
}
}
void DeferredShading::bindFBO()
{
glBindFramebuffer(GL_FRAMEBUFFER, mGBuffer);
}
void DeferredShading::bindTextures()
{
mGPosition.bind();
mGNormal.bind();
mGAlbedo.bind();
}
void DeferredShading::loadUniforms(Terrain *const terrain)
{
loadUniforms(mGBufferProgram, terrain);
}
void DeferredShading::loadUniforms(const GLint& shader, Terrain *const terrain)
{
glUseProgram(shader);
// Also send light relevant uniforms
for (GLuint i = 0; i < lightPositions.size(); i++)
{
glUniform3fv(glGetUniformLocation(shader, ("lights[" + std::to_string(i) + "].Position").c_str()), 1, &lightPositions[i][0]);
glUniform3fv(glGetUniformLocation(shader, ("lights[" + std::to_string(i) + "].Color").c_str()), 1, &lightColors[i][0]);
// Update attenuation parameters and calculate radius
const GLfloat constant = 1.0; // Note that we don't send this to the shader, we assume it is always 1.0 (in our case)
const GLfloat linear = 0.7;
const GLfloat quadratic = 1.8;
glUniform1f(glGetUniformLocation(shader, ("lights[" + std::to_string(i) + "].Linear").c_str()), linear);
glUniform1f(glGetUniformLocation(shader, ("lights[" + std::to_string(i) + "].Quadratic").c_str()), quadratic);
// Then calculate radius of light volume/sphere
const GLfloat lightThreshold = 5.0; // 5 / 256
const GLfloat maxBrightness = std::fmaxf(std::fmaxf(lightColors[i].r, lightColors[i].g), lightColors[i].b);
GLfloat radius = (-linear + static_cast<float>(std::sqrt(linear * linear - 4 * quadratic * (constant - (256.0 / lightThreshold) * maxBrightness)))) / (2 * quadratic);
glUniform1f(glGetUniformLocation(shader, ("lights[" + std::to_string(i) + "].Radius").c_str()), radius);
}
glUniform3fv(glGetUniformLocation(shader, "uCamPos"), 1, &(mCamera->getPosition()[0]));
glUniform3fv(glGetUniformLocation(shader, "uRayTerrainIntersection"), 1, &(terrain->getRayTerrainIntersection()[0]));
glUniform1f(glGetUniformLocation(shader, "uNearPlane"), mCamera->getNearPlane());
glUniform1f(glGetUniformLocation(shader, "uFarPlane"), mCamera->getFarPlane());
glUniform1f(glGetUniformLocation(shader, "uEditMode"), terrain->getEditMode());
glUniform1f(glGetUniformLocation(shader, "uModifyRadius"), terrain->getModifyRadius());
terrain->loadGBufferMaps(shader);
}
void DeferredShading::copyDepthBuffer(const GLuint& destinationFBO)
{
// 2.5. Copy content of geometry's depth buffer to default framebuffer's depth buffer
glBindFramebuffer(GL_READ_FRAMEBUFFER, mGBuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, destinationFBO);
glBlitFramebuffer(0, 0, mResolutionX, mResolutionY, 0, 0, mResolutionX, mResolutionY, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
| true |
c2fc3add25d8c042925433a2c0a76cffac2ec54c | C++ | paksas/Tamy | /Code/Engine/gl-Renderer/GLRProceduralTextureResourcesStorage.cpp | UTF-8 | 2,500 | 2.515625 | 3 | [] | no_license | #include "gl-Renderer\GLRProceduralTextureResourcesStorage.h"
#include "gl-Renderer\GLRenderer.h"
#include "gl-Renderer\GLRDefinitions.h"
#include "gl-Renderer\GLRErrorCheck.h"
#include "SOIL.h"
#include "core\Log.h"
///////////////////////////////////////////////////////////////////////////////
word g_format_1 [] = {
GL_RGB,
GL_RGBA32F
};
word g_format_2 [] = {
GL_RGB,
GL_RGBA
};
word g_format_3 [] = {
GL_UNSIGNED_BYTE,
GL_FLOAT
};
template<>
uint RenderResourceStorage< GLRenderer, ProceduralTexture, uint >::createResource( const ProceduralTexture* obj ) const
{
uint textureID = 0;
glGenTextures( 1, &textureID );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, textureID );
GLR_HALT_ERRORS();
uint textureWidth = obj->getWidth();
uint textureHeight = obj->getHeight();
const byte* pData = obj->getImageBuffer();
const word format1 = g_format_1[obj->getFormat()];
const word format2 = g_format_2[obj->getFormat()];
const word format3 = g_format_3[obj->getFormat()];
glTexImage2D( GL_TEXTURE_2D, 0, format1, textureWidth, textureHeight, 0, format2, format3, pData );
GLR_HALT_ERRORS();
// generate mipmaps
const byte numMipMaps = obj->getMipmapsCount();
if ( numMipMaps > 1 )
{
glTexStorage2D( GL_TEXTURE_2D, numMipMaps, format1, textureWidth, textureHeight );
glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, textureWidth, textureHeight, format2, format3, pData );
glGenerateMipmap( GL_TEXTURE_2D );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
GLR_HALT_ERRORS();
}
return textureID;
}
///////////////////////////////////////////////////////////////////////////////
template<>
void RenderResourceStorage< GLRenderer, ProceduralTexture, uint >::releaseResource( uint textureID ) const
{
glDeleteTextures( 1, &textureID );
}
///////////////////////////////////////////////////////////////////////////////
template<>
void RenderResourceStorage< GLRenderer, ProceduralTexture, uint >::refreshResource( const ProceduralTexture* obj, uint& textureID ) const
{
releaseResource( textureID );
textureID = createResource( obj );
}
///////////////////////////////////////////////////////////////////////////////
| true |
93260369aa4a3a067b1fd37fb3fb136c876422ad | C++ | ovr/scratchpad | /EMallocAllocator.h | UTF-8 | 1,566 | 3.015625 | 3 | [] | no_license | #ifndef EMALLOCALLOCATOR_H_
#define EMALLOCALLOCATOR_H_
#include <cstddef>
#include <limits>
#include <new>
extern "C" {
#include <Zend/zend.h>
}
template<typename T>
class EMallocAllocator {
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
// convert an allocator<T> to allocator<U>
template<typename U>
struct rebind {
typedef EMallocAllocator<U> other;
};
EMallocAllocator(void)
{
}
~EMallocAllocator(void)
{
}
EMallocAllocator(const EMallocAllocator&)
{
}
template<typename U>
EMallocAllocator(const EMallocAllocator<U>&)
{
}
pointer address(reference r)
{
return &r;
}
const_pointer address(const_reference r)
{
return &r;
}
pointer allocate(size_type cnt, typename std::allocator<void>::const_pointer = 0)
{
pointer tmp = reinterpret_cast<pointer>(emalloc(cnt * sizeof(T)));
if (!tmp) {
throw std::bad_alloc();
}
return tmp;
}
void deallocate(pointer p, size_type)
{
efree(p);
}
size_type max_size(void) const
{
return std::numeric_limits<size_type>::max() / sizeof(T);
}
void construct(pointer p, const T& t)
{
new(reinterpret_cast<void*>(p)) T(t);
}
void destroy(pointer p)
{
p->~T();
}
bool operator==(const EMallocAllocator&) const
{
return true;
}
bool operator!=(const EMallocAllocator& a) const
{
return !operator==(a);
}
};
#endif /* EMALLOCALLOCATOR_H_ */
| true |
e2e96d77e2f5a4bd962d3b78e4f6c0a37aa63fb5 | C++ | gaurav497/DAA | /Insertion_sort.cpp | UTF-8 | 847 | 3.25 | 3 | [] | no_license | #include<iostream>
using namespace std;
void insertion_sort(int arr[],int n)
{
int i,j,key,shifts=0,comparisons=0;
for(i=1;i<n;i++)
{
j=i-1;
key=arr[i];
while(j>=0 && arr[j]>key)
{
arr[j+1]=arr[j];
shifts++;
comparisons++;
j--;
}
arr[j+1]=key;
shifts++;
}
for(i=0;i<n;i++)
cout<< arr[i] <<" ";
cout<<"Comparisons="<<comparisons<<endl;
cout<<"Shifts="<<shifts<<endl;
}
int main()
{
int t,n,i,j;
cin>>t;
for(i=0;i<t;i++)
{
cin>>n;
int arr[n];
for(j=0;j<n;j++)
{
cin>>arr[j];
}
insertion_sort(arr,n);
}
return 0;
} | true |
9516d4c6b001eb5bc45d84f4c99d7c6a599d635a | C++ | hansj66/micro-bot | /Firmware/microbit/microbit-dal/inc/types/ManagedType.h | UTF-8 | 6,659 | 2.796875 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | /*
The MIT License (MIT)
Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef MICROBIT_MANAGED_TYPE_H
#define MICROBIT_MANAGED_TYPE_H
#include "MicroBitConfig.h"
/**
* Class definition for a Generic Managed Type.
*
* Represents a reference counted object.
*
* @note When the destructor is called, delete is called on the object - implicitly calling the given objects destructor.
*/
template <class T>
class ManagedType
{
protected:
int *ref;
public:
T *object;
/**
* Constructor for the managed type, given a class space T.
*
* @param object the object that you would like to be ref counted - of class T
*
* @code
* T object = new T();
* ManagedType<T> mt(t);
* @endcode
*/
ManagedType(T* object);
/**
* Default constructor for the managed type, given a class space T.
*/
ManagedType();
/**
* Copy constructor for the managed type, given a class space T.
*
* @param t another managed type instance of class type T.
*
* @code
* T* object = new T();
* ManagedType<T> mt(t);
* ManagedType<T> mt1(mt);
* @endcode
*/
ManagedType(const ManagedType<T> &t);
/**
* Destructor for the managed type, given a class space T.
*/
~ManagedType();
/**
* Copy-assign member function for the managed type, given a class space.
*
* @code
* T* object = new T();
* ManagedType<T> mt(t);
* ManagedType<T> mt1 = mt;
* @endcode
*/
ManagedType<T>& operator = (const ManagedType<T>&i);
/**
* Returns the references to this ManagedType.
*
* @code
* T* object = new T();
* ManagedType<T> mt(t);
* ManagedType<T> mt1(mt);
*
* mt.getReferences // this will be 2!
* @endcode
*/
int getReferences();
/**
* De-reference operator overload. This makes modifying ref-counted POD
* easier.
*
* @code
* ManagedType<int> x = 0;
* *x = 1; // mutates the ref-counted integer
* @endcode
*/
T& operator*() {
return *object;
}
/**
* Method call operator overload. This forwards the call to the underlying
* object.
*
* @code
* ManagedType<T> x = new T();
* x->m(); // resolves to T::m
*/
T* operator->() {
if (object == NULL)
microbit_panic(MICROBIT_NULL_DEREFERENCE);
return object;
}
/**
* Shorthand for `x.operator->()`
*/
T* get() {
return object;
}
/**
* A simple inequality overload to compare two ManagedType instances.
*/
bool operator!=(const ManagedType<T>& x) {
return !(this == x);
}
/**
* A simple equality overload to compare two ManagedType instances.
*/
bool operator==(const ManagedType<T>& x) {
return this->object == x.object;
}
};
/**
* Constructor for the managed type, given a class space T.
*
* @param object the object that you would like to be ref counted - of class T
*
* @code
* T object = new T();
* ManagedType<T> mt(t);
* @endcode
*/
template<typename T>
ManagedType<T>::ManagedType(T* object)
{
this->object = object;
ref = (int *)malloc(sizeof(int));
*ref = 1;
}
/**
* Default constructor for the managed type, given a class space T.
*/
template<typename T>
ManagedType<T>::ManagedType()
{
this->object = NULL;
ref = (int *)malloc(sizeof(int));
*ref = 0;
}
/**
* Copy constructor for the managed type, given a class space T.
*
* @param t another managed type instance of class type T.
*
* @code
* T* object = new T();
* ManagedType<T> mt(t);
* ManagedType<T> mt1(mt);
* @endcode
*/
template<typename T>
ManagedType<T>::ManagedType(const ManagedType<T> &t)
{
this->object = t.object;
this->ref = t.ref;
(*ref)++;
}
/**
* Destructor for the managed type, given a class space T.
*/
template<typename T>
ManagedType<T>::~ManagedType()
{
// Special case - we were created using a default constructor, and never assigned a value.
if (*ref == 0)
{
// Simply destroy our reference counter and we're done.
free(ref);
}
// Normal case - we have a valid piece of data.
// Decrement our reference counter and free all allocated memory if we're deleting the last reference.
else if (--(*ref) == 0)
{
delete object;
free(ref);
}
}
/**
* Copy-assign member function for the managed type, given a class space.
*
* @code
* T* object = new T();
* ManagedType<T> mt(t);
* ManagedType<T> mt1 = mt;
* @endcode
*/
template<typename T>
ManagedType<T>& ManagedType<T>::operator = (const ManagedType<T>&t)
{
if (this == &t)
return *this;
// Special case - we were created using a default constructor, and never assigned a value.
if (*ref == 0)
{
// Simply destroy our reference counter, as we're about to adopt another.
free(ref);
}
else if (--(*ref) == 0)
{
delete object;
free(ref);
}
object = t.object;
ref = t.ref;
(*ref)++;
return *this;
}
/**
* Returns the references to this ManagedType.
*
* @code
* T* object = new T();
* ManagedType<T> mt(t);
* ManagedType<T> mt1(mt);
*
* mt.getReferences // this will be 2!
* @endcode
*/
template<typename T>
int ManagedType<T>::getReferences()
{
return (*ref);
}
#endif
| true |
3c2a3d575e4b44c2765ad101a7e7c3343981bf7f | C++ | comran/cs32 | /homework_3/maze.cpp | UTF-8 | 1,326 | 3.28125 | 3 | [] | no_license | bool pathExists(std::string maze[], int nRows, int nCols, int sr, int sc, int er,
int ec) {
if(sr == er && sc == ec) return true;
maze[sr][sc] = '%';
if (sr > 0 /* there is a row above */ &&
maze[sr - 1][sc] != 'X' /* can move north */ &&
maze[sr - 1][sc] != '%' /* have not already visited that spot */) {
if(pathExists(maze, nRows, nCols, sr - 1, sc, er, ec)) return true;
maze[sr - 1][sc] = '%';
}
if (sc < nCols - 1 /* there is a column to the right */ &&
maze[sr][sc + 1] != 'X' /* can move east */ &&
maze[sr][sc + 1] != '%' /* have not already visited that spot */) {
if(pathExists(maze, nRows, nCols, sr, sc + 1, er, ec)) return true;
maze[sr][sc + 1] = '%';
}
if (sr < nRows - 1 /* there is a row below */ &&
maze[sr + 1][sc] != 'X' /* can move south */ &&
maze[sr + 1][sc] != '%' /* have not already visited that spot */) {
if(pathExists(maze, nRows, nCols, sr + 1, sc, er, ec)) return true;
maze[sr + 1][sc] = '%';
}
if (sc > 0 /* there is a column to the left */ &&
maze[sr][sc - 1] != 'X' /* can move west */ &&
maze[sr][sc - 1] != '%' /* have not already visited that spot */) {
if(pathExists(maze, nRows, nCols, sr, sc - 1, er, ec)) return true;
maze[sr][sc - 1] = '%';
}
return false;
}
| true |
e3b8e2f4275e7a94308753c5d7be50405707be53 | C++ | ebender17/Galactic-Guardian- | /SceneGame.cpp | UTF-8 | 7,817 | 3.078125 | 3 | [] | no_license | #include "stdafx.h"
#include "SceneStateMachine.h"
#include "Protagonist.h"
#include "Bullet.h"
#include "SceneGame.h"
SceneGame::SceneGame(SceneStateMachine& sceneStateMachine)
: sceneStateMachine(sceneStateMachine), activateCount(0),currLevel(1), numLevels(3), playerState(ALIVE), secPlayerDeath(0.f), secEnemiesDead(0.f)
{
//create player
player = new Protagonist();
AddAsteriods();
}
void SceneGame::OnActivate()
{
//Want to reset game if scene has been activated before
if (activateCount > 0)
{
ResetGame();
}
activateCount++;
}
void SceneGame::OnDestroy()
{
player->OnDestroy();
delete player;
}
void SceneGame::SetSwitchToScene(unsigned int stateWon, unsigned int stateLost)
{
switchToStateWon = stateWon;
switchToStateLost = stateLost;
}
void SceneGame::AddAsteriods()
{
for (int i = 0; i < 6; i++)
{
enemies.push_back(std::make_unique<Enemy>("large asteriod", 40, 500));
enemies.push_back(std::make_unique<Enemy>("medium asteriod", 20, 200));
}
}
bool SceneGame::IsPointInsideRange(float x1, float y1, float x2, float y2)
{
//If distance between points is less than 50.f, points are deemed inside each other's range
return sqrtf((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) < 50.f;
}
void SceneGame::ResetGame()
{
player->SetSpritePosition(APP_INIT_WINDOW_WIDTH / 2.f, APP_INIT_WINDOW_HEIGHT / 2.f);
player->SetHealth(1000);
player->SetObjectHurt(2.f); //Set to 2.f bc before 1.f player has an explosion sprite set on top
player->SetCurrentSeconds(0.f); //Ensures Space key or A button press from previous scene does not trigger bullet fire, bullet fires after currSec > 2.0f
player->ClearBullets();
player->SetVelocity(0.f, 0.f);
enemies.clear();
//Know I just set position so should know position, but want as accurate as can be for placing enemies below
float xPlayer, yPlayer;
player->GetSpritePosition(xPlayer, yPlayer);
AddAsteriods();
playerState = ALIVE;
currLevel = 1;
secPlayerDeath = 0.f;
secEnemiesDead = 0.f;
}
void SceneGame::CalculatePlayerState(float enemPosX, float enemPoxY, std::unique_ptr<Enemy>& currEnem)
{
float px, py;
player->GetSpritePosition(px, py);
int health = player->GetHealth();
if (IsPointInsideRange(enemPosX, enemPoxY, px, py))
{
/*if (health <= 0)
{
playerState = DEAD;
return;
}*/
if (playerState == ALIVE)
{
health -= currEnem->GetDamage();
if (health <= 0)
{
health = 0;
playerState = DEAD;
player->SetHealth(health);
player->SetObjectHurt(0.f);
return;
}
playerState = HURT;
player->SetObjectHurt(0.f);
player->SetHealth(health);
}
}
}
void SceneGame::CreateLevelTwo()
{
//Reseting player status bc beginning of round
float xPlayer, yPlayer;
player->GetSpritePosition(xPlayer, yPlayer);
player->SetSpritePosition(APP_INIT_WINDOW_WIDTH / 2.f, APP_INIT_WINDOW_WIDTH / 2.f);
player->SetVelocity(0.f, 0.f);
player->SetSpriteAngle(0.f);
for (int i = 0; i < 3; i++)
{
enemies.push_back(std::make_unique<Enemy>("green beetle", 40, 200));
enemies.push_back(std::make_unique<Enemy>("blue robot", 60, 400));
enemies.push_back(std::make_unique<Enemy>("flying bug", 20, 300));
}
currLevel += 1;
player->SetHealth(1000);
}
void SceneGame::CreateLevelThree()
{
float xPlayer, yPlayer;
player->GetSpritePosition(xPlayer, yPlayer);
player->SetSpritePosition(APP_INIT_WINDOW_WIDTH / 2.f, APP_INIT_WINDOW_WIDTH / 2.f);
player->SetVelocity(0.f, 0.f);
player->SetSpriteAngle(0.f);
for (int i = 0; i < 2; i++)
{
enemies.push_back(std::make_unique<Enemy>("small enemy", 40, 100));
enemies.push_back(std::make_unique<Enemy>("medium enemy", 60, 100));
enemies.push_back(std::make_unique<Enemy>("large enemy", 80, 100));
}
currLevel += 1;
player->SetHealth(1000);
}
void SceneGame::Update(float deltaTime)
{
player->Update(deltaTime);
std::vector<std::unique_ptr<Bullet>>& bullets = player->GetBullets();
//Lost Game
if (playerState == DEAD)
{
secPlayerDeath += deltaTime;
if(secPlayerDeath > 1.f) sceneStateMachine.SwitchTo(switchToStateLost);
}
//2nd round of enemies, this time ships!
if (enemies.empty() && currLevel == numLevels - 2 )
{
secEnemiesDead += deltaTime;
if (secEnemiesDead > 4.f) {
secEnemiesDead = 0.f;
CreateLevelTwo();
}
}
//3rd round, smart enemies
if (enemies.empty() && currLevel == numLevels - 1)
{
secEnemiesDead += deltaTime;
if (secEnemiesDead > 3.f) {
secEnemiesDead = 0.f;
CreateLevelThree();
}
}
//Won game
if (enemies.empty() &&currLevel == numLevels) {
secEnemiesDead += deltaTime;
if(secEnemiesDead > 3.f) sceneStateMachine.SwitchTo(switchToStateWon);
}
if (player->GetObjectHurt() > 3.f) playerState = ALIVE;
//Update and draw enemies
for (auto& e : enemies)
{
e->Update(deltaTime);
//Grab enemies position
float ex, ey;
e->GetSpritePosition(ex, ey);
//Check for bullet and enemy collision
for (auto& b : bullets)
{
//Grab bullets position
float bx, by;
b->GetSpritePosition(bx, by);
if (IsPointInsideRange(bx, by, ex, ey))
{
if (e->GetObjectHurt() > 1.f)
{
int health = e->GetHealth();
health -= b->GetDamage();
e->SetHealth(health);
//sec since enemy was last hurt set to 0
e->SetObjectHurt(0.f);
}
//Force bullet offscreen to be collected by remove_if lambda in protagonist.cpp
b->SetSpritePosition(2000.f, 2000.f);
}
}
if (e->GetSmartEnemy()) e->EnemyFollow(player, playerState);
//Check for enemy collisons with player
CalculatePlayerState(ex, ey, e);
}
//Remove enemies that have gone off screen
//In enemy.cpp, enemies are forced off screen if health == 0
if (enemies.size() > 0)
{
//remove_if from c algorithm library
//Returns iterator
//Sorts vector that anything that fails criteria is at end of vector
auto i = remove_if(enemies.begin(), enemies.end(), [&](std::unique_ptr<Enemy>& enemy)
{
float x, y;
enemy->GetSpritePosition(x, y);
return (x < -10.f);
}
);
if (i != enemies.end())
//delete unique ptr will be called automatically once vector no longer owns it
enemies.erase(i);
}
}
void SceneGame::Draw()
{
//Health display
int health = player->GetHealth();
std::string playerHealth = "Player health: " + std::to_string(health);
const char* cPlayerHealth = playerHealth.c_str();
float r = 0.f, b = 0.f, g = 1.f;
if (health <= 500)
{
r = 0.5f;
g = 0.5f;
}
if (health <= 200)
{
r = 1.f;
g = 0.f;
}
App::Print( 50.f, APP_INIT_WINDOW_HEIGHT - 50.f, cPlayerHealth, r, g, b, GLUT_BITMAP_9_BY_15);
//Display text after level 1 is complete
if (enemies.empty() && currLevel == numLevels - 2 && secEnemiesDead < 4.f)
{
App::Print(APP_INIT_WINDOW_WIDTH / 2.5f, APP_INIT_WINDOW_HEIGHT / 1.5f, "Level 1: Complete", 0.2f, 0.5f, 0.75f, GLUT_BITMAP_9_BY_15);
App::Print(APP_INIT_WINDOW_WIDTH / 2.75f, APP_INIT_WINDOW_HEIGHT / 2.f, "Level 2: Alien Creatures", 0.2f, 0.5f, 0.75f, GLUT_BITMAP_9_BY_15);
}
//Display text after level 2 is complete
if (enemies.empty() && currLevel == numLevels - 1 && secEnemiesDead < 4.f)
{
App::Print(APP_INIT_WINDOW_WIDTH / 2.5f, APP_INIT_WINDOW_HEIGHT / 1.5f, "Level 2: Complete", 0.2f, 0.5f, 0.75f, GLUT_BITMAP_9_BY_15);
App::Print(APP_INIT_WINDOW_WIDTH / 2.75f, APP_INIT_WINDOW_HEIGHT / 2.f, "Level 3: Invading Enemy Ships", 0.2f, 0.5f, 0.75f, GLUT_BITMAP_9_BY_15);
}
//Display text after level 3 is complete
if (enemies.empty() && currLevel == numLevels && secEnemiesDead < 3.f && playerState != DEAD)
{
App::Print(APP_INIT_WINDOW_WIDTH / 2.5f, APP_INIT_WINDOW_HEIGHT / 1.5f, "Level 3: Complete", 0.2f, 0.5f, 0.75f, GLUT_BITMAP_9_BY_15);
}
//Drawing game objects
player->Draw();
for (auto& e : enemies)
{
e->Draw();
}
} | true |
b74f20342724fb372f338f61d541dcfb38ba1756 | C++ | krashton1/PixelArtGenerator | /src/PAG_CPP/PAG_CPP/AssetGenerator.cpp | UTF-8 | 14,609 | 2.65625 | 3 | [
"MIT"
] | permissive | #define _USE_MATH_DEFINES
#include "AssetGenerator.h"
#include <cmath>
#include <algorithm>
#include <deque>
namespace godot
{
AssetGenerator::AssetGenerator(Vector2 size /*= Vector2(1024,1024)*/, int numPixels /*= 64*/)
: mSize(size)
, mAssetSize(numPixels)
, mScreenSize(Vector2(1280, 720))
, mPixelSize(std::min(size.x, size.y) / numPixels)
{
setup();
}
AssetGenerator::~AssetGenerator()
{
}
void AssetGenerator::_register_methods()
{
register_method((char*)"_ready", &_ready);
register_method((char*)"_draw", &_draw);
}
void AssetGenerator::_init()
{
// Do nothing
}
void AssetGenerator::_ready()
{
// Do nothing
}
void AssetGenerator::_draw()
{
//drawPixelArray();
//int newX = -(mBandCurPos[i] * mPixelSize) + prevX;
//Rect2 rect = Rect2(newX - mPixelSize, (i == 0 ? 0 : mBandPos[i - 1]) - mPixelSize, (mBandImages[i][x]->get_width() * mPixelSize) + mPixelSize, mBandPos[i] - (i == 0 ? 0 : mBandPos[i - 1]) + mPixelSize);
mImageTexture->create_from_image(mImage, 0);
Rect2 rect = Rect2(0, 0, mSize.x, mSize.y);
draw_texture_rect(mImageTexture, rect, false);
}
void AssetGenerator::drawPixel(Vector2 pos, Color* color)
{
Rect2 rect = Rect2(pos.x, pos.y, mPixelSize, mPixelSize);
draw_rect(rect, *color);
}
void AssetGenerator::drawPixelArray()
{
for (int i = 0; i < mAssetSize; i++)
{
for (int j = 0; j < mAssetSize; j++)
{
if (mPixelArray[i][j] != nullptr)
{
drawPixel(Vector2(i*mPixelSize, j*mPixelSize), mPixelArray[i][j]);
}
}
}
}
void AssetGenerator::setPixel(Vector2 pos, Color* color, int flag /*= 0*/)
{
// flag == 0 : force pixel to be colored
// flag == 1 : only change pixel if it was previously colored
// flag == 2 : only change pixel if it was NOT previously colored
if (pos.x >= mAssetSize || pos.x < 0 || pos.y >= mAssetSize || pos.y < 0 || color == nullptr)
return;
mImage->lock();
if (flag == 0)
{
mPixelArray[(int)pos.x][(int)pos.y] = color;
mImage->set_pixel(int(pos.x), int(pos.y), *color);
}
else if (flag == 1)
{
if (mPixelArray[(int)pos.x][(int)pos.y] != nullptr && !compareColor(mPixelArray[(int)pos.x][(int)pos.y], mColorRamp[0]))
{
mPixelArray[(int)pos.x][(int)pos.y] = color;
mImage->set_pixel(int(pos.x), int(pos.y), *color);
}
}
else if (flag == 2)
{
if (mPixelArray[(int)pos.x][(int)pos.y] == nullptr)
{
mPixelArray[(int)pos.x][(int)pos.y] = color;
mImage->set_pixel(int(pos.x), int(pos.y), *color);
}
}
mImage->unlock();
}
void AssetGenerator::addLine(Vector2 origin, Vector2 dest, Color* color, int flag /*= 0*/)
{
// flag == 0 : force pixel to be colored
// flag == 1 : only change pixel if it was previously colored
// flag == 2 : only change pixel if it was NOT previously colored
Array linePoints = getLine(origin, dest);
for (int i = 0; i < linePoints.size(); i++)
{
setPixel(linePoints[i], color, flag);
}
}
void AssetGenerator::addCircle(Vector2 origin, float radius, int samples, Color* color)
{
Vector2 lastPos = origin;
Vector2 thisPos = origin;
for (int i = 0; i < samples + 1; i++)
{
thisPos = Vector2(
origin.x + radius * cos(i / (samples / 2.0f) * M_PI),
origin.y + radius * sin(i / (samples / 2.0f) * M_PI)
);
if (i != 0)
addLine(lastPos, thisPos, color);
lastPos = thisPos;
}
}
void AssetGenerator::addShape(std::vector<Vector2> points, Color* lineColor, Color* fillColor /*= nullptr*/)
{
Vector2 origPt = points[0];
for (int i = 0; i < points.size(); i++)
{
addLine(points[i], points[(i + 1) % points.size()], lineColor);
}
if (fillColor != nullptr)
{
Vector2 avgPt = Vector2(0, 0);
for (Vector2 pt : points)
avgPt += pt;
avgPt = avgPt / points.size();
avgPt = Vector2(round(avgPt.x), round(avgPt.y));
AssetGenerator::fillColor(avgPt, fillColor);
}
}
void AssetGenerator::fillColor(Vector2 origin, Color* destColor, Color* origColor /*= nullptr*/, Color* destColor2 /*= nullptr*/)
{
if (origColor == nullptr)
origColor = mPixelArray[(int)origin.x][(int)origin.y];
std::set<Vector2> likeValidNeighbours;
std::set<Vector2> toSearch;
toSearch.insert(origin);
while (toSearch.size() > 0)
{
findLikeNeighbours(*toSearch.begin(), likeValidNeighbours, toSearch, origColor);
}
for (std::set<Vector2>::iterator it = likeValidNeighbours.begin(); it != likeValidNeighbours.end(); it++)
{
Color* c = destColor;
if (destColor2 != nullptr)
if (rand() % 2 == 0)
c = destColor2;
setPixel(*it, c);
}
}
void AssetGenerator::sprayPixel(Vector2 origin, float size, float intensity, Color* color /*= nullptr*/, bool paintOver /*= false*/)
{
// Circle of radius size located at origin
// intensity 0 means no pixels are colored
// intensity of 1 means all pixels are colored
// If supplied color is null, just brighten the pixel by 1 on ramp
Vector2 start = origin - Vector2(size, size);
for (int x = start.x; x <= origin.x + size; x++)
{
for (int y = start.y; y <= origin.y + size; y++)
{
if (x < 0 || x >= mAssetSize || y < 0 || y >= mAssetSize)
continue;
float dist = std::sqrt(std::pow(x - origin.x, 2) + std::pow(y- origin.y, 2));
if (dist <= size)
{
float t = rand() / (float)RAND_MAX;
if (t < intensity)
{
if (color != nullptr)
{
setPixel(Vector2(x, y), color, (paintOver ? 1 : 0));
}
else
{
Color* curColor = mPixelArray[x][y];
Color* tempColor = mColorRamp[0];
int i = 0;
while (true)
{
if (compareColor(curColor, tempColor))
{
setPixel(Vector2(x, y), mColorRamp[std::min(i + 1, (int)mColorRamp.size() - 1)], (paintOver ? 1 : 0));
break;
}
i++;
if (i == mColorRamp.size())
break;
tempColor = mColorRamp[i];
}
}
}
}
}
}
}
void AssetGenerator::blurPixels()
{
Color* newPixelArray[64][64];
for (int i = 0; i < mAssetSize; i++)
{
for (int j = 0; j < mAssetSize; j++)
{
newPixelArray[i][j] = nullptr;
}
}
for (int x = 0; x < mAssetSize ; x++)
{
for (int y = 0; y < mAssetSize; y++)
{
int n = 0;
Vector3 avgColor = Vector3(0, 0, 0);
float alpha = 0.0;
if (mPixelArray[x][y] != nullptr)
{
avgColor = avgColor + Vector3(mPixelArray[x][y]->r, mPixelArray[x][y]->g, mPixelArray[x][y]->b);
n++;
alpha = 1.0;
}
if (x - 1 >= 0 && mPixelArray[x-1][y] != nullptr)
{
avgColor = avgColor + Vector3(mPixelArray[x - 1][y]->r, mPixelArray[x - 1][y]->g, mPixelArray[x - 1][y]->b);
n++;
}
if (x + 1 < mAssetSize && mPixelArray[x+1][y] != nullptr)
{
avgColor = avgColor + Vector3(mPixelArray[x + 1][y]->r, mPixelArray[x + 1][y]->g, mPixelArray[x + 1][y]->b);
n++;
}
if (y - 1 >= 0 && mPixelArray[x][y-1] != nullptr)
{
avgColor = avgColor + Vector3(mPixelArray[x][y - 1]->r, mPixelArray[x][y - 1]->g, mPixelArray[x][y - 1]->b);
n++;
}
if (y + 1 < mAssetSize && mPixelArray[x][y+1] != nullptr)
{
avgColor = avgColor + Vector3(mPixelArray[x][y + 1]->r, mPixelArray[x][y + 1]->g, mPixelArray[x][y + 1]->b);
n++;
}
if (n != 0 && alpha != 0.0)
{
avgColor = avgColor / n;
Color* newColor = new Color(avgColor.x, avgColor.y, avgColor.z, alpha);
newPixelArray[x][y] = newColor;
}
}
}
for (int x = 0; x < mAssetSize; x++)
{
for (int y = 0; y < mAssetSize; y++)
{
if (newPixelArray[x][y] != nullptr)
setPixel(Vector2(x, y), newPixelArray[x][y]);
}
}
}
void AssetGenerator::resetPixelArray()
{
mImage.instance();
mImage->create(mAssetSize, mAssetSize, false, Image::Format::FORMAT_RGBA8);
mImageTexture.instance();
for (int i = 0; i < mAssetSize; i++)
{
for (int j = 0; j < mAssetSize; j++)
{
mPixelArray[i][j] = nullptr;
}
}
}
void AssetGenerator::rotatePixelArray()
{
Color* newPixelArray[64][64];
for (int x = 0; x < mAssetSize; x++)
{
for (int y = 0; y < mAssetSize; y++)
newPixelArray[x][y] = mPixelArray[y][x];
}
for (int x = 0; x < mAssetSize; x++)
{
for (int y = 0; y < mAssetSize; y++)
mPixelArray[x][y] = newPixelArray[x][y];
}
}
Array AssetGenerator::getLine(Vector2 origin, Vector2 dest)
{
Array pointsOnLine;
float stepSize = 1.0f / mAssetSize; // todo fix this
Vector2 dir = dest - origin;
// If a line is more vertical than horizontal, it should not have more than 1 pixel in same y coord. aka jaggies
bool isVertical;
if (abs(dir.y) >= abs(dir.x))
isVertical = true;
else
isVertical = false;
Vector2 temp = origin;
// Holds prev XY coord, depending on if line is horizontal or vertical, which is then used to remove jaggies
int lastXY = -1;
int thisXY = -1;
// Coef of line, 0 is first pixel, 1 is last pixel
float coef = 0.0f;
while (coef <= 1.0f)
{
temp = Vector2(
round(origin.x * (1.0f - coef) + dest.x * coef),
round(origin.y * (1.0f - coef) + dest.y * coef)
);
coef += stepSize;
// Early out of we are outside the pixelArray
if (temp.x < 0.0f || temp.x >= mAssetSize || temp.y < 0.0f || temp.y >= mAssetSize) // todo fix this
continue;
if (isVertical)
thisXY = temp.y;
else
thisXY = temp.x;
if (thisXY != lastXY)
{
pointsOnLine.append(temp);
lastXY = thisXY;
}
}
return pointsOnLine;
}
bool AssetGenerator::compareColor(Color* color1, Color* color2)
{
if (color1 == nullptr || color2 == nullptr)
return false;
if (color1->r == color2->r && color1->g == color2->g && color1->b == color2->b && color1->a == color2->a)
return true;
return false;
}
void AssetGenerator::addSmile()
{
setPixel(Vector2(0, 1), mDebugColor);
setPixel(Vector2(0, 3), mDebugColor);
setPixel(Vector2(2, 0), mDebugColor);
setPixel(Vector2(2, 4), mDebugColor);
setPixel(Vector2(3, 1), mDebugColor);
setPixel(Vector2(3, 2), mDebugColor);
setPixel(Vector2(3, 3), mDebugColor);
rotatePixelArray();
}
void AssetGenerator::addMountain(int height, Color* color0, Color* color1, Color* color2)
{
resetPixelArray();
if (height < 2)
return;
Vector2 botLeft = Vector2(0, mAssetSize - 1);
Vector2 botRight = Vector2(mAssetSize - 1, mAssetSize - 1);
int centerX = rand() % 20 + (mAssetSize - 20) / 2;
int centerY = mAssetSize - height + (rand() % (height/2)) - height/4;
if (centerY >= mAssetSize - 1)
centerY = 1;
Vector2 peak = Vector2(centerX, centerY);
std::deque<Vector2> peaks;
//peaks.push_back(botLeft);
peaks.push_back(peak);
//peaks.push_back(botRight);
int smallerPeaks = (height - 10) / 2;
for (int i = 0; i < smallerPeaks; i++)
{
int smallPeakX = rand() % 50 + (mAssetSize - 50) / 2;
int variationY = (rand() % height /3) + ((peak.x - smallPeakX) > 0 ? (peak.x - smallPeakX) : (smallPeakX - peak.x));
int smallPeakY = mAssetSize - height + variationY;
if (smallPeakY >= mAssetSize - 1)
smallPeakY = mAssetSize - 2;
Vector2 smallPeak = Vector2(smallPeakX, smallPeakY);
//if (smallPeak.x < peak.x - 5)
//{
// peaks.push_front(smallPeak);
//}
//else if (smallPeak.x > peak.x + 5)
//{
peaks.push_back(smallPeak);
//}
}
peaks.push_front(botLeft);
peaks.push_back(botRight);
std::deque<Vector2> peaksSorted;
std::set<int> doneX;
for (int i = 0; i < peaks.size(); i++)
{
int nextX = mAssetSize;
int nextIndex = -1;
for (int j = 0; j < peaks.size(); j++)
{
if (peaks[j].x < nextX && doneX.find(peaks[j].x) == doneX.end())
{
nextX = peaks[j].x;
nextIndex = j;
}
}
if (nextIndex != -1)
{
doneX.insert(peaks[nextIndex].x);
peaksSorted.push_back(peaks[nextIndex]);
}
}
for (int i = 1; i < peaksSorted.size(); i++)
{
addLine(peaksSorted[i - 1], peaksSorted[i], color0);
}
fillColor(Vector2(centerX, mAssetSize - 1), color1, nullptr, color2);
if (mPixelArray[0][0] != nullptr)
{
addMountain(height, color0, color1, color2);
return;
}
//for (int i = 0; i < peaksSorted.size(); i++)
//{
// if (mPixelArray[int(peaksSorted[i].x - 1)][int(peaksSorted[i].y)] == nullptr && mPixelArray[int(peaksSorted[i].x + 1)][int(peaksSorted[i].y)] == nullptr)
// {
// setPixel(peaksSorted[i], new Color(0, 0, 0, 0));
// setPixel(peaksSorted[i] + Vector2(0, 1), color1);
// }
//}
if (mBlur)
blurPixels();
}
void AssetGenerator::addOutline(Color* outlineColor)
{
for (int i = 0; i < mAssetSize; i++)
{
for (int j = 0; j < mAssetSize; j++)
{
if (mPixelArray[i][j] == nullptr)
{
if (
i < mAssetSize - 1 && mPixelArray[i + 1][j] != nullptr && !compareColor(mPixelArray[i + 1][j], outlineColor) ||
i > 0 && mPixelArray[i - 1][j] != nullptr && !compareColor(mPixelArray[i - 1][j], outlineColor) ||
j < mAssetSize - 1 && mPixelArray[i][j + 1] != nullptr && !compareColor(mPixelArray[i][j + 1], outlineColor) ||
j > 0 && mPixelArray[i][j - 1] != nullptr && !compareColor(mPixelArray[i][j - 1], outlineColor)
)
{
setPixel(Vector2(i, j), outlineColor);
}
}
}
}
}
void AssetGenerator::findLikeNeighbours(Vector2 origin, std::set<Vector2> &validNeighbours, std::set<Vector2> &toSearch, Color* origColor /*= nullptr*/)
{
int x = origin.x;
int y = origin.y;
if (origColor == nullptr)
validNeighbours.insert(origin);
// up
if(y != 0)
if(mPixelArray[x][y - 1] == origColor)
if (validNeighbours.find(Vector2(x, y - 1)) == validNeighbours.end())
{
validNeighbours.insert(Vector2(x, y - 1));
toSearch.insert(Vector2(x, y - 1));
}
// down
if (y != mAssetSize - 1)
if (mPixelArray[x][y + 1] == origColor)
if (validNeighbours.find(Vector2(x, y + 1)) == validNeighbours.end())
{
validNeighbours.insert(Vector2(x, y + 1));
toSearch.insert(Vector2(x, y + 1));
}
// left
if (x != 0)
if (mPixelArray[x - 1][y] == origColor)
if (validNeighbours.find(Vector2(x - 1, y)) == validNeighbours.end())
{
validNeighbours.insert(Vector2(x - 1, y));
toSearch.insert(Vector2(x - 1, y));
}
// right
if (x != mAssetSize - 1)
if (mPixelArray[x + 1][y] == origColor)
if (validNeighbours.find(Vector2(x + 1, y)) == validNeighbours.end())
{
validNeighbours.insert(Vector2(x + 1, y));
toSearch.insert(Vector2(x + 1, y));
}
if (toSearch.find(origin) != toSearch.end())
toSearch.erase(origin);
}
void AssetGenerator::setup(Vector2 pos /*= Vector2(0, 0)*/, Vector2 size /*= Vector2(1024, 1024)*/, int numPixels /*= 64*/)
{
mPosition = pos;
mSize = size;
mAssetSize = numPixels;
mScreenSize = Vector2(1280, 720);
mPixelSize = std::min(mSize.x, mSize.y) / numPixels;
mDebugColor = new Color(0, 0, 0);
resetPixelArray();
//mImage.instance();
//mImage->create(mAssetSize, mAssetSize, false, Image::Format::FORMAT_RGBA8);
//mImageTexture.instance();
}
}
| true |
d26ea523e175d0a10740fbf0cb4228c33d50e2c0 | C++ | JSY1988/Boost_USE | /memory/intrusive_ptr/intrusive_ptr.cpp | UTF-8 | 692 | 3.234375 | 3 | [] | no_license | #include <boost/smart_ptr.hpp>
using namespace boost;
int main(){
typedef intrusive_ptr<counted_data> counted_ptr; //类型定义
counted_ptr p(new counted_data); //创建智能指针
assert(p); //bool转型
assert(p->m_count == 1); //operator->
counted_ptr p2(p); //指针拷贝构造
assert(p->m_count == 2); //引用计数增加
counted_ptr weak_p(p.get(), false); //弱引用
assert(weak_p->m_count() == 2); //引用计数不增加
p2.reset(); //复位指针
assert(!p2); //p2不支持有指针
assert(p->m_count == 1); //引用计数减少
//对象被正确析构
return 0;
}
| true |
b258eef75fdb7e60eb227b15b6fff66778bae579 | C++ | Swatigupta-droid/Data_Structures | /DSA PRACTICALS/MATRICES/sparselinked.cpp | UTF-8 | 1,574 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
template<class T>
class sparselinked;
template<class T>
class node
{
int i;
int j;
T value;
node<T>* next;
friend class sparselinked<T>;
node(const T& val, int i,int j)
{
this->i=i;
this->j=j;
value=val;
}
};
template<class T>
class sparselinked
{
private:
node<T>* head;
public:
sparselinked();
bool empty() const;
void store(const T&,int , int);
const T get(int ,int);
};
template<class T>
sparselinked<T>::sparselinked()
{
head=NULL;
}
template<class T>
bool sparselinked<T>::empty() const
{
return head==NULL;
}
template<class T>
void sparselinked<T>::store(const T& val,int i,int j)
{
node<T>* n=new node<T>(val,i,j);
n->value=val;
n->i=i;
n->j=j;
n->next=head;
head=n;
}
template<class T>
const T
sparselinked<T>::get(int i,int j)
{
node<T>* n=head;
while(n!=NULL)
{
if(n->i==i&&n->j==j)
return n->value;
n=n->next;
}
return 0;
}
int main()
{
sparselinked<int> s;
int val,i,j;
int ch,n;
cout<<"Enter the order of matrix"<<endl;
cin>>n;
int **a;
a=new int*[n];
for(int k=0;k<n;k++)
a[k]=new int[n];
cout<<"Enter the number of non-zero enteries"<<endl;
cin>>ch;
for(int k=0;k<ch;k++){
cout<<"Enter the non zero value"<<endl;
cin>>val;
cout<<"Enter the indexes"<<endl;
cin>>i>>j;
s.store(val,i,j);
}
cout<<"The matrix is :"<<endl;
for(i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
cout<<s.get(i,j)<<" ";
}
cout<<endl;
}
return 0;
}
| true |
0097a09ed6679aaaffd47ad596f9dcba37a9ce03 | C++ | Soplia/Codes | /JfF/CODE-JfF-B/Devcpp/devcpp1/枚举求素数.cpp | GB18030 | 982 | 3.15625 | 3 | [] | no_license | /*
Subject:ö
Compiler:Devcpp
Description:
Author:JiaruiXie
Id:4-6-2
Date_Begin:11/01/17 21:14
Date_End:11/01/17 21:58
*/
#include <stdio.h>
bool a[10001];
int main()
{
int n;
bool isOutput;
while(scanf("%d",&n)!=EOF)
{
//ûкʵʱ-1
isOutput=false;
for(int i=1;i<=n;i++)
a[i]=true;
a[1]=false;
//дfor(int i=2;i<=n&&a[i];i++)
//ǴģӦΪһ!a[i]ѭֹ
for(int i=2;i<=n;i++)
{
if(a[i])
for(int j=2;i*j<=n;j++)
a[i*j]=false;
}
for(int i=2;i<=n;i++)
//עⲻҪʹa[i]%10==1ж
if(a[i]&&i%10==1)
{
if(!isOutput)
{
isOutput=true;
printf("%d",i);
}
else
printf(" %d",i);
}
if(!isOutput)
printf("-1\n");
else
printf("\n");
}
return 0;
}
/*
100
5
11 31 41 61 71
-1
*/
| true |
30ee9a807d50f06ac95326532c28614587291a2c | C++ | cbuchxrn/argus_utils | /argus_utils/include/argus_utils/random/UniformEllipse.hpp | UTF-8 | 2,576 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"AFL-3.0",
"AFL-2.1"
] | permissive | #pragma once
#include <Eigen/Core>
#include <Eigen/Cholesky>
#include <boost/random/random_device.hpp>
#include <boost/random/random_number_generator.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include "argus_utils/utils/LinalgTypes.h"
namespace argus
{
// TODO Generalize multivariate normal and this into some adapter class?
/*! \brief Takes uniform samples from a unit sphere and converts them to an ellipse. */
template <typename Engine = boost::mt19937>
class UniformEllipse
{
public:
typedef boost::random::uniform_real_distribution<double> UniformReal;
UniformEllipse( unsigned int dim = 1 )
: _distribution( -1.0, 1.0 ),
_mean( VectorType::Zero( dim ) ),
_S( MatrixType::Identity( dim, dim ) )
{
Initialize();
boost::random::random_device rng;
_generator.seed( rng );
}
UniformEllipse( unsigned int dim, unsigned long seed )
: _distribution( -1.0, 1.0 ),
_mean( VectorType::Zero( dim ) ),
_S( MatrixType::Identity( dim, dim ) )
{
Initialize();
_generator.seed( seed );
}
UniformEllipse( const VectorType& u, const MatrixType& S )
: _distribution( -1.0, 1.0 ),
_mean( u ),
_S( S )
{
Initialize();
boost::random::random_device rng;
_generator.seed( rng );
}
UniformEllipse( const VectorType& u, const MatrixType& S, unsigned long seed )
: _distribution( -1.0, 1.0 ),
_mean( u ),
_S( S )
{
Initialize();
_generator.seed( seed );
}
void SetMean( const VectorType& u )
{
if( u.size() != _mean.size() )
{
throw std::runtime_error( "UniformEllipse: Mean dimension mismatch." );
}
_mean = u;
}
/*! \brief Set the ellipse covariance matrix. */
void SetShape( const MatrixType& S )
{
if( S.rows() != _L.rows() || S.cols() != _L.cols() )
{
throw std::runtime_error( "UniformEllipse: Shape dimension mismatch." );
}
_L = S.llt().matrixL();
}
VectorType Sample()
{
VectorType samples( _mean.size() );
for( unsigned int i = 0; i < _mean.size(); i++ )
{
samples( i ) = _distribution( _generator );
}
return _L * samples + _mean;
}
double EvaluateProbability( const VectorType& x ) const
{
// TODO
return 1.0;
}
private:
Engine _generator;
UniformReal _distribution;
VectorType _mean;
MatrixType _S;
MatrixType _L;
double _z;
void Initialize()
{
if( _mean.size() != _S.cols() || _mean.size() != _S.rows() )
{
throw std::runtime_error( "UniformEllipse: Dimension mismatch in mean and shape." );
}
_L = _S.llt().matrixL();
_z = _S.determinant();
}
};
} // end namespace argus
| true |
daae2b9e143048599bb33df19d8639917db61ea7 | C++ | iceblinux/iceBw_GTK | /buhg_g/rnn_d5w.h | UTF-8 | 3,511 | 2.78125 | 3 | [] | no_license | /*$Id: rnn_d5w.h,v 1.4 2014/02/28 05:21:01 sasa Exp $*/
/*20.01.2015 03.04.2008 Белых А.И. rnn_d5w.h
Реквизиты для расчёта "Розшифровки податкових зобов'язань та податкового кредиту в розрізі контрагентів"
*/
class rnn_d5
{
public:
/*полученные налоговые накладные - податковий кредит********************/
class iceb_u_spisok innn1;
class iceb_u_spisok innn_per1; /*индивидуальный налоговый номер|месяц.год*/
class iceb_u_double suma_bez_nds1;
class iceb_u_double suma_nds1;
class iceb_u_double suma_nds1_7;
class iceb_u_spisok naim_kontr1;
double os_sr1[2]; /*Сумма по основным сдерствам*/
/*Операції з придбання з податком на додану вартість, які не надають права формування
податкового кредиту - попадают строки из реестра в которых заполнена колонка 13 и 14*/
class iceb_u_spisok innn1d;
class iceb_u_spisok innn_per1d; /*индивидуальный налоговый номер|месяц.год*/
class iceb_u_double suma_bez_nds1d;
class iceb_u_double suma_nds1d;
class iceb_u_double suma_nds1d_7;
class iceb_u_spisok naim_kontr1d;
/*Операції з придбання без податку на додану вартість - Если не заполнены колонки 13 и 14 и 10 колонка равна 0. и код документа не ПНП и ПНЕ*/
class iceb_u_spisok innn1d1;
class iceb_u_spisok innn_per1d1; /*индивидуальный налоговый номер|месяц.год*/
class iceb_u_double suma_bez_nds1d1;
class iceb_u_double suma_nds1d1;
class iceb_u_spisok naim_kontr1d1;
/*выданные налоговые накладные - податкові зобов'язання***************/
class iceb_u_spisok innn2;
class iceb_u_spisok innn_per2;/*индивидуальный налоговый номер|месяц.год*/
class iceb_u_double suma_bez_nds2;
class iceb_u_double suma_nds2;
class iceb_u_double suma_nds2_7;
class iceb_u_spisok naim_kontr2;
double os_sr2[2]; /*Сумма по основным сдерствам*/
/*******в новом отчёте не используется**********************/
/*операції що оподатковуються за нульовою ставкою (рядок 2.2 декларації)*/
class iceb_u_spisok innn2d;
class iceb_u_spisok innn_per2d;/*индивидуальный налоговый номер|месяц.год*/
class iceb_u_double suma_bez_nds2d;
class iceb_u_double suma_nds2d;
class iceb_u_spisok naim_kontr2d;
/*Операції які звільнені від оподаткування (рядок 5 декларації)- записи из реестра у которых заполнена колонка 11*/
class iceb_u_spisok innn2d1;
class iceb_u_spisok innn_per2d1;/*индивидуальный налоговый номер|месяц.год*/
class iceb_u_double suma_bez_nds2d1;
class iceb_u_double suma_nds2d1;
class iceb_u_spisok naim_kontr2d1;
rnn_d5()
{
os_sr1[0]=os_sr1[1]=0.;
os_sr2[0]=os_sr2[1]=0.;
}
};
| true |
cf37d6c62a403ff4fd11e325392324e367581578 | C++ | kuronekonano/OJ_Problem | /广工 质方数.cpp | UTF-8 | 806 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
bool zhishu(int x)
{
for(int i=2;i<x;i++)
{
if(x%i==0)
{
return false;
}
}
return true;
}
int main()
{
int i,j=0,n;
long long a[100005];
for(i=1;i<=100005;i++)
{
if(zhishu(i))
{
a[j++]=i*i;
}
}
int k,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<j;i++)
{
if(a[i]>n)
{
k=i;
break;
}
}
if(a[k]-n>n-a[k-1])
{
printf("%d\n",a[k-1]);
}
else
{
printf("%d\n",a[k]);
}
printf("%d\n",a[k-1]);
}
return 0;
}
| true |
0799e9eb3639f2978de4bf368a73ef4ccbdaf04d | C++ | ICS3U-Programming-Layla-M/Assign-03-CPP | /monthDays.cpp | UTF-8 | 11,620 | 3.75 | 4 | [] | no_license | // Copyright (c) Year Layla Michel All rights reserved.
//
// Created by: Layla Michel
// Date: May 13, 2021
// This program asks the user to input a month and year
// and then displays how many days are in that month on that year
#include <iostream>
#include <string>
// declare global variables
std::string month, monthLowercase, yearAsString;
char c;
int yearAsInt, i = 0;
void outputMessage() {
// display how many days are in a month and if it's a leap year or not
if (monthLowercase == "jan" || monthLowercase == "january") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), January has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), January has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), January has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), January has 31 days.\n";
}
} else if (monthLowercase == "feb" || monthLowercase == "february") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), February has 29 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), February has 28 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), February has 29 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), February has 28 days.\n";
}
} else if (monthLowercase == "mar" || monthLowercase == "march") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), March has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
"(not a leap year), March has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
"(a leap year), March has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
"(not a leap year), March has 31 days.\n";
}
} else if (monthLowercase == "apr" || monthLowercase == "april") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
"(a leap year), April has 30 days.\n";
} else {
std::cout << "In " << yearAsInt <<
"(not a leap year), April has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
"(a leap year), April has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
"(not a leap year), April has 30 days.\n";
}
} else if (monthLowercase == "may") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), May has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
"(not a leap year), May has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), May has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), May has 31 days.\n";
}
} else if (monthLowercase == "jun" || monthLowercase == "june") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), June has 30 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), June has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), June has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), June has 30 days.\n";
}
} else if (monthLowercase == "jul" || monthLowercase == "july") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), July has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), July has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), July has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), July has 31 days.\n";
}
} else if (monthLowercase == "aug" || monthLowercase == "august") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), August has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), August has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), August has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), August has 31 days.\n";
}
} else if (monthLowercase == "sep" || monthLowercase == "sept"
|| monthLowercase == "september") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), September has 30 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), September has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), September has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), September has 30 days.\n";
}
} else if (monthLowercase == "oct" || monthLowercase == "october") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), October has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), October has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), October has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), October has 31 days.\n";
}
} else if (monthLowercase == "nov" || monthLowercase == "november") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), November has 30 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), November has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), November has 30 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), November has 30 days.\n";
}
} else if (monthLowercase == "dec" || monthLowercase == "december") {
if (yearAsInt % 4 == 0) {
if (yearAsInt % 100 == 0) {
if (yearAsInt % 400 == 0) {
std::cout << "In " << yearAsInt <<
" (a leap year), December has 31 days.\n";
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), December has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (a leap year), December has 31 days.\n";
}
} else {
std::cout << "In " << yearAsInt <<
" (not a leap year), December has 31 days.\n";
}
}
}
void yearInput() {
// ask the user to input a year
std::cout << "Enter a year: ";
std::cin >> yearAsString;
try {
yearAsInt = std::stoi(yearAsString);
// check if year is a negative number
if (yearAsInt < 0) {
std::cout << "Please enter a valid year.\n";
yearInput();
} else {
std::cout << "\n";
outputMessage();
}
} // check if it's not an integer
catch (std::invalid_argument) {
// error message
std::cout << "Please enter a valid year.\n";
yearInput();
}
}
int main() {
// ask the user to input a month
std::cout << "Enter a month: ";
std::cin >> month;
i = 0;
monthLowercase = "";
while (month[i]) {
c = month[i];
monthLowercase += tolower(c);
i++;
}
if (monthLowercase == "jan" || monthLowercase == "january" ||
monthLowercase == "feb" || monthLowercase == "february" ||
monthLowercase == "mar" || monthLowercase == "march" ||
monthLowercase == "apr" || monthLowercase == "april" ||
monthLowercase == "may" ||
monthLowercase == "jun" || monthLowercase == "june" ||
monthLowercase == "jul" || monthLowercase == "july" ||
monthLowercase == "aug" || monthLowercase == "august" ||
monthLowercase == "sep" || monthLowercase == "sept" ||
monthLowercase == "september" ||
monthLowercase == "oct" || monthLowercase == "october" ||
monthLowercase == "nov" || monthLowercase == "november" ||
monthLowercase == "dec" || monthLowercase == "december") {
yearInput();
} else {
std::cout << "Please enter a valid month.\n";
main();
}
}
| true |
c7336c042865585c0199fde4f0a5febe7935fbd0 | C++ | qasimraheem/cpp11 | /2.Classes and Objects/14.std.move Function /main.cpp | UTF-8 | 438 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include "Integer.h"
using namespace std;
Integer add(const Integer &a, const Integer &b){
Integer temp;
temp.setvalue(a.getvalue()+b.getvalue());
return temp;
}
int main() {
Integer x(1);
std::cout<<x.getvalue()<<std::endl;
Integer y(std::move(x));//std move
std::cout<<y.getvalue()<<endl;
// x.setvalue(add(x,y).getvalue());
// std::cout<<x.getvalue()<<std::endl;
return 0;
} | true |
2cb4f62a43ec902eda067dfb4956b3de63ffda0f | C++ | Muzer/tmp-talk | /examples/ast/main.cpp | UTF-8 | 298 | 3.109375 | 3 | [] | no_license | #include "vectoradd.h"
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a;
std::vector<int> b;
a.push_back(1);
a.push_back(2);
a.push_back(3);
b.push_back(4);
b.push_back(5);
b.push_back(6);
std::cout << ((a + a) + b)[1] << " (should be 9)" << std::endl;
}
| true |
9766bd4b72b9d5a05105852599964fd4626853dd | C++ | Song1996/Leetcode | /p222_Count_Complete_Tree_Nodes/p222.cpp | UTF-8 | 1,276 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <memory>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <assert.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==NULL) return 0;
TreeNode* p;
int hll = 1; p = root->left; while(p!=NULL) {hll++; p = p->left;}
int hrr = 1; p = root->right; while(p!=NULL) {hrr++; p = p->right;}
int hrl; int hlr; int ans = 0;
while(root!=NULL) {
if(hll==hrr) {
ans += (1<<hll) - 1;
break;
}
hrl = 1; p = root->right; while(p!=NULL) {hrl++; p = p->left;}
if(hrl==hrr) {
ans += (1<<(hrr-1));
root = root->left;
hll --;
hrr = 0; p = root; while(p!=NULL) {hrr++; p = p->right;};
} else {
ans += (1<<(hll-1));
root = root->right;
hll = hrl - 1; hrr --;
}
}
return ans;
}
};
int main () {
return 0;
} | true |
5887239dfe3fa3aa75c871ab62cb7ca15aacd458 | C++ | arkud/C-plus-plus-modern-development-basics | /White belt/3 week/First&second names-1/main.cpp | UTF-8 | 5,506 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
struct Name {
std::string first_name;
std::string last_name;
};
class Person {
private:
std::map<int, Name> pf_year_to_name;
std::vector<int> pf_years;
std::map<int, std::pair<bool, bool>> pf_is_name_set;
int pf_birth_year;
public:
Person(const std::string &arg_first_name, const std::string &arg_last_name, const int &arg_birth_year) {
pf_year_to_name[arg_birth_year].first_name = arg_first_name;
pf_year_to_name[arg_birth_year].last_name = arg_last_name;
pf_years.push_back(arg_birth_year);
pf_birth_year = arg_birth_year;
pf_is_name_set[arg_birth_year].first = true;
pf_is_name_set[arg_birth_year].second = true;
}
void ChangeFirstName(int year, const std::string &first_name) {
if (year < pf_birth_year)
return;
UpdateYear(year);
pf_year_to_name[year].first_name = first_name;
pf_is_name_set[year].first = true;
UpdateData();
}
void ChangeLastName(int year, const std::string &last_name) {
UpdateYear(year);
pf_year_to_name[year].last_name = last_name;
pf_is_name_set[year].second = true;
UpdateData();
}
std::string GetFullName(int year) const{
if (year < pf_birth_year)
return "No person";
if (pf_years.empty() || year < pf_years.front())
return "Incognito";
if (year >= pf_years.back())
year = pf_years.back();
if (pf_year_to_name.count(year) == 0) {
for (int i = 0; i < pf_years.size(); i++) {
if (pf_years[i] <= year && pf_years[i + 1] > year)
year = pf_years[i];
}
}
if (pf_year_to_name.at(year).first_name.empty())
return pf_year_to_name.at(year).last_name + " with unknown first name";
else if (pf_year_to_name.at(year).last_name.empty())
return pf_year_to_name.at(year).first_name + " with unknown last name";
else
return pf_year_to_name.at(year).first_name + " " + pf_year_to_name.at(year).last_name;
}
std::string GetFullNameWithHistory(int year) const{
if (year < pf_birth_year)
return "No person";
if (pf_years.empty() || year <= pf_years.front())
return GetFullName(year);
if (year >= pf_years.back()) {
year = pf_years.back();
}
if (pf_year_to_name.count(year) == 0) {
for (int i = 0; i < pf_years.size(); i++) {
if (pf_years[i] <= year && pf_years[i + 1] > year)
year = pf_years[i];
}
}
std::string first_name = pf_year_to_name.at(year).first_name + " (";
std::string last_name = pf_year_to_name.at(year).last_name + " (";
std::string prev_first_name = pf_year_to_name.at(year).first_name;
std::string prev_last_name = pf_year_to_name.at(year).last_name;
for (int i = pf_years.size() - 1; i >= 0; i--) {
if (pf_years[i] < year) {
if (pf_is_name_set.at(pf_years[i]).first && prev_first_name != pf_year_to_name.at(pf_years[i]).first_name) {
first_name += pf_year_to_name.at(pf_years[i]).first_name + ", ";
prev_first_name = pf_year_to_name.at(pf_years[i]).first_name;
}
if (pf_is_name_set.at(pf_years[i]).second && prev_last_name != pf_year_to_name.at(pf_years[i]).last_name) {
last_name += pf_year_to_name.at(pf_years[i]).last_name + ", ";
prev_last_name = pf_year_to_name.at(pf_years[i]).last_name;
}
}
}
first_name.erase(first_name.end() - 2, first_name.end());
last_name.erase(last_name.end() - 2, last_name.end());
if (first_name.size() > pf_year_to_name.at(year).first_name.size())
first_name += ")";
if (last_name.size() > pf_year_to_name.at(year).last_name.size())
last_name += ")";
if (first_name.empty())
return last_name + " with unknown first name";
else if (last_name.empty())
return first_name + " with unknown last name";
else
return first_name + " " + last_name;
}
private:
void UpdateYear(int year) {
if (pf_year_to_name.count(year) == 0) {
pf_years.push_back(year);
std::sort(pf_years.begin(), pf_years.end());
}
}
void UpdateData() {
int i = 0;
for (const auto&[item, second] : pf_is_name_set) {
if (i == 0) {
i++;
continue;
}
if (!pf_is_name_set[item].first)
pf_year_to_name[pf_years[i]].first_name = pf_year_to_name[pf_years[i - 1]].first_name;
if (!pf_is_name_set[item].second)
pf_year_to_name[pf_years[i]].last_name = pf_year_to_name[pf_years[i - 1]].last_name;
i++;
}
}
};
int main() {
Person person("Polina", "Sergeeva", 1960);
for (int year : {1959, 1960}) {
std::cout << person.GetFullNameWithHistory(year) << std::endl;
}
person.ChangeFirstName(1965, "Appolinaria");
person.ChangeLastName(1967, "Ivanova");
for (int year : {1965, 1967}) {
std::cout << person.GetFullNameWithHistory(year) << std::endl;
}
return 0;
}
| true |
8ffc7c10b0ab624feef4c0c93e2191f8cb149a61 | C++ | 210183/CP | /Contest & Online Judge/Kattis/Problems/ecocover.cpp | UTF-8 | 2,782 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Dinic {
static const int N = 10005;
struct Edge {
int from;
int to;
int flow;
};
vector<Edge> elist;
vector<int> adj[N];
int saiz;
int ptr[N];
int dist[N];
int source,sink;
int num;
Dinic(int _s = 0,int _t = 0,int _num = 0) {
source = _s;
sink = _t;
num = _num;
reset();
}
void reset() {
for(int i = 0 ; i <= num ; i++)
adj[i].clear();
elist.clear();
saiz = 0;
}
void add_edge(int from,int to,int flow) {
adj[from].push_back(saiz++);
adj[to].push_back(saiz++);
elist.push_back((Edge){from,to,flow});
elist.push_back((Edge){to,from,flow});
// printf("add edge %d -> %d flow %d\n", from, to, flow);
}
bool BFS() {
for(int i = 0 ; i <= num ; i++)
dist[i] = -1;
queue<int> q;
q.push(source);
dist[source] = 0;
while(!q.empty() && dist[sink] == -1) {
int now = q.front();
q.pop();
for(int idx : adj[now]) {
int to = elist[idx].to;
int flow = elist[idx].flow;
if(dist[to] == -1 && flow > 0) {
dist[to] = dist[now] + 1;
q.push(to);
}
}
}
return dist[sink] != -1;
}
int augment(int now,int f) {
if(now == sink)
return f;
for(int &i = ptr[now] ; i < adj[now].size() ; i++) {
int idx = adj[now][i];
int to = elist[idx].to;
int flow = elist[idx].flow;
if(dist[to] == dist[now] + 1 && flow > 0) {
int res = augment(to,min(f,flow));
if(res > 0) {
elist[idx].flow -= res;
elist[idx ^ 1].flow += res;
return res;
}
}
}
return 0;
}
int maxFlow() {
int mf = 0;
while(BFS()) {
for(int i = 0 ; i <= num ; i++)
ptr[i] = 0;
int add = augment(source,(int)1e9);
while(add > 0) {
mf += add;
add = augment(source,(int)1e9);
}
}
return mf;
}
};
const int N = 45;
int dr[4] = {-1, 1, 0, 0};
int dc[4] = {0, 0, -1, 1};
int arr[N][N];
int n, m, k;
Dinic network;
int getID(int r, int c) {
return r * m + c;
}
void read() {
cin >> n >> m >> k;
for (int i = 0 ; i < n ; i++)
for(int j = 0 ; j < m ; j++)
cin >> arr[i][j];
}
void prepare() {
int source = getID(n-1,m-1)+1;
int sink = source+1;
network = Dinic(source, sink, sink);
for (int i = 0 ; i < n ; i++)
for(int j = 0 ; j < m ; j++) {
if ((i + j) % 2 == 0) {
network.add_edge(source, getID(i, j), arr[i][j]);
for (int it = 0 ; it < 4 ; it++) {
int ni = i + dr[it];
int nj = j + dc[it];
if (ni >= 0 && nj >= 0 && ni < n && nj < m) {
network.add_edge(getID(i, j), getID(ni, nj), k);
}
}
} else {
network.add_edge(getID(i, j), sink, arr[i][j]);
}
}
}
int main() {
read();
prepare();
printf("%d\n", network.maxFlow());
return 0;
} | true |
f9e75ff1d843a0db2f9fab7624d8f3f55e53ac09 | C++ | choi1019/utility | /parser/src/Lex.h | UTF-8 | 5,219 | 2.9375 | 3 | [] | no_license | /*
* Lex.h
*
* Created on: 2017. 3. 30.
* Author: choi.techwin
*/
#ifndef LEX_H_
#define LEX_H_ "LEX_H_"
#include "Exception.h"
#include <string>
#include <fstream>
using namespace std;
#define BLANKS " \t\n\r"
#define SPACE ' '
#define TAB '\t'
#define NEWLINE '\n'
#define BEGIN '{'
#define END '}'
#define INDEXBEGIN '['
#define INDEXEND ']'
#define PERIOD '.'
#define ZERO '0'
#define NINE '9'
#define PATHSEPARATOR "/"
#define EXTENSION ".txt"
class Lex {
private:
ifstream fin;
ofstream fout;
char lookahead;
string tabs;
bool isBlank(char c) {
string token;
token.append(BLANKS);
if (token.find(c) != string::npos) return true;
return false;
}
bool isBegin(char c) {
if (c == BEGIN) return true;
return false;
}
bool isEnd(char c) {
if (c == END) return true;
return false;
}
bool isIndexBegin(char c) {
if (c == INDEXBEGIN) return true;
return false;
}
bool isIndexEnd(char c) {
if (c == INDEXEND) return true;
return false;
}
bool isDelimeter(char c) {
if (this->isBlank(c)) return true;
if (this->isBegin(c)) return true;
if (this->isEnd(c)) return true;
if (this->isIndexBegin(c)) return true;
if (this->isIndexEnd(c)) return true;
return false;
}
bool isDigit(char c) {
if (c >= ZERO && c <= NINE) return true;
return false;
}
bool isPeriod(char c) {
if (c == PERIOD) return true;
return false;
}
void readBlanks() {
while(this->isBlank(this->lookahead) && !fin.eof()) {
fin.get(this->lookahead);
}
}
string readDigits() {
string token;
while (this->isDigit(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
string readPeriod() {
string token;
if (this->isPeriod(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
string readChars() {
string token;
while(!this->isDelimeter(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
string readBeginToken() {
string token;
if (this->isBegin(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
string readEndToken() {
string token;
if (this->isEnd(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
string readIndexBeginToken() {
string token;
if (this->isIndexBegin(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
string readIndexEndToken() {
string token;
if (this->isIndexEnd(this->lookahead) && !fin.eof()) {
token.append(1, this->lookahead);
fin.get(this->lookahead);
}
return token;
}
void tabIndentation() {
this->tabs.push_back(TAB);
}
void untabIndentation() {
this->tabs.erase(0, 1);
}
string getFullName(string path, string objectName) {
string fullName;
fullName.append(path);
fullName.append(PATHSEPARATOR);
fullName.append(objectName);
fullName.append(EXTENSION);
return fullName;
}
public:
Lex(): lookahead(BLANKS[0]) {}
virtual ~Lex() {}
void openIn(string path, string fileName) throw() {
string fullName = this->getFullName(path, fileName);
this->fin.open(fullName.c_str());
if (!this->fin.is_open())
throw Exception(LEX_H_, "openIn", fullName);
}
bool eof() { return fin.eof(); }
void closeIn() {
this->fin.close();
}
string readBegin() {
string token;
this->readBlanks();
token = this->readBeginToken();
return token;
}
string readEnd() {
string token;
this->readBlanks();
token = this->readEndToken();
return token;
}
string readIndexBegin() {
string token;
this->readBlanks();
token = this->readIndexBeginToken();
return token;
}
string readIndexEnd() {
string token;
this->readBlanks();
token = this->readIndexEndToken();
return token;
}
string readInt() {
string token;
this->readBlanks();
token = this->readDigits();
return token;
}
string readFloat() {
string token;
this->readBlanks();
token.append(this->readDigits());
token.append(this->readPeriod());
token.append(this->readDigits());
return token;
}
string readString() {
string token;
this->readBlanks();
token = this->readChars();
return token;
}
void openOut(string path, string fileName) throw() {
string fullName = this->getFullName(path, fileName);
this->fout.open(fullName.c_str());
if (!this->fout.is_open())
throw Exception(LEX_H_, "openOut", fullName);
this->tabs.clear();
}
void closeOut() {
this->fout.close();
}
void writeBegin() {
fout << BEGIN << NEWLINE;
tabIndentation();
}
void writeEnd() {
untabIndentation();
fout << this->tabs << END << NEWLINE;
}
void writeIndexBegin() {
fout << INDEXBEGIN;
}
void writeIndexEnd() {
fout << INDEXEND;
}
void writeKey(string token) {
fout << this->tabs << token;
}
void writeValue(string token) {
fout << SPACE << token << NEWLINE;
}
void writeSpace() {
fout << SPACE;
}
void writeTab() {
fout << this->tabs;
}
void writeEndl() {
fout << NEWLINE;
}
};
#endif /* LEX_H_ */
| true |
88fb05f8e44171902a7c8802c9fdec799c9749a3 | C++ | michelleferd/CS112-1 | /lab03/Vec.cpp | UTF-8 | 2,308 | 3.265625 | 3 | [] | no_license | /* Vec.cpp defines the methods for Vec, a simple vector class.
* Student Name:
* Date:
* Begun by: Joel C. Adams, for CS 112 at Calvin University.
*/
#include "Vec.h"
#include <stdexcept>
using namespace std;
Vec::Vec() {
mySize = 0;
myArray = NULL;
}
Vec::Vec(unsigned size) {
mySize = size;
(size > 0)? myArray = new Item[size]():
myArray = NULL;
}
Vec::Vec(const Vec& original) {
mySize = original.mySize;
if ( original.mySize > 0 ) {
myArray = new Item[mySize]();
for ( unsigned i = 0; i < mySize; i++) {
myArray[i] = original.myArray[i];
}
} else {
myArray = NULL;
}
}
Vec::~Vec() {
delete [] myArray;
myArray = NULL;
mySize = 0;
}
Vec& Vec::operator=(const Vec& original) {
if ( mySize != original.mySize ) {
if ( mySize > 0) {
delete [] myArray;
mySize = 0;
myArray = NULL;
}
if ( original.mySize > 0 ) {
myArray = new Item[original.mySize]();
}
mySize = original.mySize;
}
for ( unsigned i = 0; i < mySize; i++) {
myArray[i] = original.myArray[i];
}
return *this;
}
unsigned Vec::getSize() const {
return mySize;
}
void Vec::setItem(unsigned index, const Item& it) {
if ( mySize > index ) {
myArray[index] = it;
} else {
throw range_error("Invalid Index.");
}
}
Item Vec::getItem(unsigned index) const {
if ( mySize > index ) {
return myArray[index];
} else {
throw range_error("Invalid Index.");
}
}
void Vec::setSize(unsigned newSize) {
if (mySize != newSize) {
if ( newSize == 0 ) {
delete [] myArray;
mySize = 0;
myArray = NULL;
} else {
Item * newArray;
newArray = new Item[newSize]();
unsigned breakout = (mySize < newSize)? mySize : newSize;
for ( unsigned i = 0; i < breakout; i++) {
newArray[i] = myArray[i];
}
mySize = newSize;
delete [] myArray;
myArray = newArray;
}
}
}
bool Vec::operator==(const Vec& v2) const {
if ( mySize == v2.mySize ) {
for ( unsigned i = 0; i < mySize; i++ ) {
if ( myArray[i] != v2.myArray[i] ) {
return false;
}
}
return true;
}
return false;
}
void Vec::writeTo(ostream& out) const {
for ( unsigned i = 0; i < mySize; i++) {
out << myArray[i] << endl;
}
}
void Vec::readFrom(istream& in) {
if ( mySize > 0 ) {
for ( unsigned i = 0; i < mySize; i++) {
in >> myArray[i];
}
} else {
myArray = NULL;
}
}
| true |
f7444e4ed9367ce3d2760ad73939792de758a0b0 | C++ | rickyharis39/nolf2 | /Game/ClientShellDLL/ClientShellShared/VarTrack.h | UTF-8 | 2,466 | 2.5625 | 3 | [] | no_license |
// Console variable tracker.. makes it easy to get and set the value of
// console variables.
#ifndef __VarTrack_H__
#define __VarTrack_H__
#include <stdio.h>
#include "iltclient.h"
#include "ILTStream.h"
class VarTrack
{
public:
VarTrack()
{
m_hVar = LTNULL;
m_pClientDE = LTNULL;
m_pVarName = NULL;
}
inline LTBOOL Init(ILTClient *pClientDE, char const* pVarName, char const* pStartVal, float fStartVal)
{
char tempStr[128], tempStr2[256];
m_pVarName = pVarName;
if(!pStartVal)
{
LTSNPrintF(tempStr, sizeof(tempStr), "%5f", fStartVal);
pStartVal = tempStr;
}
m_hVar = pClientDE->GetConsoleVar(( char* )pVarName);
if(!m_hVar)
{
LTSNPrintF(tempStr2, sizeof(tempStr2), "\"%s\" \"%s\"", pVarName, pStartVal);
pClientDE->RunConsoleString(tempStr2);
m_hVar = pClientDE->GetConsoleVar(( char* )pVarName);
if(!m_hVar)
{
return LTFALSE;
}
}
m_pClientDE = pClientDE;
return LTTRUE;
}
inline LTBOOL IsInitted()
{
return !!m_pClientDE;
}
inline float GetFloat(float defVal=0.0f)
{
if(m_pClientDE && m_hVar)
return m_pClientDE->GetVarValueFloat(m_hVar);
else
return defVal;
}
inline char const* GetStr(char const* pDefault="")
{
const char *pRet;
if(m_pClientDE && m_hVar)
{
if(pRet = m_pClientDE->GetVarValueString(m_hVar))
return pRet;
}
return pDefault;
}
inline void SetFloat(float val)
{
char str[256];
if(!m_pClientDE || !m_pVarName)
return;
LTSNPrintF(str, sizeof(str), "%s %f", m_pVarName, val);
m_pClientDE->RunConsoleString(str);
}
inline void SetStr(char const* szVal)
{
char str[256];
if(!m_pClientDE || !m_pVarName)
return;
LTSNPrintF(str, sizeof(str), "+%s \"%s\"", m_pVarName, szVal);
m_pClientDE->RunConsoleString(str);
}
inline void WriteFloat(float val)
{
char str[256];
if(!m_pClientDE || !m_pVarName)
return;
LTSNPrintF(str, sizeof(str), "+%s %f", m_pVarName, val);
m_pClientDE->RunConsoleString(str);
}
inline void Load(ILTStream *pStream)
{
float val;
(*pStream) >> val;
SetFloat(val);
}
inline void Save(ILTStream *pStream)
{
float val = GetFloat();
(*pStream) << val;
}
protected:
HCONSOLEVAR m_hVar;
ILTClient *m_pClientDE;
char const *m_pVarName;
};
#endif // __VarTrack_H__
| true |
8bc4d9f56b6e8ad35169c3d34e1c082f80a8b994 | C++ | Aminul1811/Engineers-Management-System | /PROJECT 1.cpp | UTF-8 | 20,810 | 3.109375 | 3 | [] | no_license | /**********header files**********/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/************structure***********/
struct engineer_db{
char engineer_name[100];
char engineer_id[100];
int engineer_age;
char engineer_gender[100];
char engineer_hometown[100];
char engineer_address[100];
char engineer_category[100];
int engineer_level;
float engineer_salary;
char engineer_blood[100];
char engineer_contact[100];
char engineer_email[100];
char engineer_maritalstatus[100];
};
/*************main function**************/
int main()
{
char str1[100],str2[100];
puts("User:");
gets(str1);
puts("Password:");
gets(str2);
if((strcmp(str1,"Project")==0)&&(strcmp(str2,"224466")==0))
{
/*************task 1*************/
//loading the file in the structure
engineer_db s[50]; //number of engineer is 50
FILE *fp;
fp=fopen("engineer_db.txt","r");
/**************number of student count*************/
int counter=0;
char str[200];
while(fgets(str,200,fp)!=NULL)
{
counter++;
}
printf("number of student is = %d\n",counter);
rewind(fp);
char newline;
for(int i=0;i<counter;i++)
{
fscanf(fp,"%[^:]:%[^:]:%d:%[^:]:%[^:]:%[^:]:%[^:]:%d:%f:%[^:]:%[^:]:%[^:]:%s",s[i].engineer_name,s[i].engineer_id,&s[i].engineer_age,s[i].engineer_gender,s[i].engineer_hometown,s[i].engineer_address,s[i].engineer_category,&s[i].engineer_level,&s[i].engineer_salary,s[i].engineer_blood,s[i].engineer_contact,s[i].engineer_email,s[i].engineer_maritalstatus);
}
/*************testing*************/
for(int i=0;i<counter;i++)
{
puts("Name:");
puts(s[i].engineer_name);
puts("ID:");
puts(s[i].engineer_id);
puts("Age:");
printf("%d\n",s[i].engineer_age);
puts("Gender:");
puts(s[i].engineer_gender);
puts("Hometown:");
puts(s[i].engineer_hometown);
puts("Address:");
puts(s[i].engineer_address);
puts("Category:");
puts(s[i].engineer_category);
puts("Level:");
printf("%d\n",s[i].engineer_level);
puts("Salary:");
printf("%f\n",s[i].engineer_salary);
puts("Blood Group:");
puts(s[i].engineer_blood);
puts("Contact:");
puts(s[i].engineer_contact);
puts("Email:");
puts(s[i].engineer_email);
puts("Marital Status:");
printf("%s\n",s[i].engineer_maritalstatus);
}
/*int n;
while(1)
{
printf("Press 1 to see the number of male engineers in the company\n");
printf("Press 2 to see the engineer name and id whose age between 25-35\n");
printf("Press 3 to see the number of CSE engineers\n");
printf("Press 4 to see the name and contact of engineers whose level are not below 3\n");
printf("Press 5 to see the engineer name and address whose blood group is AB-\n");
printf("Press 6 to see the youngest engineer name and blood group\n");
printf("Press 7 to see the engineer name and hometown of lowest salary\n");
printf("Press 8 to see the oldest EEE engineer name and id\n");
printf("press 9 to see the male engineer name and id of highest salary\n");
printf("Press 10 to see the unmarried engineer name and age whose blood group B+\n");
printf("Press 11 to see the number of female engineers\n");
printf("Press 12 to see the engineer name and id whose address length between 8-12\n");
printf("Press 13 to see the number of engineers whose home town is comilla\n");
printf("Press 14 to see the name and email of engineer whose salary are not over 40000 tk\n");
printf("Press 15 to see the engineer name and contact whose blood group is O+\n");
printf("Press 16 to see the engineer name and blood group whose get highest salary\n");
printf("Press 17 to see the oldest engineer name and hometown\n");
printf("Press 18 to see the female engineer name and id of lowest salary\n");
printf("Press 19 to see the youngest CSE engineer name and id\n");
printf("Press 20 to see the married engineer whose home town rajshahi\n");
printf("Press 21 to see the age of a engineer by his ID\n");
printf("Press 22 to see the name & id of a engineer by his contact\n");
printf("Press 23 to see the CSE/EEE engineer name whose are using banglalink sim\n");
printf("Press 24 to see the Male/Female engineer id whose are using teletalk sim\n");
printf("Press 25 to see which has the maximum receiver in the sim company\n");
printf("Press 26 to see which has the minimum receiver in the sim company\n");
printf("Press 0 to exit\n");
scanf("%d",&n);
fflush(stdin);
if(n==1)
{
int male_count=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_gender,"Male")==0)
{
male_count++;
}
}
printf("Number of male engineers is = %d\n",male_count);
}
else if(n==2)
{
for(int i=0;i<counter;i++)
{
if((s[i].engineer_age>=25) && (s[i].engineer_age<=35))
{
puts(s[i].engineer_name);
puts(s[i].engineer_id);
}
}
}
else if(n==3)
{
int cse_count=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_category,"CSE")==0)
{
cse_count++;
}
}
printf("Number of CSE engineers is = %d\n",cse_count);
}
else if(n==4)
{
for(int i=0;i<counter;i++)
{
if(s[i].engineer_level>=3)
{
puts(s[i].engineer_name);
puts(s[i].engineer_contact);
}
}
}
else if(n==5)
{
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_blood,"AB-")==0)
{
puts(s[i].engineer_name);
puts(s[i].engineer_address);
}
}
}
else if(n==6)
{
int min_age=s[0].engineer_age;
int min_index=0;
for(int i=0;i<counter;i++)
{
if(s[i].engineer_age<min_age)
{
min_age=s[i].engineer_age;
min_index=i;
}
}
puts(s[min_index].engineer_name);
puts(s[min_index].engineer_blood);
}
else if(n==7)
{
float min_salary=s[0].engineer_salary;
int min_index=0;
for(int i=0;i<counter;i++)
{
if(s[i].engineer_salary<min_salary)
{
min_salary=s[i].engineer_salary;
min_index=i;
}
}
puts(s[min_index].engineer_name);
puts(s[min_index].engineer_hometown);
}
else if(n==8)
{
int max_age=s[0].engineer_age;
int max_index=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_category,"EEE")==0)
{
max_age=s[i].engineer_age;
max_index=i;
break;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_age>max_age)&&(strcmp(s[i].engineer_category,"EEE")==0))
{
max_age=s[i].engineer_age;
max_index=i;
}
}
puts(s[max_index].engineer_name);
puts(s[max_index].engineer_id);
}
else if(n==9)
{
float max_salary=s[0].engineer_salary;
int max_index=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_gender,"Male")==0)
{
max_salary=s[i].engineer_salary;
max_index=i;
break;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_salary>max_salary)&&(strcmp(s[i].engineer_gender,"Male")==0))
{
max_salary=s[i].engineer_salary;
max_index=i;
}
}
puts(s[max_index].engineer_name);
puts(s[max_index].engineer_id);
}
else if(n==10)
{
for(int i=0;i<counter;i++)
{
if((strcmp(s[i].engineer_maritalstatus,"Unmarried")==0)&&(strcmp(s[i].engineer_blood,"B+")==0))
{
puts(s[i].engineer_name);
printf("%d\n",s[i].engineer_age);
}
}
}
else if(n==11)
{
int female_count=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_gender,"Female")==0)
{
female_count++;
}
}
printf("Number of female engineers is =%d\n",female_count);
}
else if(n==12)
{
for(int i=0;i<counter;i++)
{
if((strlen(s[i].engineer_address)>=8)&&(strlen(s[i].engineer_address)<=12))
{
puts(s[i].engineer_name);
puts(s[i].engineer_id);
}
}
}
else if(n==13)
{
int home_count=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_hometown,"Comilla")==0)
{
home_count++;
}
}
printf("Number of engineers whose hometown comilla is =%d\n",home_count);
}
else if(n==14)
{
for(int i=0;i<counter;i++)
{
if(s[i].engineer_salary<=40000)
{
puts(s[i].engineer_name);
puts(s[i].engineer_email);
}
}
}
else if(n==15)
{
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_blood,"O+")==0)
{
puts(s[i].engineer_name);
puts(s[i].engineer_contact);
}
}
}
else if(n==16)
{
float max_salary=s[0].engineer_salary;
int max_index=0;
for(int i=0;i<counter;i++)
{
if(s[i].engineer_salary>max_salary)
{
max_salary=s[i].engineer_salary;
max_index=i;
}
}
puts(s[max_index].engineer_name);
puts(s[max_index].engineer_blood);
}
else if(n==17)
{
int max_age=s[0].engineer_age;
int max_index=0;
for(int i=0;i<counter;i++)
{
if(s[i].engineer_age>max_age)
{
max_age=s[i].engineer_age;
max_index=i;
}
}
puts(s[max_index].engineer_name);
puts(s[max_index].engineer_hometown);
}
else if(n==18)
{
float min_salary=s[0].engineer_salary;
int min_index=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_gender,"Female")==0)
{
min_salary=s[i].engineer_salary;
min_index=i;
break;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_salary<min_salary)&&(strcmp(s[i].engineer_gender,"Female")==0))
{
min_salary=s[i].engineer_salary;
min_index=i;
}
}
puts(s[min_index].engineer_name);
puts(s[min_index].engineer_id);
}
else if(n==19)
{
int min_age=s[0].engineer_age;
int min_index=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_category,"CSE")==0)
{
min_age=s[i].engineer_age;
min_index=i;
break;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_age<min_age)&&(strcmp(s[i].engineer_category,"CSE")==0))
{
min_age=s[i].engineer_age;
min_index=i;
}
}
puts(s[min_index].engineer_name);
puts(s[min_index].engineer_id);
}
else if(n==20)
{
for(int i=0;i<counter;i++)
{
if((strcmp(s[i].engineer_maritalstatus,"Married")==0)&&(strcmp(s[i].engineer_hometown,"Rajshahi")==0))
{
printf("%s\n",s[i].engineer_name);
printf("%d\n",s[i].engineer_age);
}
}
}
else if(n==21)
{
printf("Please enter engineer id:");
gets(str);
int flag=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_id,str)==0)
{
flag=1;
printf("Age is = %d\n",s[i].engineer_age);
break;
}
}
if(flag==0)
{
puts("Wrong input");
}
}
else if(n==22)
{
printf("Please enter engineer contact:");
gets(str);
int flag=0;
for(int i=0;i<counter;i++)
{
if(strcmp(s[i].engineer_contact,str)==0)
{
flag=1;
printf("Name is = %s\n",s[i].engineer_name);
printf("ID is = %s\n",s[i].engineer_id);
break;
}
}
if(flag==0)
{
puts("Wrong input");
}
}
else if(n==23)
{
printf("Please enter engineer category CSE/EEE:");
gets(str);
int flag=0;
for(int i=0;i<counter;i++)
{
if(((s[i].engineer_contact[2])=='9')&&(strcmp(s[i].engineer_category,str)==0))
{
flag=1;
puts(s[i].engineer_name);
}
}
if(flag==0)
{
puts("Wrong input");
}
}
else if(n==24)
{
printf("Please enter engineer gender Male/Female:");
gets(str);
int flag=0;
for(int i=0;i<counter;i++)
{
if(((s[i].engineer_contact[2])=='5')&&(strcmp(s[i].engineer_gender,str)==0))
{
flag=1;
puts(s[i].engineer_id);
}
}
if(flag==0)
{
puts("Wrong input");
}
}
else if(n==25)
{
int tel_count=0,air_count=0,gp_count=0,robi_count=0,ban_count=0;
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='5')
{
tel_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='6')
{
air_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='7')
{
gp_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='8')
{
robi_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='9')
{
ban_count++;
}
}
if((tel_count>air_count)&&(tel_count>gp_count)&&(tel_count>robi_count)&&(tel_count>ban_count))
{
printf("Teletalk has the maximum receiver.User is = %d\n",tel_count);
}
if((air_count>tel_count)&&(air_count>gp_count)&&(air_count>robi_count)&&(air_count>ban_count))
{
printf("Airtel has the maximum receiver.User is = %d\n",air_count);
}
if((gp_count>air_count)&&(gp_count>tel_count)&&(gp_count>robi_count)&&(gp_count>ban_count))
{
printf("Grameenphone has the maximum receiver.User is = %d\n",gp_count);
}
if((robi_count>air_count)&&(robi_count>gp_count)&&(robi_count>tel_count)&&(robi_count>ban_count))
{
printf("Robi has the maximum receiver.User is = %d\n",robi_count);
}
if((ban_count>air_count)&&(ban_count>gp_count)&&(ban_count>robi_count)&&(ban_count>tel_count))
{
printf("Banglalink has the maximum receiver.User is = %d\n",ban_count);
}
}
else if(n==26)
{
int tel_count=0,air_count=0,gp_count=0,robi_count=0,ban_count=0;
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='5')
{
tel_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='6')
{
air_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='7')
{
gp_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='8')
{
robi_count++;
}
}
for(int i=0;i<counter;i++)
{
if((s[i].engineer_contact[2])=='9')
{
ban_count++;
}
}
if((tel_count<air_count)&&(tel_count<gp_count)&&(tel_count<robi_count)&&(tel_count<ban_count))
{
printf("Teletalk has the mimimum receiver.User is = %d\n",tel_count);
}
if((air_count<tel_count)&&(air_count<gp_count)&&(air_count<robi_count)&&(air_count<ban_count))
{
printf("Airtel has the minimum receiver.User is = %d\n",air_count);
}
if((gp_count<air_count)&&(gp_count<tel_count)&&(gp_count<robi_count)&&(gp_count<ban_count))
{
printf("Grameenphone has the minimum receiver.User is = %d\n",gp_count);
}
if((robi_count<air_count)&&(robi_count<gp_count)&&(robi_count<tel_count)&&(robi_count<ban_count))
{
printf("Robi has the minimum receiver.User is = %d\n",robi_count);
}
if((ban_count<air_count)&&(ban_count<gp_count)&&(ban_count<robi_count)&&(ban_count<tel_count))
{
printf("Banglalink has the minimum receiver.User is = %d\n",ban_count);
}
}
else if(n==0)
{
exit(0);
}
}*/
fclose(fp);
}
else
{
puts("Try again");
}
return 0;
}
| true |
aa843dec45679bb1415ebf4c7794f1b34f0f48d1 | C++ | gzc/leetcode | /cpp/1001-10000/1031-1040/Minimum Score Triangulation of Polygon.cpp | UTF-8 | 985 | 2.796875 | 3 | [
"MIT"
] | permissive | class Solution {
int dfs(vector<int>& A, map<pair<int, int>, int>& cache, int start_index, int end_index) {
pair<int, int> key = {start_index, end_index};
auto it = cache.find(key);
if (it != cache.end()) return it->second;
if (end_index - start_index < 2) {
return 0;
}
if (end_index - start_index == 2) {
return A[start_index] * A[start_index+1] * A[start_index+2];
}
int ans = INT_MAX;
for (int i = start_index+1; i < end_index; i++) {
int current = A[start_index] * A[i] * A[end_index];
current += dfs(A, cache, start_index, i);
current += dfs(A, cache, i, end_index);
ans = min(ans, current);
}
return cache[key] = ans;
}
public:
int minScoreTriangulation(vector<int>& A) {
map<pair<int, int>, int> cache;
return dfs(A, cache, 0, A.size() - 1);
}
};
| true |
6d15f5e18df84a6f64f26676ce36d8e2e5a36a12 | C++ | KonradKap/Minecamp | /tests/Button/ButtonTests.cc | UTF-8 | 4,080 | 2.71875 | 3 | [] | no_license | /*
* ButtonTests.cc
*
* Created on: 4 cze 2016
* Author: konrad
*/
#include <boost/test/unit_test.hpp>
#include "Button/Button.h"
BOOST_AUTO_TEST_SUITE(ButtonTests);
BOOST_AUTO_TEST_CASE(pointsWithinButtonShouldBeRecognized)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
BOOST_CHECK(button.contains(ofVec2f(4, 4)));
}
BOOST_AUTO_TEST_CASE(pointsOustisdeButtonShouldNotBeRecognized)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
BOOST_CHECK(!button.contains(ofVec2f(14, 14)));
}
BOOST_AUTO_TEST_CASE(mouseMovementOutsideOfButtonShouldKeepItInactive)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
ofMouseEventArgs args(ofMouseEventArgs::Type::Moved, 15, 15);
button.onMouseMove(args);
BOOST_CHECK_EQUAL(button.getState(), ButtonPrototype::ButtonState::INACTIVE);
}
BOOST_AUTO_TEST_CASE(mouseMovementInsideOfButtonShouldMakeItActive)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
ofMouseEventArgs args(ofMouseEventArgs::Type::Moved, 3, 3);
button.onMouseMove(args);
BOOST_CHECK_EQUAL(button.getState(), ButtonPrototype::ButtonState::ACTIVE);
}
BOOST_AUTO_TEST_CASE(mousePressOutsideOfButtonShouldHaveNoEffect)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
ofMouseEventArgs args_moved(ofMouseEventArgs::Type::Moved, 16, 3);
ofMouseEventArgs args_pressed(ofMouseEventArgs::Type::Pressed, 16, 3);
button.onMouseMove(args_moved);
button.onMousePress(args_pressed);
BOOST_CHECK_EQUAL(button.getState(), ButtonPrototype::ButtonState::INACTIVE);
}
BOOST_AUTO_TEST_CASE(mousePressInsideOfButtonShouldMarkItAsPressed)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
ofMouseEventArgs args_moved(ofMouseEventArgs::Type::Moved, 3, 3);
ofMouseEventArgs args_pressed(ofMouseEventArgs::Type::Pressed, 3, 3);
button.onMouseMove(args_moved);
button.onMousePress(args_pressed);
BOOST_CHECK_EQUAL(button.getState(), ButtonPrototype::ButtonState::PRESSED);
}
BOOST_AUTO_TEST_CASE(mouseReleaseOutsideOfButtonShouldHaveNoEffect)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
ofMouseEventArgs args_moved(ofMouseEventArgs::Type::Moved, 13, 3);
ofMouseEventArgs args_pressed(ofMouseEventArgs::Type::Pressed, 13, 3);
ofMouseEventArgs args_released(ofMouseEventArgs::Type::Released, 13, 3);
button.onMouseMove(args_moved);
button.onMousePress(args_pressed);
button.onMouseRelease(args_released);
BOOST_CHECK_EQUAL(button.getState(), ButtonPrototype::ButtonState::INACTIVE);
}
BOOST_AUTO_TEST_CASE(mouseReleaseInsideOfButtonShouldMakeItActiveAgain)
{
ofImage image;
image.allocate(10, 10, ofImageType::OF_IMAGE_COLOR);
ButtonPrototype prototype({image, image, image}, ofTrueTypeFont());
Button button(ofVec2f(0, 0), "", prototype);
ofMouseEventArgs args_moved(ofMouseEventArgs::Type::Moved, 3, 3);
ofMouseEventArgs args_pressed(ofMouseEventArgs::Type::Pressed, 3, 3);
ofMouseEventArgs args_released(ofMouseEventArgs::Type::Released, 3, 3);
button.onMouseMove(args_moved);
button.onMousePress(args_pressed);
button.onMouseRelease(args_released);
BOOST_CHECK_EQUAL(button.getState(), ButtonPrototype::ButtonState::ACTIVE);
}
BOOST_AUTO_TEST_SUITE_END();
| true |
736876e9ed0b76009b3b2bbe21a6d47bf911df1e | C++ | zhiltsov-max/tower-defense | /modules/Game/Buildings/turret_bullet.cpp | UTF-8 | 1,399 | 2.75 | 3 | [] | no_license | #include "bullet.h"
TBuilding::Bullet::Bullet(const Point2f& pos_, float damage_, float acceleration_, TMob const* target_, ushort size_) :
pos(pos_),
damage(damage_),
acceleration(acceleration_),
target(target_),
size(size_),
color(DEFAULT_COLOR)
{}
static Graphics::ZIndex TBuilding::Bullet::getZIndex() const {
return GraphicsZIndex::Bullet;
}
void TBuilding::Bullet::setZIndex(Graphics::ZIndex value) {
UNUSED( value )
}
const Point2f TBuilding::Bullet::getPos() const {
return pos;
}
void TBuilding::Bullet::setPos(float x, float y) {
pos = Point2f(x, y);
}
void TBuilding::Bullet::setPos(const Point2f& pos_) {
pos(pos_);
}
bool TBuilding::Bullet::isCloseToTarget() const {
return (target->getPos() - pos).abs() <= target->getSize();
}
void TBuilding::Bullet::update() {
if (target == nullptr) {
return;
}
if (target->isAlive() == false) {
return;
}
if (isCloseToTarget() == true) {
hurt();
} else {
move();
}
}
void TBuilding::Bullet::draw() {
Graphics::SetColor(color);
Graphics::DrawOval(pos.x() - size, pos.y() - size, 2 * size, 2 * size);
}
void TBuilding::Bullet::move() {
speed += acceleration;
const Point2f diff = target->getPos() - pos;
double angle = std::atan2(pos.y(), pos.x());
pos += Point2f(speed * std::cos(angle), speed * std::sin(angle));
}
void TBuilding::Bullet::hurt() {
target->setHealth(target->getHealth() - damage);
} | true |
5b6ae7682286cbed1625e6241fcde794a6deb53e | C++ | francis0407/SQL-Engine-On-LSM | /test/execution/SQLStatementSuite.cpp | UTF-8 | 4,996 | 2.5625 | 3 | [] | no_license | #include "gtest/gtest.h"
#include <map>
#include <stdio.h>
#include <dirent.h>
#include "expressions/Literal.h"
#include "expressions/AttributeReference.h"
#include "expressions/Comparison.h"
#include "operators/Scan.h"
#include "operators/Project.h"
#include "operators/Filter.h"
#include "operators/Join.h"
#include "catalog/Catalog.h"
#include "catalog/RelationReference.h"
#include "execution/QueryExecutor.h"
#include "MemoryPool.h"
#include "test/util/TestCatalog.h"
#include "test/util/TestScan.h"
#include "catalog/LevelDBCatalog.h"
using namespace simplesql;
using namespace simplesql::expressions;
using namespace simplesql::operators;
using namespace simplesql::catalog;
using namespace simplesql::execution;
using namespace simplesql::test;
using namespace std;
class SQLStatementSuite : public testing::Test {
public:
SQLStatementSuite() {
qe = new QueryExecutor(new LevelDBCatalog("TestDB"));
}
~SQLStatementSuite() {
// delete qe;
}
virtual void TearDown() override {
// DIR* dirp = opendir("TestDB");
// struct dirent *dir;
// while ((dir = readdir(dirp)) != NULL)
// unlink(dir->d_name);
// closedir(dirp);
// rmdir("TestDB");
}
QueryExecutor* qe;
void withTableTest() {
static bool isCreated = false;
if (isCreated) return;
Relation result;
qe->executeSQL("CREATE TABLE TEMP (A INTEGER, B STRING, C FLOAT) INDEX ON (B);", result);
}
template<size_t rows, size_t columns>
void assertResult(const Relation& result, AnyValue* answer[rows][columns] ) {
ASSERT_EQ(result.columns, columns);
ASSERT_EQ(result.rows.size(), rows);
for (size_t i = 0; i < rows; i++)
for (size_t j = 0; j < columns; j++) {
ASSERT_TRUE(result.rows[i]->values[j]->equalToSemantically(answer[i][j]));
delete answer[i][j];
}
}
};
TEST_F(SQLStatementSuite, CreateTable) {
Relation result;
qe->executeSQL("CREATE TABLE TEMP (A INTEGER, B STRING, C FLOAT) INDEX ON (B);", result);
RelationReference relation("TEMP");
ASSERT_TRUE(qe->catalog->findRelation(relation));
ASSERT_TRUE(relation.attributes.attributes[0].equalTo(Attribute(Integer, "A")));
ASSERT_TRUE(relation.attributes.attributes[0].hasIndex);
ASSERT_TRUE(relation.attributes.attributes[1].equalTo(Attribute(Integer, "B")));
ASSERT_TRUE(relation.attributes.attributes[1].hasIndex);
ASSERT_TRUE(relation.attributes.attributes[2].equalTo(Attribute(Integer, "C")));
ASSERT_FALSE(relation.attributes.attributes[2].hasIndex);
qe->executeSQL("INSERT INTO TEMP VALUES (1, 'ddd', 1.0), (2, 'ddd', 2.0), (3, 'ccc', 3.0);", result);
Relation result2;
qe->executeSQL("SELECT A, B, C FROM TEMP;", result2);
AnyValue* answer[3][3] = {
{IntegerValue::create(1), StringValue::create(string("ddd")), FloatValue::create(1.0f)},
{IntegerValue::create(2), StringValue::create(string("ddd")), FloatValue::create(2.0f)},
{IntegerValue::create(3), StringValue::create(string("ccc")), FloatValue::create(3.0f)},
};
assertResult<3, 3>(result2, answer);
// Secondary Index Scan
OperatorBase* opt = new SecondIndexScan(new RelationReference("TEMP"), 1, Literal::create(string("ccc")), nullptr);
Relation result3;
qe->executeTree(opt, result3);
AnyValue* answer3[3][3] = {
{IntegerValue::create(3), StringValue::create(string("ccc")), FloatValue::create(3.0f)},
{IntegerValue::create(1), StringValue::create(string("ddd")), FloatValue::create(1.0f)},
{IntegerValue::create(2), StringValue::create(string("ddd")), FloatValue::create(2.0f)}
};
assertResult<3, 3>(result3, answer3);
// HashJoin
OperatorBase* opt2 = new InnerJoin(
new SecondIndexScan(new RelationReference("TEMP", "T1"), 1, nullptr, nullptr),
new SeqScan(new RelationReference("TEMP", "T2")),
BuildLeft,
new EqualTo(new AttributeReference("T1", "B"), new AttributeReference("T2", "B")),
HashJoin
);
((InnerJoin*)opt2)->leftKeyOffset = 1;
((InnerJoin*)opt2)->rightKeyOffset = 1;
Relation result4;
qe->executeTree(opt2, result4);
ASSERT_EQ(result4.rows.size(), 5);
result4.show();
}
TEST_F(SQLStatementSuite, Insert) {
// withTableTest();
// Relation result;
// qe->executeSQL("INSERT INTO TEMP VALUES (1, 'aaa', 1.0), (2, 'bbb', 2.0), (3, 'ccc', 3.0);", result);
// Relation result2;
// qe->executeSQL("SELECT A, B, C FROM TEMP;", result2);
// AnyValue* answer[3][3] = {
// {IntegerValue::create(1), StringValue::create(string("aaa")), FloatValue::create(1.0f)},
// {IntegerValue::create(2), StringValue::create(string("bbb")), FloatValue::create(2.0f)},
// {IntegerValue::create(3), StringValue::create(string("ccc")), FloatValue::create(3.0f)},
// };
// assertResult<3, 3>(result2, answer);
}
| true |
f0f6156b534bd8fc6d04b0c98e5385a707d00b32 | C++ | valentinjacot/backupETHZ | /Scientific programming/fib_2.cpp | UTF-8 | 390 | 2.6875 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<Eigen/Dense>
using namespace Eigen;
using namespace std;
int main () {
unsigned int n;
cout << "state n" << endl;
cin >> n;
Matrix2d m;
m << 0,1,1,1;
Vector2d v;
v << 0, 1;
//cout << v << endl << " " << m << endl;
for (unsigned int i= 0;i<n-1; i++){
v=m*v;
}
cout << "The " << n << "th Fibonacci number is "<< v.row(1) << endl;
return 0;
}
| true |
44ea08353c115118b53704831d1372a1aad64e5a | C++ | thongngo3301/Codeforces | /Key races.cpp | UTF-8 | 299 | 3.078125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int s, v1, v2, t1, t2;
int sum1 = 0, sum2 = 0;
cin>>s>>v1>>v2>>t1>>t2;
sum1 = s*v1 + t1*2;
sum2 = s*v2 + t2*2;
if (sum1 == sum2)
cout<<"Friendship";
else {
if (sum1 < sum2)
cout<<"First";
else
cout<<"Second";
}
return 0;
}
| true |
b2033440758fd7fd2074f0e64e1637764b87ddde | C++ | ThomK1429/cpp_workshop2_2017 | /file_io_v1.cpp | UTF-8 | 444 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <fstream> // 1
using namespace std;
int main() {
// declare the in/out files
ifstream inFile; //2a
ofstream outFile; //2a
// open the files
inFile.open("inputFile.txt"); //3
outFile.open("outputFile.txt"); //3
// processing goes here
// close the files
inFile.close(); //2b
outFile.close(); //2b
cout << endl;
system("pause"); // Windows only
return 0;
}
| true |
f6c280142640e14e416007f1bce859ca4a00737b | C++ | a-bezruchenko/prob_theory_lab | /element.h | WINDOWS-1251 | 2,997 | 3.1875 | 3 | [
"MIT"
] | permissive | #include <list>
#include <string>
#include "canvas.h"
enum Type {TypeParallel, TypeSerial, TypeReal, TypeAbstract};
class abstractElement
{
public:
abstractElement();
Type getType(); // ; typeOf
bool operator==(abstractElement& other);
virtual long double prob_breaks() = 0; //
virtual Canvas* getImage() = 0; //
virtual int getName() = 0; //
virtual std::string getFormule() = 0; // ,
virtual unsigned getH() = 0; //
virtual unsigned getW() = 0; //
protected:
Type type; //
int id; // ;
};
class virtualElement: public abstractElement
{
public:
virtualElement();
~virtualElement();
virtualElement(bool isParallel, abstractElement* element);
long double prob_breaks();
Canvas* getImage();
std::string getFormule();
int getName();
std::list <std::string> getFullFormule(); //
unsigned getH();
unsigned getW();
void createParallel(abstractElement* element, abstractElement* addedElement);
void createSerial(abstractElement* element, abstractElement* addedElement);
protected:
std::list <abstractElement*> content; //
bool isInContent(abstractElement* element); // ,
void addChild(abstractElement* child); //
void removeChild(abstractElement* child); //
};
class realElement: public abstractElement
{
public:
realElement(long double prob, int name);
realElement(long double prob, virtualElement* parent);
realElement(long double prob);
realElement();
realElement(const realElement&);
realElement& realElement::operator=(const realElement& other);
long double prob_breaks();
Canvas* getImage();
std::string getFormule();
unsigned getH();
unsigned getW();
int getName();
void addParallel(abstractElement *element); //
void addSerial(abstractElement *element); //
void setParent(virtualElement* parent);
void setProb(long double prob);
virtualElement* getParent();
protected:
long double prob; //
int name; //
virtualElement* parent; //
}; | true |
8f9356d64ca4d7174e6cbb4050da3e830c4fb7dc | C++ | zcily/test | /C++Primer/base/md5.cpp | UTF-8 | 2,814 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <string.h>
#include <fstream>
#include <stdlib.h>
#include <vector>
using namespace std;
struct md5_file
{
char *md5_file_value;
char *md5_file_name;
};
void find_same_value(md5_file *all_md5_file, int length) {
vector<md5_file*> same_file;
vector<vector<md5_file*> > same_files;
bool first_find_flag = true;
for(int i = 0; i < length; ++i) {
for(int j = i; j < length; ++j) {
if(j == i)
continue;
if(!strncmp(all_md5_file[i].md5_file_value, all_md5_file[j].md5_file_value, strlen(all_md5_file[i].md5_file_value))) {
if(first_find_flag) {
same_file.push_back(&all_md5_file[i]);
first_find_flag = false;
}
same_file.push_back(&all_md5_file[j]);
}
}
if(!first_find_flag) {
same_files.push_back(same_file);
same_file.clear();
first_find_flag = true;
}
}
if(0 == same_files.size()) {
printf("\033[31mNot Find The Same Files!!!!!\033[0m\n");
return;
}
for(vector<vector<md5_file*> >::iterator same_begin = same_files.begin(); same_begin != same_files.end();++same_begin){
for(vector<md5_file*>::iterator s_file = (*same_begin).begin(); s_file != (*same_begin).end(); ++s_file) {
printf("*********same file name : %32s value : %32s\n", (*s_file)->md5_file_name, (*s_file)->md5_file_value);
}
}
}
int main(int argc, char**argv)
{
md5_file testFile[1024];
memset(&testFile, 0, 1024);
char name[1024] = {0};
char *value, *save_ptr, *temp;
system("rm md5.txt");
system("md5sum * > md5.txt");
system("sed -i 's/ /$/g' md5.txt");
ifstream read_file;
read_file.open("md5.txt");
int i = 0;
while(read_file.good() && !read_file.eof()) {
memset(name, 0, 1024);
read_file.getline(name, 1024);
temp = name;
int j = 0;
for(j = 0, temp ; ; temp = NULL) {
value = strtok_r(temp, "$", &save_ptr);
if(!value)
break;
++j;
if(1 == j) {
testFile[i].md5_file_value = new char[strlen(value) + 1];
memset(testFile[i].md5_file_value, '0', strlen(value) + 1);
strncpy(testFile[i].md5_file_value, value, strlen(value) + 1);
}
else if( 2 == j) {
testFile[i].md5_file_name = new char[strlen(value) + 1];
memset(testFile[i].md5_file_name, '0', strlen(value) + 1);
strncpy(testFile[i].md5_file_name, value, strlen(value) + 1);
}
}
++i;
}
--i;
find_same_value(testFile, i);
return 0;
}
| true |
c939b4c3baf024c0b2f54ba1e236be4b8539e465 | C++ | KimHwon/Teamnote | /archive/2021 ICPC - fresh water/code/calipers.cpp | UTF-8 | 767 | 2.84375 | 3 | [] | no_license | //+ 정수 컨벡스 헐
void calipers(vector<point>& pt) {
sort(pt.begin(), pt.end(), [](const point& a, const point& b) {
return (a.xx == b.xx) ? a.yy < b.yy : a.xx < b.xx;
});
vector<point> up, lo;
for (const auto& p : pt) {
while (up.size() >= 2 && ccw(*++up.rbegin(), *up.rbegin(), p) >= 0)
up.pop_back();
while (lo.size() >= 2 && ccw(*++lo.rbegin(), *lo.rbegin(), p) <= 0)
lo.pop_back();
up.emplace_back(p);
lo.emplace_back(p);
}
for (int i = 0, j = (int)lo.size() - 1; i + 1 < up.size() || j > 0; ) {
// DO WHAT YOU WANT with up[i], lo[j]
if (i + 1 == up.size()) --j;
else if (j == 0) ++i;
else if ((ll)(up[i+1].yy-up[i].yy)*(lo[j].xx-lo[j-1].xx)
> (ll)(up[i+1].xx-up[i].xx)*(lo[j].yy-lo[j-1].yy)) ++i;
else --j;
}
} | true |
89727da40e57c30ca6c1c660559405300353eb5b | C++ | davidsanchezg21/proyecto | /Proyec/obstaculos.cpp | UTF-8 | 1,170 | 2.5625 | 3 | [] | no_license | #include "obstaculos.h"
obstaculos::obstaculos()
{
posx=0;
posy=0;
vx=0;
vy=0;
r=0;
limite=0;
}
obstaculos::obstaculos(double _posx, double _posy,int _r, int _limi,int _vx, int _vy)
{
posx=_posx;
posy=_posy;
vx=_vx;
vy=_vy;
r=_r;
limite=_limi;
}
QRectF obstaculos::boundingRect() const
{
return QRectF(-r,-10,2*r,20);
}
void obstaculos::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPixmap pixmap;
pixmap.load(":/barra.jpg");
painter->drawPixmap(boundingRect(),pixmap,pixmap.rect());
}
void obstaculos::mover()
{
if(vy!=0){
calVel();
}
posx=posx;
posy=posy+vy;
setPos(posx,-posy);
}
void obstaculos::calVel()
{
//modifica posiocion para que no salga de la escena y cambia el sentido de la velocidad
if(posy-10<=limite){
vy=5;
posy=limite+r;
}
if(posy+10>=450){
vy=-5;
posy=450-r;
}
}
double obstaculos::getposx()
{
return posx;
}
double obstaculos::getPosy()
{
return posy;
}
double obstaculos::setVelocidad(float _vx, float _vy)
{
vx = _vx;
vy = _vy;
}
| true |
4997bd2e0db6c8ee2e91a06c0ad1324f805f9bc9 | C++ | rodchenkov-sn/CLoxx | /ReiLang/Function.hpp | UTF-8 | 767 | 2.578125 | 3 | [] | no_license | #pragma once
#include "Callable.hpp"
#include "Environment.hpp"
#include "Ast.hpp"
class Function : public Callable
{
public:
explicit Function(Stmt::Function* declaration, std::shared_ptr<Environment> closure);
explicit Function(Expr::Lambda* declaration, std::shared_ptr<Environment> closure);
[[nodiscard]] unsigned arity() const override;
Value call(Interpreter& interpreter, std::vector<Value> args) override;
[[nodiscard]] std::string toString() const override;
[[nodiscard]] std::shared_ptr<Function> bind(const std::weak_ptr<Instance>& instance) const;
private:
std::vector<Token> params_;
std::list<Stmt::Base::Ptr> body_;
std::string name_;
std::shared_ptr<Environment> closure_;
Stmt::Function* declaration_;
};
| true |
a6cb6a50639d6e02ec670873607ccb35ce29e8db | C++ | ssnhrytsiv/manager_task | /BL/Menu.cpp | UTF-8 | 1,294 | 2.921875 | 3 | [] | no_license | //
// Created by Nazar on 21.02.2017.
//
#include "../Entity/Task.h"
#include "../main.cpp"
int FirstMenu();
void add_new_task();
void menu()
{
int your_choice = 0;
while(your_choice != 5){
your_choice = FirstMenu();
switch (your_choice){
case 1:
{
add_new_task();
system("cls");
break;
}
case 2:
{
system("cls");
break;
}
case 3:
{
system("cls");
break;
}
case 4:
{
system("cls");
break;
}
default:
{
system("cls");
break;
}
}
}
}
int FirstMenu() {
int choose;
cout << "1)Create" << endl;
cout << "2)Read" << endl;
cout << "3)Update" << endl;
cout << "4)Delete" << endl;
cin >> choose;
return choose;
}
void add_new_task(Task & task_1, FILE *dataF)
{
char state[MAX_LEN];
char name[MAX_LEN];
cout << "enter name: " << endl;
cin >> name;
cout << "enter state: " << endl;
cin >> state;
task_1.set_name(name);
task_1.set_state(state);
} | true |
6872b48cbaacd80c07f2354a3cb66d9e7fd9788b | C++ | rlabrecque/RLEngine | /Core/src/ConVar.hpp | UTF-8 | 1,261 | 3.234375 | 3 | [] | no_license | #pragma once
class ConVar {
public:
inline ConVar(const char* name, const char* description, int value) : m_value(value), m_name(name), m_description(description), m_min(INT32_MIN), m_max(INT32_MAX) {
AddToList();
}
inline ConVar(const char* name, const char* description, const int value, const int min, const int max) :
m_value(value), m_name(name), m_description(description), m_min(min), m_max(max) {
RL_ASSERT(min <= max, "Minimum value must be greater than the maximum.");
RL_ASSERT(value >= min && value <= max, "The value must be between the minimum and maximum values!");
AddToList();
}
inline ConVar& operator=(int value) {
if(value < m_min) {
//todo: log error.
m_value = m_min;
}
if(value > m_max) {
m_value = m_max;
}
m_value = value;
return *this;
}
inline operator int(void) const {
return m_value;
}
inline const char* GetName() {
return m_name;
}
inline const char* GetDesc() {
return m_description;
}
inline ConVar* GetNextConvar() {
return m_next;
}
static ConVar* GetHead();
private:
void AddToList();
ConVar* m_next;
int m_value;
const char* m_name;
const char* m_description;
const int m_min;
const int m_max;
};
| true |
0474a745cf6a6b68fd86359b202f1c9765b32b1e | C++ | weidongguo/ecs175_computer_graphics | /p3/graph.h | UTF-8 | 1,677 | 2.828125 | 3 | [] | no_license | #ifndef GRAPH_H
#define GRAPH_H
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include "vector.h"
#include "common_type.h"
class Graph {
friend class Polygon; //not used
friend class Line; //not used
friend class Polyhedron ;
int window_width;
int window_height;
public:Color background_color;
public:
Graph(int width, int height, float* PixelBufferPtr);
float *PixelBuffer;
float *PixelBufferBackup;
int drawPixel(Point p);
int drawPixel(int x, int y, float r, float g, float b);
int drawPixel(int x, int y, Color c);
int drawLine(Point p1, Point p2); //using the color specified in each point
int drawLine(Point p1, Point p2, float r, float g, float b);
int drawLine(Point p1, Point p2, float r, float g, float b, int method);
int dda(Point p1, Point p2, float r, float g, float b);
int bresenham(Point p1, Point p2, float r, float, float);
int bresenham(Point p1, Point p2);
int fillScreen(float r, float g, float b);
int fillScreen(Color c);
int drawPolygon( Point *listOfPoints, int numberOfPoints, float r, float g, float b);
bool outOfBound(int x, int y);
void drawMegaPixel(int numberOfPixels, int maxNumberOfPixels, int r, int c, Color k);
void halfTone(Color color);
Color readPixel(int x, int y);
void backupPixelBuffer();
void restorePixelBuffer();
};
void determineStartAndEndPoints(Point p1, Point p2, int*x, int*y, int *x_end, int*y_end);//helper function for bresenham algo
void swapXY(Point *p1);//swap the x value of the point with its y value: helper funcion for bresenha algo
#define BRESENHAM 0
#define DDA 1
#endif
| true |
80889904ca3574f3ba94a38495914c84a7bb867b | C++ | litityum/EventQueueSmilator | /main.cpp | UTF-8 | 9,574 | 3.03125 | 3 | [] | no_license | #include "Passenger.h"
#include "Event.h"
#include <sstream>
#include <fstream>
#include <vector>
#include <queue>
bool first_fly = true;
struct mycmp
{
bool operator()(Event*& p1, Event*& p2)
{
return *p1>*p2;
}
};
struct first_fly_cmp{
bool operator() (Passenger*& p1, Passenger*& p2){
if(p1->flight != p2->flight)
return p1->flight > p2->flight;
return p1->arrive > p2->arrive;
}
};
void airport(priority_queue<Event*, vector<Event*>, mycmp> EventQueue, int _case, int sec, int lugg, int pass, ofstream& myfile){
first_fly = false;
bool vip_check = false;
bool online = false;
if(_case % 2 == 1)
first_fly = true;
if(_case % 4 > 1)
vip_check = true;
if(_case > 3)
online = true;
Passenger* security_counter[sec];
Passenger* luggage_counter[lugg];
for(int i = 0; i < sec; i++){
security_counter[i] = NULL;
}
for(int i = 0; i < lugg; i++){
luggage_counter[i] = NULL;
}
int fail_counter = 0;
int total_wait_time = 0;
int empty_lug = lugg;
int empty_sec = sec;
int count = 0;
if(first_fly){
priority_queue<Passenger*, vector<Passenger*>, first_fly_cmp> security_queue;
priority_queue<Passenger*, vector<Passenger*>, first_fly_cmp> luggage_queue;
while(!EventQueue.empty()){
count++;
Event* current = EventQueue.top();
EventQueue.pop();
int time = current->time;
if(current->type == 0){
if(online && current->passenger->luggage == 'N'){
if(vip_check && current->passenger->VIP == 'V'){
continue;
}
if(empty_sec){
EventQueue.push(new Event(time + current->passenger->security_time, 2, *current->passenger));
empty_sec--;
}
else {
current->passenger->queue_enter_time = time;
security_queue.push(current->passenger);
}
}
else {
if (empty_lug) {
EventQueue.push(new Event(time + current->passenger->luggage_time, 1, *current->passenger));
empty_lug--;
} else {
current->passenger->queue_enter_time = time;
luggage_queue.push(current->passenger);
}
}
}
if(current->type == 1){
empty_lug++;
if(vip_check && current->passenger->VIP == 'V'){
total_wait_time += (time - current->passenger->arrive);
if(time > current->passenger->flight)
fail_counter++;
/*
delete current->passenger;
delete current;
*/
}
else{
if(empty_sec){
EventQueue.push(new Event(time + current->passenger->security_time, 2, *current->passenger));
empty_sec--;
}
else {
current->passenger->queue_enter_time = time;
security_queue.push(current->passenger);
}
}
if(!luggage_queue.empty()){
Passenger* pass = luggage_queue.top();
luggage_queue.pop();
EventQueue.push(new Event(time + pass->luggage_time, 1, *pass));
empty_lug--;
}
}
if(current->type == 2){
total_wait_time += (time - current->passenger->arrive);
empty_sec++;
if(time > current->passenger->flight)
fail_counter++;
/*
delete current->passenger;
delete current;
*/
if(!security_queue.empty()){
Passenger* pass = security_queue.top();
security_queue.pop();
EventQueue.push(new Event(time + pass->security_time, 2, *pass));
empty_sec--;
}
}
}
}
else{
queue<Passenger*> security_queue;
queue<Passenger*> luggage_queue;
while(!EventQueue.empty()){
count++;
Event* current = EventQueue.top();
EventQueue.pop();
int time = current->time;
if(current->type == 0){
if(online && current->passenger->luggage == 'N'){
if(vip_check && current->passenger->VIP == 'V'){
continue;
}
if(empty_sec){
EventQueue.push(new Event(time + current->passenger->security_time, 2, *current->passenger));
empty_sec--;
}
else {
current->passenger->queue_enter_time = time;
security_queue.push(current->passenger);
}
}
else {
if (empty_lug) {
EventQueue.push(new Event(time + current->passenger->luggage_time, 1, *current->passenger));
empty_lug--;
} else {
current->passenger->queue_enter_time = time;
luggage_queue.push(current->passenger);
}
}
}
if(current->type == 1){
empty_lug++;
if(vip_check && current->passenger->VIP == 'V'){
total_wait_time += (time - current->passenger->arrive);
if(time > current->passenger->flight)
fail_counter++;
/*
delete current->passenger;
delete current;
*/
}
else{
if(empty_sec){
EventQueue.push(new Event(time + current->passenger->security_time, 2, *current->passenger));
empty_sec--;
}
else {
current->passenger->queue_enter_time = time;
security_queue.push(current->passenger);
}
}
if(!luggage_queue.empty()){
Passenger* pass = luggage_queue.front();
luggage_queue.pop();
EventQueue.push(new Event(time + pass->luggage_time, 1, *pass));
empty_lug--;
}
}
if(current->type == 2){
total_wait_time += (time - current->passenger->arrive);
empty_sec++;
if(time > current->passenger->flight)
fail_counter++;
/*
delete current->passenger;
delete current;
*/
if(!security_queue.empty()){
Passenger* pass = security_queue.front();
security_queue.pop();
EventQueue.push(new Event(time + pass->security_time, 2, *pass));
empty_sec--;
}
}
}
}
myfile << ((double)total_wait_time / (double)pass) << " " << fail_counter << endl;
}
int main(int argc, char* argv[]) {
//clock_t start = clock();
// below reads the input file
// in your next projects, you will implement that part as well
if (argc != 3) {
cout << "Run the code with the following command: ./project1 [input_file] [output_file]" << endl;
return 1;
}
//cout << "wtf is this: " << argv[0] << endl;
//cout << "input file: " << argv[1] << endl;
//cout << "output file: " << argv[2] << endl;
// here, perform the input operation. in other words,
// read the file named <argv[1]>
ifstream infile(argv[1]);
string line;
vector<string> input;
// process first line
getline(infile, line);
//cout << line << endl;
string token;
stringstream stream(line);
int pass;
stream >> pass;
int lugg;
stream >> lugg;
int sec;
stream >> sec;
/*
getline(stream, token, ' ');
const int pass = stoi(token);
getline(stream, token, ' ');
const int lugg = stoi(token);
getline(stream, token, ' ');
const int sec = stoi(token);
*/
//cout << pass << " " << lugg << " " << sec << endl;
Passenger* passenger;
// int max = 0;
priority_queue<Event*, vector<Event*>, mycmp> EventQueue;
//priority_queue<Passenger*, vector<Passenger*>, first_fly_cmp> passengers;
for(int i = 0; i < pass; i++){
getline(infile, line);
passenger = new Passenger(line);
Event* ev = new Event(passenger->arrive, 0, *passenger);
EventQueue.push(ev);
}
ofstream myfile;
myfile.open (argv[2]);
for(int k = 0; k < 8; k++){
airport(EventQueue, k, sec, lugg, pass, myfile);
}
myfile.close();
//clock_t stop = clock();
//double elapsed = (double) (stop - start) / CLOCKS_PER_SEC;
//printf("\nTime elapsed: %.5f\n", elapsed);
//return 0;
} | true |