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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3cb60f0ccb21b9094123afac3e8d82c1dde30964 | C++ | valiok98/testing | /OpenCV/main.cpp | UTF-8 | 4,431 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv_modules.hpp>
// Custom header files
#include "window.hpp"
#include "frame-helper.hpp"
#define MODE 0 // This is the mode of thresholding. Currently supported : 0 | 1
int main() {
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
Window* threshold_window = new Window(MODE ? "Adaptive thresholding" : "Normal thresholding"),
* trackbar_window = new Window("Trackbar window");
FrameHelper thrs_fr_hp(MODE),
* threshold_fr_hp = &thrs_fr_hp;
cv::VideoCapture cap(0);
if (!cap.isOpened()) {
std::cerr << "Video capturing failed!\n";
return -1;
}
/**
* Open 3 windows.
* 1. Threshold window with camera feed.
* 2. Adaptive threshold window with camera feed.
* 3. Trackbar window with controls for both thresholding types.
*/
cv::namedWindow(threshold_window->getName());
cv::namedWindow(trackbar_window->getName());
// Create the trackbars
threshold_fr_hp->create_trackbars(trackbar_window);
while (1) {
cv::Mat threshold_frame,
threshold_frame_copy;
cap >> threshold_frame;
cap >> threshold_frame_copy;
try {
cv::cvtColor(threshold_frame, threshold_frame_copy, CV_BGR2GRAY);
// Set frame.
threshold_fr_hp->setFrame(threshold_frame_copy);
// Apply thresholding.
threshold_fr_hp->thresholding();
// Find contours.
cv::findContours(threshold_frame_copy, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
// Draw contours.
for( size_t i = 0; i < contours.size(); i++ ) {
std::vector<cv::Point> approx_contour;
cv::approxPolyDP(contours[i], approx_contour, cv::arcLength(contours[i], true) * 0.02, true);
cv::Scalar QUADRILATERAL_COLOR(0, 0, 255),
color;
cv::Rect r = cv::boundingRect(approx_contour);
if (approx_contour.size() == 4) {
color = QUADRILATERAL_COLOR;
}
else {
continue;
}
if (r.height < 20 || r.width < 20 ||
r.width > threshold_frame.cols - 10 || r.height > threshold_frame.rows - 10) {
continue;
}
cv::polylines(threshold_frame, approx_contour, true, color, 4);
// -----------------------------
// --- Process Corners ---
for (size_t j = 0; j < approx_contour.size(); ++j) {
cv::circle(threshold_frame, approx_contour[j], 3, CV_RGB(0, 255, 0), -1);
double dx = ((double)approx_contour[(j + 1) % 4].x - (double)approx_contour[j].x) / 7.0;
double dy = ((double)approx_contour[(j + 1) % 4].y - (double)approx_contour[j].y) / 7.0;
for (int k = 1; k < 7; ++k) {
double px = (double)approx_contour[j].x + (double)k * dx;
double py = (double)approx_contour[j].y + (double)k * dy;
cv::Point p;
p.x = (int)px;
p.y = (int)py;
cv::circle(threshold_frame, p, 2, CV_RGB(0, 0, 255), -1);
}
}
}
// -----------------------------
} catch(cv::Exception& err) {
// Let it slide, happens on first try. Continue with the safe copy instead.
threshold_frame = threshold_frame_copy;
}
//hello
// Show the thresholded image.
cv::imshow(threshold_window->getName(), threshold_frame);
if (cv::waitKey(10) == 27) {
break;
}
}
delete trackbar_window;
delete threshold_window;
return 0;
}
| true |
eca344ce1485c49bb95171dd0f17ac5b7b4b3d48 | C++ | Ethan0pia/School-Work | /cs162-IntroToCSII/group project/group project/Tool.hpp | UTF-8 | 541 | 2.703125 | 3 | [] | no_license | /**************************************************************
* Authors: Lindsey Bunte, Ethan Dunham, Bryan Fishback, Marisa Rea, Dean Ohashi, James Whiteley IV, Kyle Wollman
* Date: 2/13/2017
* Description: Group Project
* Tool.hpp is the Tool class specification file.
* ***********************************************************/
#ifndef TOOL_HPP
#define TOOL_HPP
class Tool {
protected:
double strength;
char type;
public:
Tool();
void setStrength(int);
int getStrength();
char getType();
virtual int fight(Tool*) = 0;
virtual ~Tool(){}
};
#endif
| true |
cbbe5265abd279180bff1a60a73ac0a6d869115b | C++ | wizaral/Chess | /src/menu.cpp | UTF-8 | 3,177 | 2.65625 | 3 | [] | no_license | #include "game.hpp"
void Game::print_menu(std::array<int, 4> &positions) {
bool exit = false;
while (m_window.isOpen() && !exit) {
sf::Event e;
while (m_window.pollEvent(e)) {
if (Game::is_exit(e)) {
m_window.close();
}
if (e.type == sf::Event::MouseButtonReleased && e.mouseButton.button == sf::Mouse::Left) {
auto pos = sf::Mouse::getPosition(m_window);
if (m_buttons[0].first.getGlobalBounds().contains(pos.x, pos.y)) {
positions[0] = 1;
positions[1] = 0;
} else if (m_buttons[1].first.getGlobalBounds().contains(pos.x, pos.y)) {
positions[0] = 0;
positions[1] = 1;
} else if (m_buttons[2].first.getGlobalBounds().contains(pos.x, pos.y)) {
positions[2] = 1;
positions[3] = 0;
} else if (m_buttons[3].first.getGlobalBounds().contains(pos.x, pos.y)) {
positions[2] = 0;
positions[3] = 1;
} else if (m_buttons[4].first.getGlobalBounds().contains(pos.x, pos.y)) {
exit = true;
}
}
if (e.type == sf::Event::KeyPressed && (e.key.code == sf::Keyboard::Enter || e.key.code == sf::Keyboard::Space)) {
exit = true;
}
}
m_window.draw(m_background.first);
for (auto &i : m_buttons)
m_window.draw(i.first);
for (int i = 0; i < 4; ++i) {
if (positions[i] > 0) {
m_rect.first.setPosition(m_buttons[i].first.getPosition() - sf::Vector2f{4, -4});
m_window.draw(m_rect.first);
}
}
m_window.display();
}
}
void Game::menu() {
#if defined(_WIN64) || defined(_WIN32)
std::string path("stockfish.exe");
#elif defined(__APPLE__) || defined(__linux__)
std::string path("PUT_CORRECT_PATH_HERE");
#else
#error unsupported OS
#endif
std::array<int, 4> positions{1, 0, 1, 0};
std::array<std::unique_ptr<Chess::Player>, Chess::players_amount> players;
print_menu(positions);
if (m_window.isOpen()) {
if (positions[0]) {
players[1] = std::make_unique<GraphicsBotPlayer>(Chess::FigureColor::Black, "Black bot", m_move, m_log, path, s_tile_size, m_window, m_dragg_pos, m_dragging);
} else {
players[1] = std::make_unique<RealPlayer>(Chess::FigureColor::Black, "Black player", m_move, s_tile_size, m_window, m_dragg_pos, m_dragging);
}
if (positions[2]) {
players[0] = std::make_unique<GraphicsBotPlayer>(Chess::FigureColor::White, "White bot", m_move, m_log, path, s_tile_size, m_window, m_dragg_pos, m_dragging);
} else {
players[0] = std::make_unique<RealPlayer>(Chess::FigureColor::White, "White player", m_move, s_tile_size, m_window, m_dragg_pos, m_dragging);
}
m_logic = std::make_unique<Chess::Logic>(std::move(players));
m_logic->init_game(std::make_unique<Chess::ClassicFactory>());
loop();
}
}
| true |
32ecc92bf3943d43654efaf4f32beb6780c237bc | C++ | MahmoudOuka/C-console-App. | /main.cpp | UTF-8 | 7,981 | 2.9375 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "course.h"
#include"Student.h"
#include"Teacher.h"
#include"Doctor.h"
#include"TA.h"
#include"person.h"
#include"System.h"
using namespace std;
int main(){
System fci(100);
//-------------Making Two Objects Of Students , Teacher Assistant , Doctor
//------------- Making 2 courses && Add Materials to them.
Student s1("karim","1","karim2016@gmail.com","CS");
fci.AllStudents[fci.NumOfS++]=&s1;
Student s2("Ismail","2","ismail2016@gmail.com","IT");
fci.AllStudents[fci.NumOfS++]=&s2;
TA t1("Mohamed","3","mohamed2016@gmail.com","IS");
fci.AllTAs[fci.NumOfT++]=&t1;
TA t2("Rashad","4","rashad2016@gmail.com","DS");
fci.AllTAs[fci.NumOfT++]=&t2;
Doctor d1("Mahmoud","5","mahmoud2016@gmail.com","CS");
d1.addCourse("Mahmoud","Math",&fci);
d1.AddMaterial("http://www.math.com/",&fci);
d1.AddMaterial("http://www.mathAllTimeIsFun.com/",&fci);
fci.AllDoctors[fci.NumOfD++]=&d1;
Doctor d2("Maged","6","maged2016@gmail.com","IT");
Doctor d3("esss","6","maged2016@gmail.com","DS");
d2.addCourse("Maged","English",&fci);
d2.AddMaterial("http://www.Engliiiiish.com/",&fci);
d2.AddMaterial("http://www.English.Ils.com/",&fci);
fci.AllDoctors[fci.NumOfD++]=&d2;
fci.AllDoctors[fci.NumOfD++]=&d3;
///////////////////////////////////////////////////////////////////////////////////////
Start :
fci.Design();
int x,ID;
string pass,username;
cin>>x;
while(x!=2 && x!=1)
{
cout<<"Please Reenter Your choice: ";
cin>>x;
}
if(x==1)
{
//---------Student---------Student---------Student---------Student---------Student---------Student-------
cout<<"Enter your UserName : ";
cin>>username;
cout<<"Enter your Password : ";
cin>>pass;
for(int i=0 ; i<username.size() ; i++)
if(isalpha(username[i]))
{
cout<<"Invalid user name Characters not allowed"<<endl;
goto Start;
}
ID=fci.Int(username);
system("cls") ;
if(ID>199999||ID<100000) goto Start;
string Id=fci.NumberToString(ID);
if(fci.SignIn(Id, pass))
{
Student *s;
for(int i=0 ; i<fci.NumOfS ; i++)
if(fci.AllStudents[i]->getId()==ID)
{
s=fci.AllStudents[i];
}
Student1:
cout << "Choose from the following :"<<endl
<< "1 . Join Course.\n"
<< "2 . Get Materials\n"
<< "3 . Show Grades\n"
<< "4 . Log Out"<<endl;
int t=0;
while(t!=1 && t!=2 && t!=3 && t!=4)
{
cout<<"Enter Your Choice : ";
cin>>t;
system("cls");
}
if(t==1)
{
fci.ShowCourses();
cout<<endl<<endl;
int v;
cout<<"Enter Course ID which You want to join in : ";
cin>>v;
system("cls");
s->joinCourse(v,&fci);
goto Student1;
}
else if(t==2)
{
fci.ShowCourses();
cout<<endl<<endl;
int v;
cout<<"Whats Course ID You want to get Material : ";
cin>>v;
system("cls");
s->getMatrial(v);
cout<<endl<<endl;
goto Student1;
}
else if(t==3)
{
system("cls");
s->ShowGrades();
cout<<endl<<endl;
goto Student1;
}
else
{
goto Start;
}
}
else
{
goto Start;
}
}
else
{
//-----------------------------------------------Stuff Log In-----------------------------------
cout<<"Enter UserName : ";
cin>>username;
cout<<"Enter your Password : ";
cin>>pass;
for(int i=0 ; i<username.size() ; i++)
if(isalpha(username[i]))
{
cout<<"Invalid user name Characters not allowed "<<endl;
goto Start;
}
ID=fci.Int(username);
system("cls");
if(ID<200000) goto Start;
else if(ID<300000)
{
//------------Teacher Assistant------------Teacher Assistant------------Teacher Assistant------------Teacher Assistant
string Id=fci.NumberToString(ID);
if(fci.SignIn(Id, pass))
{
TA *ta;
for(int i=0 ; i<fci.NumOfT ; i++)
if(fci.AllTAs[i]->get_ID()==ID)
{
ta=fci.AllTAs[i];
}
TA1:
cout << "Choose from the following :"<<endl
<< "1 . Join Course.\n"
<< "2 . Add Materials\n"
<< "3 . Modify Grades\n"
<< "4 . Log Out"<<endl;
int t=0;
while(t!=1 && t!=2 && t!=3 && t!=4)
{
cout<<"Enter Your Choice : ";
cin>>t;
system("cls");
}
if(t==1)
{
fci.ShowCourses();
cout<<endl<<endl;
int v;
cout<<"Enter Course ID Which You want to join in : ";
cin>>v;
system("cls");
ta->JoinCourse(v,&fci);
goto TA1;
}
else if(t==2)
{
string v;
cout<<"Enter The Course Materials you want to Add : ";
cin.sync();
getline(cin,v);
bool f = false;;
for(int i = 0 ; i<v.length() ; ++i)
{
if(v[i] == ' ')
{
f = true;
break;
}
}
try
{
if(f == true)
{
throw "Material URL can't contain spaces.";
}
system("cls");
ta->AddMaterial(v,&fci);
goto TA1;
}
catch(const char * x)
{
cout << x << endl << endl << endl;
}
//system("cls");
//ta->AddMaterial(v,&fci);
goto TA1;
}
else if(t==3)
{
int v;
cout<<"Enter The Student ID You want to Modify his Grades : ";
cin>>v;
double g;
cout<<"Enter His new Grade + Old Grades : ";
cin>>g;
system("cls");
ta->ModGrades(v,g,&fci);
goto TA1;
}
else
{
goto Start;
}
}
else
{
system("cls");
goto Start;
}
}
else
{
//----------Doctor----------Doctor----------Doctor----------Doctor----------Doctor----------Doctor---------
string Id=fci.NumberToString(ID);
if(fci.SignIn(Id, pass))
{
Doctor *d;
for(int i=0 ; i<fci.NumOfD ; i++)
if(fci.AllDoctors[i]->GetID()==ID)
{
d=fci.AllDoctors[i];
}
Doctor1:
cout << "Choose from the following :"<<endl
<< "1 . Add Course.\n"
<< "2 . Add Materials\n"
<< "3 . Modify Grades\n"
<< "4 . Log Out"<<endl;
int t=0;
while(t!=1 && t!=2 && t!=3 && t!=4)
{
cout<<"Enter Your Choice : ";
cin>>t;
system("cls");
}
if(t==1)
{
string v1,v2;
cout<<"What Course Name You want to Add : ";
cin.sync();
getline(cin,v1);
cout<<"Enter your Name : ";
cin.sync();
getline(cin,v2);
system("cls");
d->addCourse(v2,v1,&fci);
goto Doctor1;
}
else if(t==2)
{
string v;
cout<<"Enter the Course Materials you want to Add : ";
cin.sync();
getline(cin,v);
bool f = false;;
for(int i = 0 ; i<v.length() ; ++i)
{
if(v[i] == ' ')
{
f = true;
break;
}
}
try
{
if(f == true)
{
throw "Material URL can't contain spaces.";
}
system("cls");
d->AddMaterial(v,&fci);
goto Doctor1;
}
catch(const char * x)
{
cout << x << endl << endl << endl;
}
//system("cls");
//d->AddMaterial(v,&fci);
goto Doctor1;
}
else if(t==3)
{
int v;
cout<<"Enter The Student ID You want to Modify his Grades : ";
cin>>v;
double g;
cout<<"Enter His new Grade + Old Grades : ";
cin>>g;
system("cls");
d->ModGrades(v,g,&fci);
goto Doctor1;
}
else
{
system("cls");
goto Start;
}
}
else
{
goto Start;
}
}
}
system("cls") ;
}
| true |
1c419329e32687933ddc64567da26345687e809e | C++ | Frankalexej/COMP2113GroupProject | /Map.h | UTF-8 | 3,729 | 3.25 | 3 | [] | no_license | #include "Point.h"
#include "Initialiser.h"
#include "ConfigInitiator.h"
#pragma once
class Map
{
// it is basically an array of Point ptrs, with many functions
private:
Initialiser* initialiser; // this is used mainly for getting fullLife and Fee, sth ConfigInitiator doesn't cover
ConfigInitiator* init; // mainly used to pass new Troop infos
int width; // map width (columns)
int height; // map height (rows)
Point*** map; // start address of array with Point*
// 存疑
public:
Map(); // not used in our game
Map(Initialiser* initialiser, ConfigInitiator* init); // pass in Initialiser and ConfigInitiator
~Map(); // destructor, deletes Point*** map (but in fact not a must, because Map will be created once only in an excution, and it lives until end of program)
void bindConfigInitiator(ConfigInitiator* init); // binder
void bindInitialiser(Initialiser* initialiser); // binder
// this opens a .txt file to set up a map (an array of terrain points with two capital points)
void initMap(ifstream& fin); // please refer to definition for details
// saves the map as .txt file
// accepts GameMediator data as input, this is because saveMap(), unlike initMap(), will not run in main() and thus cannot be bridged to GameMediator directly
void saveMap(ofstream& fou, bool isTurn, int AMoney, int BMoney);
// simple getters
int getWidth();
int getHeight();
// get Point at position, accepts coordination, return Point*
Point* getPointAt(int x, int y);
// set position, unlike addTo, does insertion only (simple assignment given array index)
void setPointAt(Point* p);
// judges whether point p can move to position (destinationX, destinationY), true if can
bool canTo(Point* p, int destinationX, int destinationY);
// part of canTo(), used to judge whether position (x, y) is out of the map
// calling it beforehands can prevent array outOfBound errors
bool notOutOfBound(int x, int y);
// this function adds point to one position, returns the was of the occupier before move
// return value passed to reconstruct orignial terrain at place just left
// note that this function will add point to position as defined in its x and y
int addTo(Point* p); // no side check!
// this is no more needed
// void dieFrom(Point* p); // only applicable to occupiers
// this function moves point at origin to destination (applies to troops only)
// input same as for canTo()
bool moveTo(Point* p, int destinationX, int destinationY); // true if move successful, else false
// below three are functional
// engineer only, if called, change engineer to a factory, return false if not enough money, checker included
int setFactory(Point* p, int money);
// if called, add to full life, return false if not enough money or life already full, no checker
int lifeRecover(Point* p, int money);
// used for factory/capital's troop production
// money: total money of player, used to judge whether production can proceed
// side: to which side the troop belongs
// type: troop type; (destinationX, destinationY): destination position
int newTroopto(int money, bool side, string type, int destinationX, int destinationY);
// battle, pass in two Point ptrs: attacker and original (defender)
// includes randomness, please refer to definition for details
bool battle(Point* attacker, Point* original); // true if attacker wins, false if else
// this should print to screen info and operations available at the point
string getTerrainInfo(Point* p);
// Point* p same as getTerrainInfo(), isTurn: if not your Occupiers, you cannot access any information
string getOccupierInfo(Point* p, bool isTurn);
};
| true |
2d0916d3e78c9a79ae5bd035336f0e8d4fa8dd57 | C++ | wma1729/simple-n-fast | /http/include/common/headers.h | UTF-8 | 5,749 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef _SNF_HTTP_CMN_HEADERS_H_
#define _SNF_HTTP_CMN_HEADERS_H_
#include <string>
#include <utility>
#include <vector>
#include <ostream>
#include <memory>
#include "hval.h"
namespace snf {
namespace http {
const std::string CONTENT_LENGTH("content-length");
const std::string TRANSFER_ENCODING("transfer-encoding");
const std::string TE("te");
const std::string TRAILERS("trailers");
const std::string HOST("host");
const std::string VIA("via");
const std::string CONNECTION("connection");
const std::string CONTENT_TYPE("content-type");
const std::string CONTENT_ENCODING("content-encoding");
const std::string CONTENT_LANGUAGE("content-language");
const std::string CONTENT_LOCATION("content-location");
const std::string DATE("date");
const std::string TRANSFER_ENCODING_CHUNKED("chunked");
using hdr_vec_t = std::vector<std::pair<std::string, std::shared_ptr<base_value>>>;
/*
* HTTP headers. Maintained as a vector of key/value pair.
*/
class headers
{
private:
hdr_vec_t m_headers;
hdr_vec_t::iterator find(const std::string &);
hdr_vec_t::const_iterator find(const std::string &) const;
base_value *validate(const std::string &, const std::string &);
public:
static std::string canonicalize_name(const std::string &);
headers() {}
headers(const headers &hdrs) { m_headers = hdrs.m_headers; }
headers(headers &&hdrs) { m_headers = std::move(hdrs.m_headers); }
const headers & operator=(const headers &hdrs)
{
if (this != &hdrs)
m_headers = hdrs.m_headers;
return *this;
}
headers & operator=(headers &&hdrs)
{
if (this != &hdrs)
m_headers = std::move(hdrs.m_headers);
return *this;
}
friend std::ostream &operator<<(std::ostream &, const headers &);
bool empty() const { return m_headers.empty(); }
void add(const std::string &);
void add(const std::string &, const std::string &);
void update(const std::string &, const std::string &);
void update(const std::string &, base_value *);
void remove(const std::string &);
bool is_set(const std::string &) const;
const base_value *get(const std::string &) const;
/*
* Content-Length: <size>
*/
size_t content_length() const;
void content_length(size_t);
void content_length(const std::string &);
/*
* Transfer-Encoding: chunked
*
* From RFC 7231:
*
* Transfer-Encoding is primarily intended to accurately
* delimit a dynamically generated payload and to distinguish payload
* encodings that are only applied for transport efficiency or security
* from those that are characteristics of the selected resource.
*
* A recipient MUST be able to parse the chunked transfer coding
* because it plays a crucial role in framing messages
* when the payload body size is not known in advance. A sender MUST
* NOT apply chunked more than once to a message body (i.e., chunking an
* already chunked message is not allowed). If any transfer coding
* other than chunked is applied to a request payload body, the sender
* MUST apply chunked as the final transfer coding to ensure that the
* message is properly framed. If any transfer coding other than
* chunked is applied to a response payload body, the sender MUST either
* apply chunked as the final transfer coding or terminate the message
* by closing the connection.
*
* For example,
* Transfer-Encoding: gzip, chunked
*
* indicates that the payload body has been compressed using the gzip
* coding and then chunked using the chunked coding while forming the
* message body.
*/
const std::vector<token> &transfer_encoding() const;
void transfer_encoding(const token &);
void transfer_encoding(const std::vector<token> &);
void transfer_encoding(const std::string &);
bool is_message_chunked() const;
/*
* TE: trailers
*/
const std::vector<token> &te() const;
void te(const token &);
void te(const std::vector<token> &);
void te(const std::string &);
bool has_trailers() const;
/*
* Trailers: <list_of_header_fields>
*/
const std::vector<std::string> &trailers() const;
void trailers(const std::string &);
void trailers(const std::vector<std::string> &);
/*
* Host: <host>[:<port>]
*/
const std::string &host(in_port_t *) const;
void host(const std::string &, in_port_t port);
void host(const host_port &);
/*
* Via: [<protocol-name>/]<protocol-version> <received-by> <comment>
*/
const std::vector<via> &intermediary() const;
void intermediary(const via &);
void intermediary(const std::vector<via> &);
void intermediary(const std::string &);
/*
* Connection: close
* Connection: keep-alive
* Connection: upgrade
*/
const std::vector<std::string> &connection() const;
bool close_connection() const;
void connection(const std::string &);
void connection(const std::vector<std::string> &);
/*
* Content-Type: text/plain;charset=utf-8
* Content-Type: application/json;charset=iso-8859-1
*/
const media_type &content_type() const;
void content_type(const media_type &);
void content_type(const std::string &, const std::string &);
/*
* Content-Encoding: gzip
*/
const std::vector<std::string> &content_encoding() const;
void content_encoding(const std::string &);
/*
* Content-Lanaguage: en-US [, en-UK]
*/
const std::vector<std::string> &content_language() const;
void content_language(const std::string &);
void content_language(const std::vector<std::string> &);
/*
* Content-Location: <uri>
*/
uri content_location() const;
void content_location(const uri &);
void content_location(const std::string &);
/*
* Date: <imf-date>
*/
const snf::datetime &date() const;
void date(time_t);
void date(const snf::datetime &);
void date(const std::string &);
};
} // namespace http
} // namespace snf
#endif // _SNF_HTTP_CMN_HEADERS_H_
| true |
e3846576142dacd4a95eb58f7d3da266795ca47f | C++ | WarlockD/quake-stm32 | /old_wgtcc/type.h | UTF-8 | 12,260 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef _WGTCC_TYPE_H_
#define _WGTCC_TYPE_H_
#include "common.h"
#include "mem_pool.h"
#include "scope.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <list>
class Scope;
class Token;
class Expr;
class Type;
class QualType;
class VoidType;
class Identifier;
class Object;
class Constant;
class ArithmType;
class DerivedType;
class ArrayType;
class FuncType;
class PointerType;
class StructType;
class EnumType;
enum {
// Storage class specifiers
S_TYPEDEF = 0x01,
S_EXTERN = 0x02,
S_STATIC = 0x04,
S_THREAD = 0x08,
S_AUTO = 0x10,
S_REGISTER = 0x20,
// Type specifier
T_SIGNED = 0x40,
T_UNSIGNED = 0x80,
T_CHAR = 0x100,
T_SHORT = 0x200,
T_INT = 0x400,
T_LONG = 0x800,
T_VOID = 0x1000,
T_FLOAT = 0x2000,
T_DOUBLE = 0x4000,
T_BOOL = 0x8000,
T_COMPLEX = 0x10000,
//T_ATOMIC = 0x20000,
T_STRUCT_UNION = 0x40000,
T_ENUM = 0x80000,
T_TYPEDEF_NAME = 0x100000,
T_LLONG = 0x2000000,
// Function specifier
F_INLINE = 0x4000000,
F_NORETURN = 0x8000000,
};
struct Qualifier {
enum {
CONST = 0x01,
RESTRICT = 0x02,
VOLATILE = 0x04,
MASK = CONST | RESTRICT | VOLATILE
};
};
class QualType {
public:
QualType(Type* ptr, int quals=0x00)
: ptr_(reinterpret_cast<intptr_t>(ptr)) {
assert((quals & ~Qualifier::MASK) == 0);
ptr_ |= quals;
}
operator bool() const { return !IsNull(); }
bool IsNull() const { return GetPtr() == nullptr; }
const Type* GetPtr() const {
return reinterpret_cast<const Type*>(ptr_ & ~Qualifier::MASK);
}
Type* GetPtr() {
return reinterpret_cast<Type*>(ptr_ & ~Qualifier::MASK);
}
Type& operator*() { return *GetPtr(); }
const Type& operator*() const { return *GetPtr(); }
Type* operator->() { return GetPtr(); }
const Type* operator->() const { return GetPtr(); }
// Indicate whether the specified types are identical(exclude qualifiers).
friend bool operator==(QualType lhs, QualType rhs) {
return lhs.operator->() == rhs.operator->();
}
friend bool operator!=(QualType lhs, QualType rhs) {
return !(lhs == rhs);
}
int Qual() const { return ptr_ & 0x03; }
bool IsConstQualified() const { return ptr_ & Qualifier::CONST; }
bool IsRestrictQualified() const { return ptr_ & Qualifier::RESTRICT; }
bool IsVolatileQualified() const { return ptr_ & Qualifier::VOLATILE; }
private:
intptr_t ptr_;
};
class Type {
public:
static const int intWidth_ = 4;
static const int machineWidth_ = 8;
bool operator!=(const Type& other) const = delete;
bool operator==(const Type& other) const = delete;
virtual bool Compatible(const Type& other) const {
return complete_ == other.complete_;
}
virtual ~Type() {}
// For Debugging
virtual std::string Str() const = 0;
virtual size_t Width() const = 0;
virtual int Align() const { return Width(); }
static int MakeAlign(int offset, int align) {
if ((offset % align) == 0)
return offset;
if (offset >= 0)
return offset + align - (offset % align);
else
return offset - align - (offset % align);
}
static QualType MayCast(QualType type, bool inProtoScope=false);
bool Complete() const { return complete_; }
void SetComplete(bool complete) const { complete_ = complete; }
bool IsReal() const { return IsInteger() || IsFloat(); };
virtual bool IsScalar() const { return false; }
virtual bool IsFloat() const { return false; }
virtual bool IsInteger() const { return false; }
virtual bool IsBool() const { return false; }
virtual bool IsVoidPointer() const { return false; }
virtual bool IsUnsigned() const { return false; }
virtual VoidType* ToVoid() { return nullptr; }
virtual const VoidType* ToVoid() const { return nullptr; }
virtual ArithmType* ToArithm() { return nullptr; }
virtual const ArithmType* ToArithm() const { return nullptr; }
virtual ArrayType* ToArray() { return nullptr; }
virtual const ArrayType* ToArray() const { return nullptr; }
virtual FuncType* ToFunc() { return nullptr; }
virtual const FuncType* ToFunc() const { return nullptr; }
virtual PointerType* ToPointer() { return nullptr; }
virtual const PointerType* ToPointer() const { return nullptr; }
virtual DerivedType* ToDerived() { return nullptr; }
virtual const DerivedType* ToDerived() const { return nullptr; }
virtual StructType* ToStruct() { return nullptr; }
virtual const StructType* ToStruct() const { return nullptr; }
protected:
Type(MemPool* pool, bool complete)
: complete_(complete), pool_(pool) {}
mutable bool complete_;
MemPool* pool_;
};
class VoidType : public Type {
public:
static VoidType* New();
virtual ~VoidType() {}
virtual VoidType* ToVoid() { return this; }
virtual const VoidType* ToVoid() const { return this; }
virtual bool Compatible(const Type& other) const { return other.ToVoid(); }
virtual int Width() const {
// Non-standard GNU extension
return 1;
}
virtual std::string Str() const { return "void:1"; }
protected:
explicit VoidType(MemPool* pool): Type(pool, false) {}
};
class ArithmType : public Type {
public:
static ArithmType* New(int typeSpec);
virtual ~ArithmType() {}
virtual ArithmType* ToArithm() { return this; }
virtual const ArithmType* ToArithm() const { return this; }
virtual bool Compatible(const Type& other) const {
// C11 6.2.7 [1]: Two types have compatible type if their types are the same
// But i would to loose this constraints: integer and pointer are compatible
//if (IsInteger() && other.ToPointer())
// return other.Compatible(*this);
return this == &other;
}
virtual size_t Width() const;
virtual std::string Str() const;
virtual bool IsScalar() const { return true; }
virtual bool IsInteger() const { return !IsFloat() && !IsComplex(); }
virtual bool IsUnsigned() const { return tag_ & T_UNSIGNED; }
virtual bool IsFloat() const {
return (tag_ & T_FLOAT) || (tag_ & T_DOUBLE);
}
virtual bool IsBool() const { return tag_ & T_BOOL; }
bool IsComplex() const { return tag_ & T_COMPLEX; }
int Tag() const { return tag_; }
int Rank() const;
static ArithmType* IntegerPromote(ArithmType* type) {
assert(type->IsInteger());
if (type->Rank() < ArithmType::New(T_INT)->Rank())
return ArithmType::New(T_INT);
return type;
}
static ArithmType* MaxType(ArithmType* lhsType,
ArithmType* rhsType);
protected:
explicit ArithmType(MemPool* pool, int spec)
: Type(pool, true), tag_(Spec2Tag(spec)) {}
private:
static int Spec2Tag(int spec);
int tag_;
};
class DerivedType : public Type {
public:
QualType Derived() const { return derived_; }
void SetDerived(QualType derived) { derived_ = derived; }
virtual DerivedType* ToDerived() { return this; }
virtual const DerivedType* ToDerived() const { return this; }
protected:
DerivedType(MemPool* pool, QualType derived)
: Type(pool, true), derived_(derived) {}
QualType derived_;
};
class PointerType : public DerivedType {
public:
static PointerType* New(QualType derived);
~PointerType() {}
virtual PointerType* ToPointer() { return this; }
virtual const PointerType* ToPointer() const { return this; }
virtual bool Compatible(const Type& other) const;
virtual int Width() const { return 8; }
virtual bool IsScalar() const { return true; }
virtual bool IsVoidPointer() const { return derived_->ToVoid(); }
virtual std::string Str() const {
return derived_->Str() + "*:" + std::to_string(Width());
}
protected:
PointerType(MemPool* pool, QualType derived): DerivedType(pool, derived) {}
};
class ArrayType : public DerivedType {
public:
static ArrayType* New(int len, QualType eleType);
static ArrayType* New(Expr* expr, QualType eleType);
virtual ~ArrayType() { /*delete derived_;*/ }
virtual ArrayType* ToArray() { return this; }
virtual const ArrayType* ToArray() const { return this; }
virtual bool Compatible(const Type& other) const;
virtual int Width() const {
return Complete() ? (derived_->Width() * len_): 0;
}
virtual int Align() const { return derived_->Align(); }
virtual std::string Str() const {
return derived_->Str() + "[]:" + std::to_string(Width());
}
int GetElementOffset(int idx) const { return derived_->Width() * idx; }
int Len() const { return len_; }
void SetLen(int len) { len_ = len; }
bool Variadic() const { return lenExpr_ != nullptr; }
protected:
ArrayType(MemPool* pool, Expr* lenExpr, QualType derived)
: DerivedType(pool, derived),
lenExpr_(lenExpr), len_(0) {
SetComplete(false);
//SetQual(QualType::CONST);
}
ArrayType(MemPool* pool, int len, QualType derived)
: DerivedType(pool, derived),
lenExpr_(nullptr), len_(len) {
SetComplete(len_ >= 0);
//SetQual(QualType::CONST);
}
const Expr* lenExpr_;
int len_;
};
class FuncType : public DerivedType {
public:
typedef std::vector<Object*> ParamList;
public:
static FuncType* New(QualType derived,
int funcSpec,
bool variadic,
const ParamList& params);
~FuncType() {}
virtual FuncType* ToFunc() { return this; }
virtual const FuncType* ToFunc() const { return this; }
virtual bool Compatible(const Type& other) const;
virtual int Width() const { return 1; }
virtual std::string Str() const;
const ParamList& Params() const { return params_; }
void SetParams(const ParamList& params) { params_ = params; }
bool Variadic() const { return variadic_; }
bool IsInline() const { return inlineNoReturn_ & F_INLINE; }
bool IsNoReturn() const { return inlineNoReturn_ & F_NORETURN; }
protected:
FuncType(MemPool* pool, QualType derived, int inlineReturn,
bool variadic, const ParamList& params)
: DerivedType(pool, derived), inlineNoReturn_(inlineReturn),
variadic_(variadic), params_(params) {
SetComplete(false);
}
private:
int inlineNoReturn_;
bool variadic_;
ParamList params_;
};
class StructType : public Type {
public:
typedef std::list<Object*> MemberList;
typedef std::list<Object*>::iterator Iterator;
public:
static StructType* New(bool isStruct,
bool hasTag,
Scope* parent);
~StructType() {}
virtual StructType* ToStruct() { return this; }
virtual const StructType* ToStruct() const { return this; }
virtual bool Compatible(const Type& other) const;
virtual int Width() const { return width_; }
virtual int Align() const { return align_; }
virtual std::string Str() const;
// struct/union
void AddMember(Object* member);
void AddBitField(Object* member, int offset);
bool IsStruct() const { return isStruct_; }
Object* GetMember(const Symbol& member);
Scope* MemberMap() { return memberMap_; }
MemberList& Members() { return members_; }
int Offset() const { return offset_; }
bool HasTag() const { return hasTag_; }
void MergeAnony(Object* anony);
void Finalize();
protected:
// default is incomplete
StructType(MemPool* pool, bool isStruct, bool hasTag, Scope* parent);
StructType(const StructType& other);
private:
void CalcWidth();
bool isStruct_;
bool hasTag_;
Scope* memberMap_;
MemberList members_;
int offset_;
int width_;
int align_;
int bitFieldAlign_;
};
/*
// Not used yet
class EnumType: public Type {
public:
static EnumTypePtr New(bool complete=false, int quals);
virtual ~EnumType() {}
virtual bool IsInteger() const { return true; }
virtual ArithmType* ToArithm() {
assert(false);
return ArithmType::New(T_INT);
}
virtual EnumTypePtr ToEnum() { return this; }
virtual bool Compatible(const Type& other) const {
// As enum is always casted to INT, there is no chance for this call
assert(false);
return (other.ToEnum() || other.IsInteger()) && Type::Compatible(other);
}
virtual int Width() const {
return ArithmType::New(T_INT)->Width();
}
virtual std::string Str() const { return "enum:4"; }
protected:
explicit EnumType(MemPool* pool, bool complete): Type(pool, complete) {}
};
*/
#endif
| true |
2cc4e287ffcba2ef48e4c86ab259809e66428545 | C++ | mperez-fomento/3dengine | /test/test.cpp | UTF-8 | 3,569 | 3.125 | 3 | [] | no_license | #include <catch2/catch_test_macros.hpp>
#include "matrix.hpp"
#include "engine3d.hpp"
TEST_CASE("Rows can be checked for equality", "[columns]") {
matrix::Row<3> c {1, 2, 3};
matrix::Row<3> d {4, 5, 6};
matrix::Row<3> f {1, 2, 3};
REQUIRE(c == c);
REQUIRE(c == f);
REQUIRE(c != d);
}
TEST_CASE("Rows can be multiplied by scalars", "[columns]") {
matrix::Row<3> a {1, 2, 3};
REQUIRE(2*a == matrix::Row<3>{2, 4, 6});
REQUIRE(0.5*a == matrix::Row<3>{0.5, 1, 1.5});
}
TEST_CASE("Rows can be added", "[columns]") {
matrix::Row<3> a {1, 2, 3};
matrix::Row<3> b {4, 5, 6};
REQUIRE(a + b == matrix::Row<3>{5, 7, 9});
REQUIRE(a - b == matrix::Row<3>{-3, -3, -3});
}
TEST_CASE("Dot product of two columns is a scalar", "[columns]") {
matrix::Row<3> a {1, 2, 3};
matrix::Row<3> b {4, 5, 6};
REQUIRE(a*b == 32);
}
TEST_CASE("Rows can be negated", "[columns]") {
matrix::Row<3> a {1, 2, 3};
REQUIRE(-a == matrix::Row<3>{-1, -2, -3});
}
TEST_CASE("Matrices can be multiplied by a scalar", "[matrix]") {
matrix::Matrix<3, 3> a {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
REQUIRE(2*a == matrix::Matrix<3, 3>{{{2, 4, 6}, {8, 10, 12}, {14, 16, 18}}});
}
TEST_CASE("Matrices can be added", "[matrix]") {
matrix::Matrix<2, 2> a {{{1, 2}, {4, 5}}};
matrix::Matrix<2, 2> b {{{1, 1}, {1, 1}}};
REQUIRE(a + b == matrix::Matrix<2, 2>{{{2, 3}, {5, 6}}});
}
TEST_CASE("Matrices can be multiplied", "[matrix]") {
matrix::Matrix<2, 2> a {{{1, 2}, {3, 4}}};
matrix::Matrix<2, 2> b {{{1, 1}, {1, 1}}};
matrix::Matrix<2, 3> c {{{1, 2, 3}, {4, 5, 6}}};
REQUIRE(a * b == matrix::Matrix<2, 2>{{{3, 3}, {7, 7}}});
REQUIRE(b * a == matrix::Matrix<2, 2>{{{4, 6}, {4, 6}}});
REQUIRE(b * c == matrix::Matrix<2, 3>{{{5, 7, 9}, {5, 7, 9}}});
}
TEST_CASE("Matrices can be transposed", "[matrix]") {
matrix::Matrix<2, 2> a {{{1, 2}, {3, 4}}};
REQUIRE(transpose(a) == matrix::Matrix<2, 2>{{{1, 3}, {2, 4}}});
}
TEST_CASE("Rows can be multiplied with matrices", "[row],[matrix]") {
matrix::Row<3> r {1, 2, 3};
matrix::Matrix<3, 3> m {{{1, 1, 1}, {1, 0, 1}, {-1, 0, 1}}};
REQUIRE(r * m == matrix::Row<3>{0, 1, 6});
}
TEST_CASE("Identity matrix times any matrix or row is that matrix or row", "[matrix]") {
matrix::Matrix<3, 3> m {{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}};
matrix::Row<3> r {1, 2 ,3};
REQUIRE(matrix::I<3>() * m == m);
REQUIRE(m * matrix::I<3>() == m);
REQUIRE(r * matrix::I<3>() == r);
}
TEST_CASE("Homegeneous vectors can be normalized", "[row]") {
matrix::Vector4 v {2, 4, 6, 2};
matrix::Vector4 w {2, 4, 6, 0};
matrix::Vector4 x {2, 4, 6, 1};
REQUIRE(normalize(v) == matrix::Vector4{1, 2, 3, 1});
REQUIRE(normalize(w) == matrix::Vector4{2, 4, 6, 0});
REQUIRE(normalize(x) == matrix::Vector4{2, 4, 6, 1});
}
TEST_CASE("3D vectors can be transformed into homogeneous coordinate vectors", "[row]") {
matrix::Vector3 v {1, 2, 3};
REQUIRE(homogenize(v) == matrix::Vector4{1, 2, 3, 1});
}
TEST_CASE("Object-to-World matrix is correctly computed", "[poly]") {
e3d::Poly frontTri;
frontTri.triangles.push_back({{-1, -1, 0}, {0, 1, 0}, {1, -1, 0}});
e3d::Poly sideTri;
sideTri.triangles.push_back({{0, -1, -1}, {0, 1, 0}, {0, -1, -1}});
e3d::Poly horTri;
horTri.triangles.push_back({{-1, 0, -1}, {0, 0, 1}, {1, 0, -1}});
SECTION("Without moving or rotating, o2w matrix is the identity matrix") {
REQUIRE(frontTri.objectToWorldMatrix - matrix::I<4>() == 2*matrix::I<4>());
}
}
| true |
8492038d8a15ef90b4fee3fadccd44d42d8623d5 | C++ | HaochenLiu/My-Project-Euler | /007.cpp | UTF-8 | 630 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <math.h>
using namespace std;
int main() {
int N = 200001;
bool* flag = new bool[N];
memset(flag, true, sizeof(flag));
flag[0] = false;
flag[1] = false;
for(int i = 2; i <= sqrt((double)N); i++) {
for(int j = 2 * i; j < N; j += i) {
flag[j] = false;
}
}
int cnt = 0;
for(int i = 0; i < N; i++) {
if(flag[i]) {
cnt++;
if(cnt == 10001) {
cout<<"res = "<<i<<endl;
break;
}
}
}
delete[] flag;
int wait = 0;
cin>>wait;
return 0;
}
| true |
91a969474446eae522d478dda47c0c5348a0158e | C++ | spade69/strikeoffer | /Binary_01/binary1.cpp | UTF-8 | 1,096 | 3.296875 | 3 | [] | no_license | include<iostream>
using namespace std;
/**
*Binary tree
*A node has left right and parent pointer
*Given a binary tree and a node in it.
*Find and return the next node at the order
*midOrder traversal
*eg : left->root->right
*
*Author Jason
Date 2016/7/1
* */
struct TreeLinkNode{
int val;
struct TreeLink* left;
struct TreeLink* right;
struct TreeLink* parent;
TreeLinkNode(int x):val(x),left(NULL),right(NULL),parent(NULL){
}
};
TreeLinkNode* GetNext(TreeLinkNode* pNode){
if(pNode==NULL)
return NULL;
//mid order . If right's Node 's leftchild is not empty,then must travseral to left is NULL
if(pNode->right!=NULL){
pNode=pNode->right;
while(pNode->left!=NULL)
{
pNode=pNode->left;
}
return pNode;
}
//right is NULL,then go to find the parent!
//parent's left!
while(pNode->parent!=NULL){
TreeLinkNode *pRoot=pNode->parent;
if(pRoot->left==pNode)
return pRoot;
pNode=pNode->parent;
}
return NULL;
}
int main(){
return 0;
}
| true |
b78298dda201d2d56311304c9dd0576b4caf7009 | C++ | yja938882/CSE | /coding_problem/baekjoon_7568.cpp | UTF-8 | 343 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main( void ){
int N;
cin >> N;
int kg[N];
int cm[N];
for( int i=0; i<N; i++ ){
cin >> kg[i] >> cm[i];
}
for( int i=0; i< N; i++ ){
int cnt = 1;
for( int j=0; j<N; j++ ){
if( j== i ) continue;
if( kg[i] < kg[j] && cm[i] < cm[j] ) cnt ++;
}
cout << cnt <<" ";
}
return 0;
}
| true |
ee55cfba9c447a84efc4ef56472ecd9bd12a05e8 | C++ | LiamTyler/Progression | /code/shared/hash.hpp | UTF-8 | 502 | 3.015625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <functional>
#include <string>
template <class T>
inline void HashCombine( std::size_t& seed, const T& v )
{
std::hash<T> hasher;
seed ^= hasher( v ) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
inline void HashCombine( std::size_t& seed, const char* str )
{
std::string s( str );
std::hash<std::string> hasher;
seed ^= hasher( s ) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
template <class T>
inline size_t Hash( const T& x )
{
return std::hash<T>{}( x );
} | true |
3e36d006493299fa89cf112802eb9efb05aa093f | C++ | bhagya314/MKPITS_Bhagyashri_Lalsare_Java_Mar_2021 | /C_Programs/330_CalculateTotalPerGrade.cpp | UTF-8 | 863 | 3.734375 | 4 | [] | no_license | //create function
//a- calculatetotal(int sub1,int sub2,int sub3)
//b - calculatepercentage(int total)
//c- calculategrade(float per)
#include<stdio.h>
#include<conio.h>
void calculatepercentage(int total);
void calculategrade(double per);
void calculatetotal(int s1,int s2,int s3)
{
int total;
total=s1+s2+s3;
printf("\nTotal Marks = %d / 300",total);
calculatepercentage(total);
}
void calculatepercentage(int total)
{
double per;
per=(double)(total/300.0f)*100;
printf("\nPercentage = %lf %",per);
calculategrade(per);
}
void calculategrade(double per)
{
if (per>=75)
printf("\n Grade : Distinction");
else if(per<75 && per>=40)
printf("\nGrade : First Division");
else
printf("\nFailed");
}
int main()
{
int s1,s2,s3;
printf("enter marks of 3 subjects : ");
scanf("%d%d%d",&s1,&s2,&s3);
calculatetotal(s1,s2,s3);
return 0;
}
| true |
8a15cf96c2dcccefa6d0346bbf9b7b8e9267ef62 | C++ | PortfolioJohannOstero/Console-Solitaire | /ConsoleRPG/UIContainer.cpp | UTF-8 | 1,773 | 2.890625 | 3 | [] | no_license | #include "UIContainer.h"
#include "Bounds.h"
#include "Vector2.h"
#include "View.h"
#include "AsciiTexture.h"
const rchar UIContainer::BORDER[]{ L"╔╗╚╝═║ " };
// @ Construction
UIContainer::UIContainer(const Vector2& position, int width, int height, UIAlignment alignment, bool border, UIComponent* parent)
: UIComponent(position, alignment, parent)
{
if (!border)
mTexture = new AsciiTexture(width, height, BORDER[FILL_INDEX]);
else
ConstructBorder(width, height);
}
UIContainer::UIContainer(const UIContainer& cpy) : UIComponent(cpy)
{
mTexture = new AsciiTexture(*cpy.mTexture);
}
UIContainer::~UIContainer()
{
delete mTexture;
mTexture = nullptr;
}
// @ Virtual
void UIContainer::Render(View& window)
{
if(GetIsActive())
window.FillBuffer(GetTransformedPosition(), *mTexture);
}
// @ Getters
Bounds UIContainer::GetBoundary() const
{
return mTexture->GetBoundary();
}
// @ Helper method
void UIContainer::ConstructBorder(int width, int height)
{
const int size = width * height;
rchar* container = new rchar[size];
wmemset(container, BORDER[FILL_INDEX], size);
/// edges - horizontal
int ht = 1;
int hb = (height * width) - width;
for (; ht < width; ht++, hb++)
{
container[ht] = BORDER[H_INDEX];
container[hb] = BORDER[H_INDEX];
}
/// edges - vertical
for (int y = 1; y < height-1; y++)
{
const int vl = width * y;
const int vr = width * y + width-1;
container[vl] = BORDER[V_INDEX];
container[vr] = BORDER[V_INDEX];
}
/// corners
container[0] = BORDER[TL_INDEX];
container[width-1] = BORDER[TR_INDEX];
container[height * width - width] = BORDER[BL_INDEX];
container[size-1] = BORDER[BR_INDEX];
mTexture = new AsciiTexture(width, height, container);
delete[] container;
container = nullptr;
}
| true |
ac74e194d01426214713089f70cdb9265a13d776 | C++ | Joco223/SVML | /Compiler/src/Lexer.cpp | UTF-8 | 10,456 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "Lexer.h"
namespace Lexer {
const std::string load_file(std::string& file_path) {
std::ifstream f(file_path.c_str());
if(!f.good()) {
Error_handler::error_out("Error opening file: " + file_path + ".");
return "";
}
std::string content((std::istreambuf_iterator<char>(f)), (std::istreambuf_iterator<char>()));
f.close();
return content;
};
void clean(std::string& input) {
while(input[0] == ' ') {
input.erase(input.begin());
}
while(input[input.length()] == ' ') {
input.erase(input.end());
}
}
bool is_int(const std::string& s) {
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false;
char* p;
strtol(s.c_str(), &p, 10);
return (*p == 0);
}
bool matches_type(std::string type) {
for(auto& i : types) {
if(type == i) {
return true;
}
}
return false;
}
void process_chunk(std::string& chunk, int line, std::vector<token>& tokens, int column, std::string& path, int file_index) {
token t = {-1, line, column, file_index, path, ""};
if(chunk != "") {
if(matches_type(chunk)) {
t = {tt_type, line, column, file_index, path, chunk};
}else if(chunk == "if") {
t = {tt_if, line, column, file_index, path, "if"};
}else if(chunk == "else") {
t = {tt_else, line, column, file_index, path, "else"};
}else if(chunk == "+" || chunk == "-" || chunk == "*" || chunk == "/" || chunk == "%") {
t = {tt_arithmetic, line, column, file_index, path, chunk};
}else if(chunk == "<" || chunk == ">" || chunk == "<=" || chunk == ">=" || chunk == "==" || chunk == "!=") {
t = {tt_logic, line, column, file_index, path, chunk};
}else if(chunk == "while") {
t = {tt_while, line, column, file_index, path, "while"};
}else if(chunk == "return") {
t = {tt_return, line, column, file_index, path, "return"};
}else{
if(is_int(chunk)) {
t = {tt_value, line, column, file_index, path, chunk};
}else{
t = {tt_identifier, line, column, file_index, path, chunk};
}
}
chunk = "";
tokens.push_back(t);
}
}
std::vector<std::vector<std::string>> lines;
int file_count = 0;
std::vector<token> process(std::string& file_path, bool debug) {
const std::string input = load_file(file_path);
std::vector<token> tokens;
if(input == "")
return tokens;
std::string chunk = "";
int line = 1;
auto start = std::chrono::high_resolution_clock::now();
tokens.reserve(input.length());
int since_last_nl = 0;
std::string current_line = "";
int current_file = file_count;
file_count++;
lines.resize(lines.size()+1);
for(int i = 0; i < input.length(); i++) {
if(input[i] != '\n') {
if(input[i] == '\t') {
std::string tmp = " ";
current_line += tmp;
}else{
current_line.push_back(input[i]);
}
}else{
lines[current_file].push_back(current_line);
current_line = "";
}
if(input[i] == ';') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_eoi, line, i - since_last_nl, current_file, file_path, ";"});
}else if(input[i] == '{') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_ocb, line, i - since_last_nl, current_file, file_path, "{"});
}else if(input[i] == '}') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_ccb, line, i - since_last_nl, current_file, file_path, "}"});
}else if(input[i] == '(') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_ob, line, i - since_last_nl, current_file, file_path, "("});
}else if(input[i] == ')') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_cb, line, i - since_last_nl, current_file, file_path, ")"});
}else if(input[i] == '[') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_osb, line, i - since_last_nl, current_file, file_path, "["});
}else if(input[i] == ']') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_csb, line, i - since_last_nl, current_file, file_path, "]"});
}else if(input[i] == ',') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_comma, line, i - since_last_nl, current_file, file_path, ","});
}else if(input[i] == '.') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_point, line, i - since_last_nl, current_file, file_path, "."});
}else if(input[i] == '=') {
if(input[i + 1] == '=') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_logic, line, i - since_last_nl, current_file, file_path, "=="});
i++;
}else{
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_assign, line, i - since_last_nl, current_file, file_path, "="});
}
}else if(input[i] == '+') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_arithmetic, line, i - since_last_nl, current_file, file_path, "+"});
}else if(input[i] == '-') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_arithmetic, line, i - since_last_nl, current_file, file_path, "-"});
}else if(input[i] == '*') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_arithmetic, line, i - since_last_nl, current_file, file_path, "*"});
}else if(input[i] == '/') {
if(input[i + 1] == '/') {
while(i < input.length()-1) {
if(input[i + 1] != '\n') {
i++;
}else{
break;
}
}
}else{
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_arithmetic, line, i - since_last_nl, current_file, file_path, "/"});
}
}else if(input[i] == '%') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_arithmetic, line, i - since_last_nl, current_file, file_path, "%"});
}else if(input[i] == '^') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_arithmetic, line, i - since_last_nl, current_file, file_path, "^"});
}else if(input[i] == '<') {
if(input[i + 1] == '=') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_logic, line, i - since_last_nl, current_file, file_path, "<="});
i++;
}else{
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_logic, line, i - since_last_nl, current_file, file_path, "<"});
}
}else if(input[i] == '>') {
if(input[i + 1] == '=') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_logic, line, i - since_last_nl, current_file, file_path, ">="});
i++;
}else{
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_logic, line, i - since_last_nl, current_file, file_path, ">"});
}
}else if(input[i] == '!' && input[i + 1] == '=') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
tokens.push_back({tt_logic, line, i - since_last_nl, current_file, file_path, "!="});
}else if(input[i] == '@') {
std::string use = "";
i++;
while(i < input.length()-1) {
if(input[i] != ' ') {
use = use + input[i];
i++;
}else{
i++;
break;
}
}
if(use == "use") {
std::string additional_input = "";
while(i < input.length()-1) {
if(input[i] != ';') {
additional_input = additional_input + input[i];
i++;
}else{
break;
}
}
std::vector<token> additional_tokens = process(additional_input, debug);
for(auto& i : additional_tokens)
tokens.push_back(i);
}else{
Error_handler::error_out("Invalid macro: @" + use + " on line: " + std::to_string(line));
tokens.clear();
return tokens;
}
}else if(input[i] == ' ') {
process_chunk(chunk, line, tokens, i - since_last_nl - chunk.length(), file_path, current_file);
}else if(input[i] == '\n') {
since_last_nl = i+1;
line++;
}else if(input[i] != '\t' && input[i] != '\n') {
chunk = chunk + input[i];
}else if(input[i] != '\t') {
std::string tmp = "Invalid token: ";
tmp.push_back(input[i]);
Error_handler::error_part_out(tmp + " on: " + file_path + ":" + std::to_string(i-since_last_nl-1) + ":" + std::to_string(line), i-since_last_nl-1, line, 1, current_file);
tokens.clear();
return tokens;
}
if(i % 300 == 0 && debug) {
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\rLexer: Processing file: " << file_path << " - [";
float percent = (float)(i+1) / (float)input.length();
int filled = ceil(percent * 20);
int empty = 20 - filled;
for(int j = 0; j < filled; j++)
std::cout << '#';
for(int j = 0; j < empty; j++)
std::cout << '-';
std::cout << "] - " << (percent*100) << "%, time left: " << (((double)std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()/(double)(i+1)) * (input.length()-i-1) / 1000) << "s.";
for(int k = 0; k < 20; k++)
std::cout << ' ';
std::cout << '\r';
//start = std::chrono::high_resolution_clock::now();
}
}
if(debug) {
std::cout << "\rLexer: Processing file: " << file_path << " - [";
for(int j = 0; j < 20; j++)
std::cout << '#';
std::cout << "] - " << 100 << "%, time left: 0s.";
for(int k = 0; k < 20; k++)
std::cout << ' ';
std::cout << '\n';
}
return tokens;
}
}
| true |
6966bb6b8c4187ee17a3d793abbd4be32946d953 | C++ | gtagency/buzzmobile-old | /processors/lane_classifier/include/image.h | UTF-8 | 2,068 | 2.71875 | 3 | [] | no_license | #ifndef __IMAGE_H
#define __IMAGE_H
#include "opencv/cv.h"
#include "instance.h"
using namespace cv;
namespace image {
int getCvType();
extern void (*getFeatures)(const Point3_<uchar>* pt, uchar features[2]);
Instance makeInstance(uchar imgFeatures[2], int pixelDist, int label);
Instance makeInstance(uchar imgFeatures[2], int label);
void getLightInvariantBGR(const Mat& bgr, Mat& libgr);
void maskImageByDensity(Mat& img);
template <typename Labeler>
void extractInstances(const Mat& lab, int startRow, int endRow, int data[3], Labeler labeler, std::vector<Instance>& instances) {
uchar features[2];
for(int row = startRow; row < endRow; ++row) {
const Point3_<uchar> *p = lab.ptr<Point3_<uchar> > (row);
//cout << "Row: " << row << endl;
//assumes CV_8UC3 LAB color image, with 3 values per pixel
for(int col = 0; col < lab.cols; ++col, ++p) {
//throw away the L
// if (col < inLaneStart) {
// continue;
// }
getFeatures(p, features);
uchar lbl = labeler(row, col);
int pixelDist = 0; //abs(col - inLaneStart);
instances.push_back(makeInstance(features, pixelDist, lbl));
if (data[0] < features[0]) data[0] = features[0];
if (data[1] < features[1]) data[1] = features[1];
if (data[2] < pixelDist) data[2] = pixelDist;
}
}
}
template <typename Labeler>
std::vector<Instance> extractInstances(const Mat& lab, int data[3], Labeler labeler) {
std::vector<Instance> instances;
int trainingTenth = 5;
int trainRow = lab.rows * trainingTenth / 20;
int trainRowLast = lab.rows * (trainingTenth + 1) / 20;
instances.reserve((lab.rows / 10) * (1 + lab.cols));
// memset(data, 0, 3 * sizeof(int));
extractInstances(lab, lab.rows * 10/20, lab.rows * 11/20, data, labeler, instances);
extractInstances(lab, lab.rows * 14/20, lab.rows * 15/20, data, labeler, instances);
return instances;
}
}
#endif
| true |
0c5626e04f1937d514ff7c244b83483c9997bb36 | C++ | Mnvjhamb/CodeQuotient-Cpp | /binaryTree/recursive_Inorder_Preorder_Postorder.cpp | UTF-8 | 541 | 3.609375 | 4 | [] | no_license | /* struct Node
{
int data;
Node *left, *right;
};
The above structure is used for tree node.
*/
void inorder(Node* root){
if(root == NULL) return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void preorder(Node* root){
// Write your code here
if(root == NULL) return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(Node* root){
// Write your code here
if(root == NULL) return;
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
} | true |
0ed935089e2e123ab3e24bf273fece409d4b35e7 | C++ | jingweixi233/OnlineJudge_SJTU | /quickSort.cpp | UTF-8 | 1,005 | 3.25 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
void quickSort(int a[], int l, int r){
int i, j, x;
if(l < r){
i = l;
j = r;
x = a[l];
while(i < j){
while(i < j && a[j] > x){
j = j - 1;
}
if(i < j){
a[i] = a[j];
i = i + 1;
}
while(i < j && a[i] < x){
i = i + 1;
}
if(i < j){
a[j] = a[i];
j = j - 1;
}
}
a[i] = x;
quickSort(a, l, i - 1);
quickSort(a, i + 1, r);
}
}
int main(){
int a[100];
int i;
srand(time(NULL));
for(i = 0; i < 100; i++){
a[i] = rand() %100;
}
for(i = 0; i < 100; i++){
cout << a[i] << " ";
}
cout << endl;
quickSort(a, 0, 99);
for(i = 0; i < 100; i++){
cout << a[i] << " ";
}
cout << endl;
}
| true |
c1fc7d470605b4a1eb3386cb9b8745ccb66782ab | C++ | gari3008ma/Algo-Wiki | /Graph/maxflow.cpp | UTF-8 | 2,072 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool bfsutil(vector<vector<pair<int,int> > > graph,int parent[],int n)
{
bool visited[n+1];
int i;
memset(visited,false,sizeof(visited));
queue<int> q;
q.push(0);
visited[0]=true;
parent[0]=-1;
vector<vector<int,int> > :: iterator it;
while(!q.empty())
{
int s=q.front();
q.pop();
for(i=0;i<graph[s].size();i++)
{
if(visited[graph[s][i].first]==false &&(graph[s][i].second)>0)
{
q.push(graph[s][i].first);
visited[graph[s][i].first]=true;
parent[graph[s][i].first]=s;
}
}
}
return visited[n-1];
}
int main()
{
int t,i,j,n,m,u,v,w;
cin>>t;
while(t--)
{
vector<vector<pair<int,int> > > graph;
cin>>n>>m;
graph.resize(n+1);
while(m--)
{
cin>>u>>v>>w;
graph[u-1].push_back(make_pair(v-1,w));
graph[v-1].push_back(make_pair(u-1,w));
}
int parent[n+1];
int max_flow=0;
while(bfsutil(graph,parent,n))
{
int path_flow = INT_MAX;
for (v=n-1; v!=0; v=parent[v])
{
u = parent[v];
for(i=0;i<graph[u].size();i++)
{
if(graph[u][i].first==v)
{
path_flow = min(path_flow, graph[u][i].second);
}
}
}
for (v=n-1; v != 0; v=parent[v])
{
u = parent[v];
for(i=0;i<graph[u].size();i++)
{
if(graph[u][i].first==v)
{
graph[u][i].second -= path_flow;
for(i=0;i<graph[v].size();i++)
{
if(graph[v][i].first==u)
{
graph[v][i].second += path_flow;
}
}
}
}
}
max_flow += path_flow;
cout<<"Hello";
}
cout<<max_flow<<"\n";
}
return 0;
} | true |
ba8de9c173c2a32bbf1883ef71d45526c06814a4 | C++ | Fikridzz/1435 | /jpierceLab13/search.cpp | UTF-8 | 6,698 | 3.6875 | 4 | [] | no_license | //********************************************************************
//Name: Jp Pierce
//Class: COSC 1435.001
//Instructor: Marwa Hassan
//Lab 13 Problem 2
//Date: 4/16/2012
//Program description: Search takes a list of of numbers from a file and
// makes it into an array. That array is then sorted from acsending order
// using the selection sort method. It then allows the user to request
// the location of a specific number, it then returns which element subscript
// it's at in the array.
//*********************************************************************
#include<iostream>
#include<string>
#include<fstream>
#include<cstring>
#include <cstdlib>
#include<iomanip>
using namespace std;
void showArray(int[], int);
void selectionSort(int [], int);
int binarySearch(int [], int , int);
void swap(int [], int, int);
int findMin(int [], int, int);
const int SIZE = 40; //couldn't use any number over 40 or
//else i got garbage? Couldn't find a
// reasonable reason.
int main()
{
int array [SIZE];
int count = 0;
ifstream inputFile;
string filename;
int value, result;
//to find the median VALUE in the array
// program finds the middle supsrcipt of the
//array and outputs the value;
int median;
median = SIZE/2;
//opening the file user enters
cout << "Enter the filename: ";
cin >> filename;
inputFile.open (filename.c_str());
cout<<"-----------------------------------------"<<endl;
if (inputFile)
{
while(count < SIZE && inputFile >> array[count])
count++;
cout << "There are "<< count <<" values in the array: "<<endl;
cout<<"-----------------------------------------"<<endl;
//outputs the unordered array
showArray(array, SIZE);
}
//loop until user opens a correct file
else
{
while(!(inputFile))
{
cout << "Error opening file " <<filename<<endl;
cout << "Re-enter the filename: ";
cin >> filename;
inputFile.open (filename.c_str());
}
while(count < SIZE && inputFile >> array[count])
count++;
showArray(array, SIZE);
}
inputFile.close();
cout<<" "<<endl;
cout<<"-----------------------------------------"<<endl;
cout<<"Now to sort the array is ascending order: "<<endl;
cout<<"-----------------------------------------"<<endl;
//Selection Sort function orders the array
// from least to greatest, using 2 functions
// in the process.
selectionSort(array, SIZE);
showArray(array, SIZE);
cout<<"-----------------------------------------"<<endl;
cout<<"The Median of the data set is: "<< array[median] << endl;
cout<<"-----------------------------------------"<<endl;
cout<<"Enter the number you're looking for: ";
cin >> value;
//Binary Search Function
result = binarySearch(array, SIZE, value);
//loop if user enters a number not in the array
if(result == -1 )
{
while(result == -1)
{
cout<<"That number doesn't exist in the array."<<endl;
cout<<"Enter the number you're looking for: ";
cin >> value;
result = binarySearch(array, SIZE, value);
}
}
else
{
cout<<"-----------------------------------------"<<endl;
cout<<"The Number " <<value<<" is found at element " << result;
cout<< " in the array."<<endl;
cout<<"-----------------------------------------"<<endl;
}
return 0;
}
//*************************************************
// binarySearch function
// This function finds a target value in a ordered
// array.
//
// Return Value
// ------------
// int Subscript number where target
// value is located at in array.
//
// Parameters
// ------------
// int a[] array
// int SIZE SIZE of array
// int target user target value
//*************************************************
int binarySearch(int a[],int size,int target)
{
int first =0,
last = size -1,
middle,
position = -1;
bool found = false;
while(!found && first<=last)
{
middle = (first + last) /2;
if(a[middle] == target)
{
found = true;
position = middle;
}
else if(a[middle] > target)
last = middle -1;
else if(a[middle] < target)
first = middle +1;
}
return position;
}
//*************************************************
// showArray function
// This function outputs the array
//
// Return Value
// ------------
// void
//
// Parameters
// ------------
// int a[] array
// int SIZE SIZE of array
//*************************************************
void showArray(int array[], int size)
{
for(int count = 0; count < size; count++)
cout << array[count] << " " << endl;
}
//*************************************************
// swap function
// This function swaps the values of two numbers using
// a temporary number to store in
//
// Return Value
// ------------
// void
//
// Parameters
// ------------
// int a[] array
// int x represents 1st subscript to be swapped
// int y represents 2ns subscript to be swapped
//*************************************************
void swap(int a[], int x, int y)
{
int temp;
temp = a[x];
a[x] = a[y];
a[y] = temp;
}
//*************************************************
// findMin function
// This function finds the smallest value in a array
//
// Return Value
// ------------
// int smallest smallest value in array
//
// Parameters
// ------------
// int a[] array
// int SIZE SIZE of array
// int i incrementor
//*************************************************
int findMin(int a[], int size, int i)
{
int smallest, j;
smallest = i;
j = i + 1;
while(j < size)
{
if(a[j] < a[smallest])
smallest = j;
j = j + 1;
}
return smallest;
}
//*************************************************
// selectionSort function
// This function finds the target value entered by the
// user. It uses 2 other function (swap, findMin) to
// do it's dirty work. Then returns the location of the
// target element subscript.
//
// Return Value
// ------------
// void
//
// Parameters
// ------------
// int a[] array
// int SIZE SIZE of array
//*************************************************
void selectionSort(int a[], int size)
{
int i = 0, unsorted;
while(i<size)
{
unsorted = findMin(a, size, i);
swap(a , i , unsorted);
i = i +1;
}
}
| true |
d965cc30573b437103b2e95985644c1826f272ed | C++ | sureshyhap/Schaums-Outlines-Data-Structures-with-C-plus-plus | /Second/Chapter 4/Problems/34/thirtyfour.cpp | UTF-8 | 309 | 3.390625 | 3 | [] | no_license | #include <iostream>
double tangent(double x);
double tangent(double x) {
if (x > -.005 and x < .005) {
return x + (1 / 3) * (x * x * x);
}
return (2 * tangent(x / 2)) / (1 - (tangent(x / 2) * tangent(x / 2)));
}
int main(int argc, char* argv[]) {
std::cout << tangent(5) << '\n';
return 0;
}
| true |
662d41ce9a4725cfafbd187a91d25f1ca7fb8844 | C++ | ItemZheng/PAT_Advanced_Level_Answer | /1013.cpp | UTF-8 | 1,426 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <vector>
// 注意点:只要将lose city去掉之后,然后计算剩下的城市有几个set就可以
using namespace std;
class Edge{
public:
int v1, v2;
public:
Edge(int v1, int v2){
this->v1 = v1 - 1;
this->v2 = v2 - 1;
}
};
int root_of(int city_set[], int i){
while (city_set[i] >= 0){
i = city_set[i];
}
return i;
}
int main(){
int N, M, K;
cin >> N >> M >> K;
vector<Edge *> edges;
for(int i = 0; i < M; i++){
int v1, v2;
cin >> v1 >> v2;
Edge * e = new Edge(v1, v2);
edges.push_back(e);
}
// K cases
for(int i = 0; i < K; i++){
int city_set[N];
for(int j = 0; j < N; j++){
city_set[j] = -1;
}
int lose_city;
cin >> lose_city;
lose_city--;
// Merge City
for(int j = 0; j < edges.size(); j++){
Edge *e = edges[j];
if(e->v1 == lose_city || e->v2 == lose_city){
continue;
}
int r1 = root_of(city_set, e->v1), r2 = root_of(city_set, e->v2);
if(r1 == r2){
continue;
}
city_set[r2] = r1;
}
int count = 0;
for(int j = 0; j < N; j++){
if(city_set[j] < 0){
count++;
}
}
cout << count - 2 << endl;
}
} | true |
d2fcea5d82966dae26f012f8523a28fe33a6f5a8 | C++ | rvt/bbq-controller | /lib/utils/propertyutils.h | UTF-8 | 4,273 | 3.109375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <stdint.h>
#include <map>
#include <Stream.h>
class Properties;
class PropertyValue {
private:
union {
int32_t m_long;
float m_float;
std::string m_string;
bool m_bool;
};
friend class Properties;
public:
enum Type {
LONG,
FLOAT,
STRING,
BOOL,
EMPTY
} m_type;
explicit PropertyValue();
explicit PropertyValue(int32_t p_long);
explicit PropertyValue(const char* p_char);
explicit PropertyValue(const std::string& p_string);
explicit PropertyValue(float p_float);
explicit PropertyValue(bool p_bool);
virtual ~PropertyValue();
PropertyValue(const PropertyValue& val);
PropertyValue& operator=(const PropertyValue& val);
void copy(const PropertyValue&);
void destroy();
// Create a long properety from string
static PropertyValue longProperty(const char* p_char);
// Create a float property from string
static PropertyValue floatProperty(const char* p_char);
// Create a bool property from string
static PropertyValue boolProperty(const char* p_char);
bool asBool() const;
float asFloat() const;
long asLong() const;
Type type() const;
static Type charToType(char type);
//////////////////////////////////////////////////////////////////
operator const char* () const;
/**
* Get the float value from any type
* float: use value itself
* bool: returns 1.0f or 0.0f
* char: uses atof(..)
* long: standard cast
*/
operator float() const;
/**
* Get the bool value from any type
* float: returns false when value was 0.0f
* bool: value itself
* char: uses PropertyValue::boolProperty(m_char).getBool();
* long: 0 for false
*/
operator bool() const;
/**
* Get the long value from any type
* float: use std::lsround(..). overflows undefined behavior
* bool: returns 1 or 0
* char: uses atol(..)
* long: value itself
*/
operator long() const;
operator int16_t() const {
return (long) * this;
}
operator int32_t() const {
return (long) * this;
}
operator char() const {
return (long) * this;
}
};
class Properties {
private:
std::map<std::string, const PropertyValue> m_type;
public:
template<std::size_t desiredCapacity>
friend void serializeProperties(Stream& device, Properties& properties, bool showPassword);
template<std::size_t desiredCapacity>
friend void serializeProperties(Stream& device, Properties& properties);
template<std::size_t desiredCapacity>
friend void deserializeProperties(Stream& device, Properties& properties);
void erase(const std::string& p_entry);
void put(const std::string& p_entry, const PropertyValue& value);
void put(const char* p_entry, const PropertyValue& value);
bool putNotContains(const std::string& p_entry, const PropertyValue& value);
bool putNotContains(const char* p_entry, const PropertyValue& value);
const PropertyValue& get(const std::string& p_entry) const;
bool contains(const std::string& p_entry) const;
private:
char* stripWS_LT(char* str);
char* getNextNonSpaceChar(char* buffer);
void serializeProperties(char* v, size_t desiredCapacity, Stream& device, bool showPassword);
void deserializeProperties(char* buffer, size_t desiredCapacity, Stream& device);
};
template<std::size_t desiredCapacity>
void serializeProperties(Stream& device, Properties& p, bool showPassword) {
static_assert(desiredCapacity > 0, "Must be > 0");
char buffer[desiredCapacity];
p.serializeProperties(buffer, desiredCapacity, device, showPassword);
}
template<std::size_t desiredCapacity>
void serializeProperties(Stream& device, Properties& p) {
static_assert(desiredCapacity > 0, "Must be > 0");
char buffer[desiredCapacity];
p.serializeProperties(buffer, desiredCapacity, device, true);
}
template<std::size_t desiredCapacity>
void deserializeProperties(Stream& device, Properties& p) {
static_assert(desiredCapacity > 0, "Must be > 0");
char buffer[desiredCapacity];
p.deserializeProperties(buffer, desiredCapacity, device);
} | true |
9ebdb925cbf144a9cbec467b4d8380cddddbc53d | C++ | vuonghung2308/CTDL | /contest2/notGreen/ex32.cpp | UTF-8 | 942 | 3.03125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool isOk(string s) {
if(s == "")
return false;
int x = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '(') x++;
else if(s[i] == ')') x--;
if(x < 0) return false;
}
return x == 0;
}
void remove(string s, bool &has) {
queue<string> q;
set<string> visit;
visit.insert(s);
q.push(s);
bool level = false;
while(!q.empty()) {
string str = q.front();
q.pop();
if(isOk(str)) {
has = true;
cout << str << ' ';
level = true;
}
if(level) continue;
for(int i = 0; i < str.length(); i++) {
if(str[i] == '(' || str[i] == ')') {
string temp = str.substr(0, i) + str.substr(i+1);
if(visit.find(temp) == visit.end()) {
q.push(temp);
visit.insert(temp);
}
}
}
}
}
int main() {
int t; cin >> t;
for(int i = 0; i < t; i++) {
string s; cin >> s;
bool has = false;
remove(s, has);
if(!has) cout << "-1";
cout << endl;
}
}
| true |
6909ecab21198e91fd4aa9cace762de812d4bb45 | C++ | Adelost/Ultimate-Coffee | /Source/System_Render/Box.h | UTF-8 | 7,698 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Vertex.h"
namespace Shape
{
Vector3 BoxPos[8] =
{ //Index:
Vector3( 0.5f, 0.5f, 0.5f), //0
Vector3( 0.5f, -0.5f, 0.5f), //1
Vector3(-0.5f, -0.5f, 0.5f), //2
Vector3(-0.5f, 0.5f, 0.5f), //3
Vector3( 0.5f, 0.5f, -0.5f), //4
Vector3( 0.5f, -0.5f, -0.5f), //5
Vector3(-0.5f, -0.5f, -0.5f), //6
Vector3(-0.5f, 0.5f, -0.5f), //7
};
Vector4 BoxColor[8] =
{ //Index:
Vector4(1.0f, 1.0f, 1.0f, 1.0f), //0
Vector4(1.0f, 0.0f, 0.0f, 1.0f), //1
Vector4(0.0f, 1.0f, 0.0f, 1.0f), //2
Vector4(0.0f, 0.0f, 1.0f, 1.0f), //3
Vector4(0.0f, 1.0f, 1.0f, 1.0f), //4
Vector4(1.0f, 1.0f, 0.0f, 1.0f), //5
Vector4(1.0f, 0.0f, 1.0f, 1.0f), //6
Vector4(0.0f, 0.0f, 0.0f, 1.0f), //7
};
Vector3 BoxNormal[8] =
{
Vector3( 0.0f, 1.0f, 0.0f), // 0, Up
Vector3( 0.0f, -1.0f, 0.0f), // 1, Down
Vector3( 1.0f, 0.0f, 0.0f), // 2, Right
Vector3(-1.0f, 0.0f, 0.0f), // 3, Left
Vector3( 0.0f, 0.0f, -1.0f), // 4, Back
Vector3( 0.0f, 0.0f, 1.0f), // 5, Front
};
VertexPosColNorm BoxVertices[36] =
{
// Front
{BoxPos[2], BoxColor[2], BoxNormal[5]},
{BoxPos[1], BoxColor[1], BoxNormal[5]},
{BoxPos[0], BoxColor[0], BoxNormal[5]},
{BoxPos[0], BoxColor[0], BoxNormal[5]},
{BoxPos[3], BoxColor[3], BoxNormal[5]},
{BoxPos[2], BoxColor[2], BoxNormal[5]},
// Back
{BoxPos[5], BoxColor[5], BoxNormal[4]},
{BoxPos[6], BoxColor[6], BoxNormal[4]},
{BoxPos[7], BoxColor[7], BoxNormal[4]},
{BoxPos[7], BoxColor[7], BoxNormal[4]},
{BoxPos[4], BoxColor[4], BoxNormal[4]},
{BoxPos[5], BoxColor[5], BoxNormal[4]},
// Right
{BoxPos[1], BoxColor[1], BoxNormal[2]},
{BoxPos[5], BoxColor[5], BoxNormal[2]},
{BoxPos[4], BoxColor[4], BoxNormal[2]},
{BoxPos[4], BoxColor[4], BoxNormal[2]},
{BoxPos[0], BoxColor[0], BoxNormal[2]},
{BoxPos[1], BoxColor[1], BoxNormal[2]},
// Left
{BoxPos[6], BoxColor[6], BoxNormal[3]},
{BoxPos[2], BoxColor[2], BoxNormal[3]},
{BoxPos[3], BoxColor[3], BoxNormal[3]},
{BoxPos[3], BoxColor[3], BoxNormal[3]},
{BoxPos[7], BoxColor[7], BoxNormal[3]},
{BoxPos[6], BoxColor[6], BoxNormal[3]},
// Up
{BoxPos[3], BoxColor[3], BoxNormal[0]},
{BoxPos[0], BoxColor[0], BoxNormal[0]},
{BoxPos[4], BoxColor[4], BoxNormal[0]},
{BoxPos[4], BoxColor[4], BoxNormal[0]},
{BoxPos[7], BoxColor[7], BoxNormal[0]},
{BoxPos[3], BoxColor[3], BoxNormal[0]},
// Down
{BoxPos[6], BoxColor[6], BoxNormal[1]},
{BoxPos[5], BoxColor[5], BoxNormal[1]},
{BoxPos[1], BoxColor[1], BoxNormal[1]},
{BoxPos[1], BoxColor[1], BoxNormal[1]},
{BoxPos[2], BoxColor[2], BoxNormal[1]},
{BoxPos[6], BoxColor[6], BoxNormal[1]},
};
//VertexPosColNorm BoxVerticesNormals[36] =
//{
// // Front
// {Vector3( 0.5f, 0.5f, 0.5f), Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector3( 0.0f, 0.0f, -1.0f)},
// {Vector3( 0.5f, -0.5f, 0.5f), Vector4(1.0f, 0.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, -1.0f)},
// {Vector3(-0.5f, -0.5f, 0.5f), Vector4(0.0f, 1.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, -1.0f)},
//
// {Vector3(-0.5f, -0.5f, 0.5f), Vector4(0.0f, 1.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, -1.0f)},
// {Vector3(-0.5f, 0.5f, 0.5f), Vector4(0.0f, 0.0f, 1.0f, 1.0f), Vector3( 0.0f, 0.0f, -1.0f)},
// {Vector3( 0.5f, 0.5f, 0.5f), Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector3( 0.0f, 0.0f, -1.0f)},
//
// // Back
// {Vector3(-0.5f, 0.5f, -0.5f), Vector4(0.0f, 0.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, 1.0f)},
// {Vector3(-0.5f, -0.5f, -0.5f), Vector4(1.0f, 0.0f, 1.0f, 1.0f), Vector3( 0.0f, 0.0f, 1.0f)},
// {Vector3( 0.5f, -0.5f, -0.5f), Vector4(1.0f, 1.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, 1.0f)},
//
// {Vector3( 0.5f, -0.5f, -0.5f), Vector4(1.0f, 1.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, 1.0f)},
// {Vector3( 0.5f, 0.5f, -0.5f), Vector4(0.0f, 1.0f, 1.0f, 1.0f), Vector3( 0.0f, 0.0f, 1.0f)},
// {Vector3(-0.5f, 0.5f, -0.5f), Vector4(0.0f, 0.0f, 0.0f, 1.0f), Vector3( 0.0f, 0.0f, 1.0f)},
// // Right
// {Vector3( 0.5f, 0.5f, -0.5f), Vector4(0.0f, 1.0f, 1.0f, 1.0f), Vector3( 1.0f, 0.0f, 0.0f)},
// {Vector3( 0.5f, -0.5f, -0.5f), Vector4(1.0f, 1.0f, 0.0f, 1.0f), Vector3( 1.0f, 0.0f, 0.0f)},
// {Vector3( 0.5f, -0.5f, 0.5f), Vector4(1.0f, 0.0f, 0.0f, 1.0f), Vector3( 1.0f, 0.0f, 0.0f)},
//
// {Vector3( 0.5f, -0.5f, 0.5f), Vector4(1.0f, 0.0f, 0.0f, 1.0f), Vector3( 1.0f, 0.0f, 0.0f)},
// {Vector3( 0.5f, 0.5f, 0.5f), Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector3( 1.0f, 0.0f, 0.0f)},
// {Vector3( 0.5f, 0.5f, -0.5f), Vector4(0.0f, 1.0f, 1.0f, 1.0f), Vector3( 1.0f, 0.0f, 0.0f)},
//
// // Left
// {Vector3(-0.5f, 0.5f, 0.5f), Vector4(0.0f, 0.0f, 1.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f)},
// {Vector3(-0.5f, -0.5f, 0.5f), Vector4(0.0f, 1.0f, 0.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f)},
// {Vector3(-0.5f, -0.5f, -0.5f), Vector4(1.0f, 0.0f, 1.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f)},
//
// {Vector3(-0.5f, -0.5f, -0.5f), Vector4(1.0f, 0.0f, 1.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f)},
// {Vector3(-0.5f, 0.5f, -0.5f), Vector4(0.0f, 0.0f, 0.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f)},
// {Vector3(-0.5f, 0.5f, 0.5f), Vector4(0.0f, 0.0f, 1.0f, 1.0f), Vector3(-1.0f, 0.0f, 0.0f)},
//
// // Up
// {Vector3( 0.5f, 0.5f, -0.5f), Vector4(0.0f, 1.0f, 1.0f, 1.0f), Vector3( 0.0f, -1.0f, 0.0f)},
// {Vector3( 0.5f, 0.5f, 0.5f), Vector4(1.0f, 1.0f, 1.0f, 1.0f), Vector3( 0.0f, -1.0f, 0.0f)},
// {Vector3(-0.5f, 0.5f, 0.5f), Vector4(0.0f, 0.0f, 1.0f, 1.0f), Vector3( 0.0f, -1.0f, 0.0f)},
//
// {Vector3(-0.5f, 0.5f, 0.5f), Vector4(0.0f, 0.0f, 1.0f, 1.0f), Vector3( 0.0f, -1.0f, 0.0f)},
// {Vector3(-0.5f, 0.5f, -0.5f), Vector4(0.0f, 0.0f, 0.0f, 1.0f), Vector3( 0.0f, -1.0f, 0.0f)},
// {Vector3( 0.5f, 0.5f, -0.5f), Vector4(0.0f, 1.0f, 1.0f, 1.0f), Vector3( 0.0f, -1.0f, 0.0f)},
//
// // Down
// {Vector3( 0.5f, -0.5f, 0.5f), Vector4(1.0f, 0.0f, 0.0f, 1.0f), Vector3( 0.0f, 1.0f, 0.0f)},
// {Vector3( 0.5f, -0.5f, -0.5f), Vector4(1.0f, 1.0f, 0.0f, 1.0f), Vector3( 0.0f, 1.0f, 0.0f)},
// {Vector3(-0.5f, -0.5f, -0.5f), Vector4(1.0f, 0.0f, 1.0f, 1.0f), Vector3( 0.0f, 1.0f, 0.0f)},
//
// {Vector3(-0.5f, -0.5f, -0.5f), Vector4(1.0f, 0.0f, 1.0f, 1.0f), Vector3( 0.0f, 1.0f, 0.0f)},
// {Vector3(-0.5f, -0.5f, 0.5f), Vector4(0.0f, 1.0f, 0.0f, 1.0f), Vector3( 0.0f, 1.0f, 0.0f)},
// {Vector3( 0.5f, -0.5f, 0.5f), Vector4(1.0f, 0.0f, 0.0f, 1.0f), Vector3( 0.0f, 1.0f, 0.0f)},
//};
/////////////////////////////////
//VertexPosCol BoxVertices[8] =
//{ //Index:
// {Vector3( 0.5f, 0.5f, 0.5f), Vector4(1.0f, 1.0f, 1.0f, 1.0f)}, //0
// {Vector3( 0.5f, -0.5f, 0.5f), Vector4(1.0f, 0.0f, 0.0f, 1.0f)}, //1
// {Vector3(-0.5f, -0.5f, 0.5f), Vector4(0.0f, 1.0f, 0.0f, 1.0f)}, //2
// {Vector3(-0.5f, 0.5f, 0.5f), Vector4(0.0f, 0.0f, 1.0f, 1.0f)}, //3
// {Vector3( 0.5f, 0.5f, -0.5f), Vector4(0.0f, 1.0f, 1.0f, 1.0f)}, //4
// {Vector3( 0.5f, -0.5f, -0.5f), Vector4(1.0f, 1.0f, 0.0f, 1.0f)}, //5
// {Vector3(-0.5f, -0.5f, -0.5f), Vector4(1.0f, 0.0f, 1.0f, 1.0f)}, //6
// {Vector3(-0.5f, 0.5f, -0.5f), Vector4(0.0f, 0.0f, 0.0f, 1.0f)}, //7
//};
unsigned int BoxIndex[36] =
{
// Front
0, 1, 2,
2, 3, 0,
// Back
7, 6, 5,
5, 4, 7,
// Right
4, 5, 1,
1, 0, 4,
// Left
3, 2, 6,
6, 7, 3,
// Up
4, 0, 3,
3, 7, 4,
// Down
1, 5, 6,
6, 2, 1,
};
} | true |
eba8361b028e03de73e2ed33c20dd0e34ed2d452 | C++ | 20twenty/kglSN2 | /11try/src/xform.cpp | UTF-8 | 2,056 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unistd.h>
#include <ios>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include "xData.h"
using namespace std;
void process_mem_usage(double& vm_usage, double& resident_set)
{
using std::ios_base;
using std::ifstream;
using std::string;
vm_usage = 0.0;
resident_set = 0.0;
// 'file' stat seems to give the most reliable results
//
ifstream stat_stream("/proc/self/stat",ios_base::in);
// dummy vars for leading entries in stat that we don't care about
//
string pid, comm, state, ppid, pgrp, session, tty_nr;
string tpgid, flags, minflt, cminflt, majflt, cmajflt;
string utime, stime, cutime, cstime, priority, nice;
string O, itrealvalue, starttime;
// the two fields we want
//
unsigned long vsize;
long rss;
stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
>> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
>> utime >> stime >> cutime >> cstime >> priority >> nice
>> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
stat_stream.close();
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage = vsize / 1024.0;
resident_set = rss * page_size_kb;
}
int main(int argc, char** argv) {
if(argc < 8 || argc > 9) {
cerr << "args: <train_file(string)> <test_file(string)> <seed> <train_limit> <test_limit> <group> <groups> <cache_only>" << endl;
return 1;
}
bool cache_only = false;
if(argc == 9) cache_only = (atoi(argv[8]) == 1) ? true : false;
xData* pXD = new xData(argv[1],argv[2],atoi(argv[3]),atoi(argv[4]),atoi(argv[5]),atoi(argv[6]),atoi(argv[7]),cache_only);
if (!pXD->isgood()) return 1;
double vm, rss;
process_mem_usage(vm, rss);
cerr << "VM: " << vm << "; RSS: " << rss << endl;
if(0) {
cerr << "press any key and hit return... ";
string tmp;
cin >> tmp;
}
return 0;
}
| true |
d489710c96aa4eb816be4e3e2dbbdc3fc10924c6 | C++ | moonps/ProblemSolving | /9328_열쇠/은경.cpp | UTF-8 | 4,002 | 2.671875 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
struct DATA {int x,y;};
queue<DATA> q;
queue<DATA> door[28];
int dx[]={0,0,1,-1,}, dy[]={1,-1,0,0};
bool check[102][102];
char arr[102][102];
bool key[102];
char keys[102];
int main(void) {
int t; scanf("%d", &t);
while(t--) {
int h,w,ans=0;
scanf("%d %d", &h, &w);
// 입력을 받습니다
for(int i=1; i<=h; i++) {
for(int j=1; j<=w; j++) {
scanf(" %c", &arr[i][j]);
}
}
// 가지고 있는 열쇠 체크!
scanf("%s", keys);
for(int i=0; i<strlen(keys); i++) {
if (keys[i]=='0') continue;
key[keys[i]-'a']=true;
}
// 테두리를 만든다
for(int j=0; j<=w+1; j++) {
arr[0][j]='.';
arr[h+1][j]='.';
}
for(int i=1; i<=h; i++) {
arr[i][0]='.';
arr[i][w+1]='.';
}
q.push({0,0}); check[0][0]=true;
while(!q.empty()) {
int x=q.front().x;
int y=q.front().y;
q.pop();
for(int k=0; k<4; k++) {
int nx=x+dx[k];
int ny=y+dy[k];
if (0<=nx && nx<=h+1 && 0<=ny && ny<=w+1) {
// 벽이거나 이미 방문했었던 공간이면 무시
if(arr[nx][ny]=='*' || check[nx][ny]) {
continue;
}
// 어차피 아래 모든 곳에 방문하게 되니까 방문처리 먼저 해줌
check[nx][ny]=true;
// 문서이면 줍줍하고 큐에 넣기
if (arr[nx][ny]=='$'){
ans++;
q.push({nx,ny});
}
// 이동할 수 있는 빈 공간이면 큐에 넣기
else if (arr[nx][ny]=='.') {
q.push({nx,ny});
}
// 열쇠면 줍고 큐에 넣고 0으로 만들고 열쇠 가졌따고 표시
else if ('a'<=arr[nx][ny] && arr[nx][ny]<='z') {
q.push({nx,ny});
// 주운 열쇠가 없었던 열쇠면 줍는다
if(key[arr[nx][ny]-'a']==false) {
key[arr[nx][ny]-'a']=true;
// 그리고 해당 열쇠랑 맞는 문을 다 열어준다
while(!door[arr[nx][ny]-'a'].empty()) {
q.push({door[arr[nx][ny]-'a'].front()});
door[arr[nx][ny]-'a'].pop();
}
}
}
// 문이면 가지고 있는 열쇠랑 일치하는지 확인
else if ('A'<=arr[nx][ny] && arr[nx][ny]<='Z') {
// 해당 알파벳에 맞는 키가 존재하면
if(key[arr[nx][ny]-'A']==true) {
q.push({nx,ny}); // 문 위치를 큐에 넣기
}
// 열쇠랑 일치하지 않으면 문 큐에 넣기
else {
door[arr[nx][ny]-'A'].push({nx,ny});
}
}
}
}
}
printf("%d\n", ans);
memset(check,0,sizeof(check));
memset(arr,0,sizeof(arr));
memset(key,false,sizeof(key));
memset(keys,false,sizeof(keys));
for(int i=0; i<28; i++) {
while(!door[i].empty())
door[i].pop();
}
}
return 0;
}
| true |
b593d0563978d3258a42f4aeb940bba18d2fe4dc | C++ | sxs-collaboration/spectre | /tests/Unit/NumericalAlgorithms/LinearOperators/Test_CoefficientTransforms.cpp | UTF-8 | 10,844 | 2.59375 | 3 | [
"MIT"
] | permissive | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <array>
#include <cstddef>
#include <vector>
#include "DataStructures/ComplexDataVector.hpp"
#include "DataStructures/ComplexModalVector.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/IndexIterator.hpp"
#include "DataStructures/ModalVector.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Framework/TestHelpers.hpp"
#include "Helpers/DataStructures/MakeWithRandomValues.hpp"
#include "NumericalAlgorithms/LinearOperators/CoefficientTransforms.hpp"
#include "NumericalAlgorithms/Spectral/LogicalCoordinates.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "NumericalAlgorithms/Spectral/Spectral.hpp"
#include "Utilities/Algorithm.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Math.hpp"
// These tests generate a function `u_nodal_expected` from a linear
// superposition of the basis functions, which are then transformed to spectral
// space (`u_modal`). The coefficients are compared to their expected values,
// which is 1 if the coefficient is specified in `coeffs_to_include` and 0
// otherwise. Finally, the modal coefficients are transformed back to the nodal
// coefficients and compared to `u_nodal_expected`.
namespace {
template <typename ModalVectorType, typename NodalVectorType,
Spectral::Basis Basis, Spectral::Quadrature Quadrature, size_t Dim>
void check_transforms(
const Mesh<Dim>& mesh,
const std::vector<std::array<size_t, Dim>>& coeffs_to_include) {
CAPTURE(Basis);
CAPTURE(Quadrature);
CAPTURE(mesh);
CAPTURE(coeffs_to_include);
MAKE_GENERATOR(generator);
UniformCustomDistribution<
tt::get_fundamental_type_t<typename ModalVectorType::ElementType>>
dist{0.5, 2.0};
const auto basis_factor =
make_with_random_values<typename ModalVectorType::ElementType>(
make_not_null(&generator), make_not_null(&dist));
// Construct a functions:
//
// 1D: u(\xi) = sum_i c_i phi_i(\xi)
// 2D: u(\xi,\eta) = sum_{i,j} c_{i,j} phi_i(\xi) phi_j(\eta)
// 3D: u(\xi,\eta,\zeta) = sum_{i,j,k} c_{i,j,k} phi_i(\xi)
// phi_j(\eta) phi_k(\zeta)
//
// where the coefficients c_{i,j,k} are 1 if listed in `coeffs_to_include` and
// 0 otherwise.
const auto logical_coords = logical_coordinates(mesh);
NodalVectorType u_nodal_expected(mesh.number_of_grid_points(), 0.0);
for (const auto& coeff : coeffs_to_include) {
// additional * 1.0 in appropriate type necessary for being generic to
// complex values
NodalVectorType basis_function =
basis_factor * Spectral::compute_basis_function_value<Basis>(
coeff[0], get<0>(logical_coords));
for (size_t dim = 1; dim < Dim; ++dim) {
basis_function *= typename ModalVectorType::ElementType{1.0} *
Spectral::compute_basis_function_value<Basis>(
gsl::at(coeff, dim), logical_coords.get(dim));
}
u_nodal_expected += basis_function;
}
// Transform to modal coefficients and check their values
const ModalVectorType u_modal = to_modal_coefficients(u_nodal_expected, mesh);
for (IndexIterator<Dim> index_it(mesh.extents()); index_it; ++index_it) {
CAPTURE(*index_it);
if (alg::found(coeffs_to_include, index_it->indices())) {
CHECK_COMPLEX_APPROX(u_modal[index_it.collapsed_index()], basis_factor);
} else {
CHECK_COMPLEX_APPROX(u_modal[index_it.collapsed_index()],
typename ModalVectorType::ElementType{0.0});
}
}
// Back to nodal coefficients, which should match what we set up initially
const NodalVectorType u_nodal = to_nodal_coefficients(u_modal, mesh);
CHECK_ITERABLE_APPROX(u_nodal_expected, u_nodal);
}
template <typename ModalVectorType, typename NodalVectorType,
Spectral::Basis Basis, Spectral::Quadrature Quadrature,
typename Generator>
void test_1d(const gsl::not_null<Generator*> generator) {
UniformCustomDistribution<size_t> dist{
1, Spectral::maximum_number_of_points<Basis> - 1};
const size_t order = dist(*generator);
// Start at 1st order so we are independent of the minimum number of
// coefficients.
CAPTURE(order);
const Mesh<1> mesh(order + 1, Basis, Quadrature);
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order}}, {{order / 2}}});
if (order > 4) {
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order}}, {{order / 3}}});
}
}
template <typename ModalVectorType, typename NodalVectorType,
Spectral::Basis Basis, Spectral::Quadrature Quadrature,
typename Generator>
void test_2d(const gsl::not_null<Generator*> generator) {
// Start at one higher order so we can drop one order in the y-direction.
UniformCustomDistribution<size_t> dist{
Spectral::minimum_number_of_points<Basis, Quadrature> + 1,
Spectral::maximum_number_of_points<Basis> - 1};
const size_t order = dist(*generator);
CAPTURE(order);
const Mesh<2> mesh({{order + 1, order}}, Basis, Quadrature);
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order, order - 1}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order, order - 1}}, {{order / 2, order / 2}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
Mesh<2>{{{order + 1, order + 1}}, Basis, Quadrature},
{{{order - 1, order}}, {{order / 2, order / 2}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
Mesh<2>{{{order + 1, order + 1}}, Basis, Quadrature},
{{{order, order}}, {{order / 2, order / 2}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order, order - 1}}, {{order / 3, order / 3}}});
}
template <typename ModalVectorType, typename NodalVectorType,
Spectral::Basis Basis, Spectral::Quadrature Quadrature,
typename Generator>
void test_3d(const gsl::not_null<Generator*> generator) {
// Start at two orders higher so we can drop one order in the y-direction and
// two in z-direction.
UniformCustomDistribution<size_t> dist{
Spectral::minimum_number_of_points<Basis, Quadrature> + 2,
Spectral::maximum_number_of_points<Basis> - 2};
const size_t order = dist(*generator);
CAPTURE(order);
const Mesh<3> mesh({{order + 1, order, order - 1}}, Basis, Quadrature);
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh, {{{order, order - 1, order - 2}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh,
{{{order, order - 1, order - 2}}, {{order / 2, order / 2, order / 2}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
Mesh<3>{{{order + 1, order + 1, order + 1}}, Basis, Quadrature},
{{{order, order, order}}});
check_transforms<ModalVectorType, NodalVectorType, Basis, Quadrature>(
mesh,
{{{order, order - 1, order - 2}}, {{order / 3, order / 3, order / 3}}});
}
} // namespace
SPECTRE_TEST_CASE("Unit.Numerical.LinearOperators.CoefficientTransforms",
"[NumericalAlgorithms][LinearOperators][Unit]") {
MAKE_GENERATOR(generator);
test_1d<ModalVector, DataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_1d<ModalVector, DataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_2d<ModalVector, DataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_2d<ModalVector, DataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_3d<ModalVector, DataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_3d<ModalVector, DataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_1d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_1d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_2d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_2d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_3d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_3d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Legendre,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_1d<ModalVector, DataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_1d<ModalVector, DataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_2d<ModalVector, DataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_2d<ModalVector, DataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_3d<ModalVector, DataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_3d<ModalVector, DataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_1d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_1d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_2d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_2d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
test_3d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::GaussLobatto>(make_not_null(&generator));
test_3d<ComplexModalVector, ComplexDataVector, Spectral::Basis::Chebyshev,
Spectral::Quadrature::Gauss>(make_not_null(&generator));
}
| true |
8b7090a3bc9e921f2104a98d909247ffb47ae51e | C++ | robotil/robil | /C11_OperatorControl/src/arcitem.cpp | UTF-8 | 4,881 | 2.65625 | 3 | [] | no_license | #include "arcitem.h"
#include <QPainter>
#include <QGraphicsScene>
#include <math.h>
CArcItem::CArcItem(QPointF p,QGraphicsScene* scene)
: QGraphicsEllipseItem()
{
centerPos = p;
radius = 160;
setStartAngle(60 * 16);
setSpanAngle(60 * 16);
RightPoint = new CPointItem(GetRightPoint(),scene);
scene->addItem(RightPoint);
LeftPoint = new CPointItem(GetLeftPoint(),scene);
scene->addItem(LeftPoint);
PressedPoint = NULL;
}
CArcItem::~CArcItem()
{
}
void CArcItem::updatePie_LeftPressed(QPointF p)
{
double pi = 3.1415926535;
int spanAngl;
double c,span;
int lastSpanAngle = spanAngle()/16;
int lastStartAngle = startAngle()/16;
if(p.y() < centerPos.y())
{
c = (p.x()-centerPos.x())/radius;
span = acos(c);
spanAngl = (180*span)/pi;
setSpanAngle((spanAngl-lastStartAngle)*16);
LeftPoint->setPointParam(GetLeftPoint());
}
else
{
c = (p.x()-centerPos.x())/radius;
span = acos(-c);
spanAngl = 180+(180*span)/pi;
setSpanAngle((spanAngl-lastStartAngle)*16);
LeftPoint->setPointParam(GetLeftPoint());
}
}
void CArcItem::updatePie_RightPressed(QPointF p)
{
double pi = 3.1415926535;
int startAngl,spanAngl;
double c,start,span;
int lastStartAngle = startAngle()/16;
int lastSpanAngle = spanAngle()/16;
QPointF LastRightPoint = GetRightPoint();
QPointF LastLeftPoint = GetLeftPoint();
if(p.y() <= centerPos.y())
{
c = (p.x()-centerPos.x())/radius;
start = acos(c);
startAngl = (180*start)/pi;
setStartAngle(startAngl*16);
RightPoint->setPointParam(p);
c = (LastLeftPoint.x()-centerPos.x())/radius;
span = acos(c);
spanAngl = (180*span)/pi;
setSpanAngle((spanAngl-startAngl)*16);
LeftPoint->setPointParam(GetLeftPoint());
}
else
{
c = (p.x()-centerPos.x())/radius;
start = acos(-c);
startAngl = 180+(180*start)/pi;
setStartAngle(startAngl*16);
RightPoint->setPointParam(p);
c = (LastLeftPoint.x()-centerPos.x())/radius;
span = acos(-c);
spanAngl = 180+(180*span)/pi;
setSpanAngle(spanAngl*16);
LeftPoint->setPointParam(GetLeftPoint());
}
}
QPointF CArcItem::GetRightPoint()
{
double pi = 3.1415926535;
QPointF R_temp;
double startAngl = startAngle()/16;
double start = pi / (180/startAngl);
double s = sin((double)(start));
double c = cos((double)(start));
R_temp.setY(centerPos.y()-(s*radius));
R_temp.setX(centerPos.x()+(c*radius));
return R_temp;
}
QPointF CArcItem::GetLeftPoint()
{
double pi = 3.1415926535;
QPointF L_temp;
double startAngl =( spanAngle()/16)+(startAngle()/16);
double start = pi / (180/startAngl);
double s = sin((double)(start));
double c = cos((double)(start));
L_temp.setY(centerPos.y()-(s*radius));
L_temp.setX(centerPos.x()+(c*radius));
return L_temp;
}
QPainterPath CArcItem::shape() const
{
return QGraphicsEllipseItem::shape();
}
QRectF CArcItem::boundingRect() const
{
return QRectF(centerPos.x()-radius,centerPos.y()-radius,radius*2,radius*2);
}
void CArcItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rec;
painter->setPen(QPen(Qt::green));
rec = QRectF(QPointF(centerPos.x()-radius,centerPos.y()-radius),QPointF(centerPos.x()+radius,centerPos.y()+radius));
painter->drawPie(rec, startAngle(), spanAngle());
}
bool CArcItem::IsArcContains(QPointF p)
{
bool b;
b = RightPoint->isContainPoint(p);
if(b)
PressedPoint = RightPoint;
else
{
b = LeftPoint->isContainPoint(p);
if(b)
PressedPoint = LeftPoint;
}
return b;
}
void CArcItem::MoveArcPoint(QPointF p)
{
checkMousePos(p);
scene()->update();
update();
}
void CArcItem::checkMousePos(QPointF new_point)
{
float x1,y1;
double m;
int Xnew,Ynew;
double pi = 3.1415926535;
x1=new_point.x()-centerPos.x();
y1=new_point.y()-centerPos.y();
if(x1!=0)
m=y1/x1;
double b,a;
a = radius;
b = radius;
if(new_point.x() > centerPos.x())
Xnew=(a*b)/(sqrt(pow(b,2)+(pow(a,2)*pow(m,2))))+centerPos.x();
else
{
if(new_point.x() < centerPos.x())
Xnew=-(a*b)/(sqrt(pow(b,2)+(pow(a,2)*pow(m,2))))+centerPos.x();
else
Xnew = centerPos.x();
}
if(Xnew != centerPos.x())
Ynew=m*(Xnew-centerPos.x())+centerPos.y();
else
{
if(new_point.y() > centerPos.y())
Ynew=b+centerPos.y();
else
{
if(new_point.y() < centerPos.y())
Ynew=-b+centerPos.y();
else
Ynew = centerPos.y();
}
}
QPointF ppp;
ppp.setX(Xnew);
ppp.setY(Ynew);
//PressedPoint->setPointParam(ppp);
if(PressedPoint == RightPoint)
updatePie_RightPressed(QPointF(Xnew,Ynew));
else
if(PressedPoint == LeftPoint)
updatePie_LeftPressed(QPointF(Xnew,Ynew));
}
| true |
2cc877d1d3ee30d373fa7d7363ee3c073fc1a0ea | C++ | brandonwsims/laserharp | /laserHarp.ino | UTF-8 | 1,814 | 3 | 3 | [] | no_license | #include <Stepper.h>
const int laser = 13;
const int stepsPerRevolution = 200;
const int numberOfReads = 3;
int i = 0;
int read = 0;
int previousAvg = 0;
int reads[numberOfReads] = {0, 0, 0};
int avg = 0;
int initial = 0;
bool stop = false;
bool first = true;
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
void setup() {
myStepper.setSpeed(60);
Serial.begin(9600);
pinMode(laser, OUTPUT);
}
void loop() {
//Another option would be to take an average for the first few iterations
//then use that metric for all comparisons past this. The constant rising
//in values over time might become an issue though.
delay(500);
if(i > 0){
first = false;
}
read = analogRead(A0);
if(first){
for(int j = 0; j < numberOfReads; j++){
reads[j] = read;
}
initial = read;
}
if(!stop){
reads[i] = read;
}
//Take the average of the last numberOfReads values
for(int j = 0; j < numberOfReads; j++){
avg += reads[j];
}
avg = avg/numberOfReads;
Serial.print("Average: ");
Serial.print(avg);
Serial.print(" Read: ");
Serial.println(read);
//If there was a change of more than 10.
if((read - avg) > 10){
stop = true;
digitalWrite(13, HIGH);
}
else{
stop = false;
digitalWrite(13, LOW);
}
//increment up the index
i++;
if(i == numberOfReads){
i = 0;
}
if((read - avg) > 200 && stop){
for(int j = 0; j < numberOfReads; j++){
reads[j] = initial;
}
}
//Reset avg for next iteration
avg = 0;
}
// myStepper.step(stepsPerRevolution);
// myStepper.step(stepsPerRevolution, laser);
// for(int i = 0; i < 12; i++){
// myStepper.step(2, laser);
// }
//
// for(int i = 0; i < 12; i++){
// myStepper.step(-2, laser);
// }
| true |
8fd19f882706f71c45240112a735a16e6f12ff56 | C++ | litao91/gsampling | /mcmc_span.h | UTF-8 | 1,402 | 2.53125 | 3 | [] | no_license | #include "util.h"
#include "reduce_func.h"
#include <iostream>
using namespace std;
//#include "hash.h"
//#include <ext/hash_set>
#include <vector>
#include <set>
#ifndef _MCMC_SPAN_H_
#define _MCMC_SPAN_H_
struct CompareSet;
using std::set;
using std::vector;
/**
* Type of a pattern, currently implemented as array with the same
* size as the label number, if the set contain a certain label,
* the corresponding value in the array is 1 and 0- otherwise.
*/
typedef vector<int> pattern_t;
/**
* Use the set to store the mined pattern to make finding faster
*/
typedef set<pattern_t, CompareSet> pattern_db_t;
struct CompareSet{
bool operator()(const vector<int>& set1, const vector<int>& set2);
};
class McmcSpan{
public:
McmcSpan(float min_sup, int label_num):
_m_min_sup(min_sup),
_m_label_num(label_num){}
~McmcSpan();
//the type for a single pattern
//Data format:
//columns corresponding to labels and rows as sets
void set_data(const vector<vector<float> >& database);
void run_alg(int mix_time, int k, ReduceFunc * reduce_func);
void init_gpu();
void print_max_pat();
float* dev_data;
float* dev_dot;
float* dev_out;
private:
int _m_N; //database size
vector<vector<float> > _m_database;
float* _m_raw_database;
int _m_min_sup;
int _m_label_num;
pattern_db_t _m_max_pattern;
};
#endif
| true |
985c6efe1dee8b1adf44aa5e987606b92de94bc5 | C++ | guiguibubu/MyBotLogic-1 | /Strategies/CheckingHiddenDoors.cpp | UTF-8 | 3,887 | 2.71875 | 3 | [] | no_license |
#include "CheckingHiddenDoors.h"
#include "MyBotLogic/BehaviorTree/BT_Noeud.h"
#include "MyBotLogic/GameManager.h"
#include "MyBotLogic/MapTile.h"
#include <string>
#include <vector>
using std::vector;
BT_Noeud::ETAT_ELEMENT CheckingHiddenDoors::execute() noexcept {
ProfilerRelease pointeurProfiler{ GameManager::getLoggerRelease(), "CheckingHiddenDoors", true, true };
ProfilerDebug profiler{ GameManager::getLogger(), string("CheckingHiddenDoors") };
// Pour tous les npcs
for (auto& pair : manager.getNpcs()) {
Npc& npc = pair.second;
// On regarde s'ils sont à coté d'une mur à checker
if (isAdajacentToWallToCheck(npc.getTileId())) {
// Si oui, il check
affecterDoorACheckerAuNpc(npc);
} else {
// Si non, on lui affecte un chemin vers un mur à checker
affecterCheminNpcPourCheckerDoors(npc);
}
}
return ETAT_ELEMENT::REUSSI;
}
void CheckingHiddenDoors::affecterDoorACheckerAuNpc(Npc& npc) {
for (Voisin voisin : manager.c.getTile(npc.getTileId()).getVoisins()) {
int voisinID = voisin.getTuileIndex();
if (manager.c.hasWallBetweenUnchecked(npc.getTileId(), voisinID)) {
npc.setIsCheckingDoor(true, manager.c.getDirection(npc.getTileId(), voisinID));
return;
}
}
LOG("On ne devrait pas être ici !!!");
}
bool CheckingHiddenDoors::isAdajacentToWallToCheck(const int npcTileID) const noexcept {
for (Voisin voisin : manager.c.getTile(npcTileID).getVoisins()) {
int voisinID = voisin.getTuileIndex();
if (manager.c.hasWallBetweenUnchecked(npcTileID, voisinID))
return true;
}
return false;
}
void CheckingHiddenDoors::affecterCheminNpcPourCheckerDoors(Npc& npc) {
npc.resetObjectifs();
// Calculer le score de chaque tile pour le npc
// En même temps on calcul le chemin pour aller à cette tile
// On stocke ces deux informations dans l'attribut cheminsPossibles du Npc
calculerScoresTilesPourNpc(npc);
// Choisir la meilleure tile pour ce npc et lui affecter son chemin
int tileChoisi = npc.affecterMeilleurObjectif(manager);
}
void CheckingHiddenDoors::calculerScoresTilesPourNpc(Npc& _npc) noexcept {
ProfilerDebug profiler{ GameManager::getLogger(), "calculerScoresTilesPourNpc", false};
//profiler << "Taille ensemble : " << _npc.getEnsembleAccessible().size() << endl;
for (auto score : _npc.getEnsembleAccessible()) { // parcours toutes les tiles découvertes par l'ensemble des npcs et qui sont accessibles
calculerScore1Tile(score.tuileID, manager.c, _npc);
}
}
void CheckingHiddenDoors::calculerScore1Tile(int _tileID, Carte& _carte, Npc& _npc) {
MapTile tile = _carte.getTile(_tileID);
saveScore(tile, _npc);
}
void CheckingHiddenDoors::saveScore(const MapTile& _tile, Npc& _npc) const noexcept {
float score = 0;
// On enregistre le cout, cad la distanc npc-tile
score += _npc.distanceToTile(_tile.getId()) * COEF_DISTANCE_NPC_TILE;
// On regarde l'intéret de cette tile
float interetTile = interet(_tile);
score += interetTile * COEF_INTERET;
if (interetTile == 0) return; // Si pas d'intéret, la tile ne nous intéresse pas !
// Il reste à affecter le score et le chemin au npc
_npc.addScore({ _tile.getId(), score });
}
// L'intérét est définit par :
// Le nombre de murs que possède la tuile
float CheckingHiddenDoors::interet(const MapTile& tile) const noexcept {
float interet = 0;
// On compte le nombre de murs
int nbMursAdjacents = 0;
for (Voisin voisin : tile.getVoisins()) {
int voisinID = voisin.getTuileIndex();
if (manager.c.hasWallBetweenUnchecked(tile.getId(), voisinID))
nbMursAdjacents++;
}
interet += nbMursAdjacents * COEF_NB_MURS_TILE;;
return interet;
}
| true |
e650e3251d74386ccb4fd95d6284bbc60ca792d7 | C++ | amd/libflame | /test/lapacke/LIN/lapacke_gtest_sytrs_3.cc | UTF-8 | 37,818 | 2.78125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive"
] | permissive | #include "gtest/gtest.h"
#include "../lapacke_gtest_main.h"
#include "../lapacke_gtest_helper.h"
#define sytrs_3_free() \
if (ipiv != NULL) free (ipiv); \
if (bref != NULL) free (bref); \
if (b != NULL) free (b ); \
if (a != NULL) free (a ); \
if (aref != NULL) free (aref); \
if (e != NULL) free (e ); \
if (eref != NULL) free (eref); \
if (ipivref != NULL)free (ipivref); \
if( hModule != NULL) dlclose(hModule); \
if(dModule != NULL) dlclose(dModule)
// index of the 'config parameter struct' array to enable multiple sub-tests.
static int idx = 0;
/* Begin sytrs_3_double_parameters class definition */
class sytrs_3_double_parameters{
public:
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char uplo; // Must be 'U' or 'L'
lapack_int n; // The order of A; the number of rows in B
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
double *a, *aref; //The array 'a' contains the matrix A
double *e, *eref; // superdiagonal (or subdiagonal) elements of
// the symmetric block diagonal matrix D
lapack_int *ipiv, *ipivref; // The pivot indices
void *hModule, *dModule;
int b_bufsize;
/* Input/ Output parameters */
double *b, *bref; //right-hand sides for the systems of equations.
/* Return Values */
lapack_int info, inforef;
public:
sytrs_3_double_parameters ( int matrix_layout_i, char uplo_i,
lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i);
~sytrs_3_double_parameters ();
}; /* end of sytrs_3_double_parameters class definition */
/* Constructor sytrs_3_double_parameters definition */
sytrs_3_double_parameters:: sytrs_3_double_parameters ( int matrix_layout_i,
char uplo_i, lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i) {
matrix_layout = matrix_layout_i;
n = n_i;
uplo = uplo_i;
lda = lda_i;
ldb = ldb_i;
nrhs = nrhs_i;
hModule = NULL;
dModule = NULL;
#if LAPACKE_TEST_VERBOSE
printf(" \n sytrs_3 Double: n: %d, uplo: %c lda: %d ldb: %d nrhs: %d \n",
n, uplo, lda, ldb, nrhs);
#endif
if(matrix_layout==LAPACK_COL_MAJOR){
b_bufsize = ldb*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
b_bufsize = ldb*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
/* Memory allocation of the buffers */
lapacke_gtest_alloc_double_buffer_pair( &a, &aref, (n*lda));
lapacke_gtest_alloc_double_buffer_pair( &e, &eref, n);
lapacke_gtest_alloc_double_buffer_pair( &b, &bref, b_bufsize);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n);
if( (a==NULL) || (aref==NULL) || \
(b==NULL) || (bref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "sytrs_3_double_parameters object: malloc error.";
sytrs_3_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_double_buffer_pair_rand( a, aref, n*lda);
lapacke_gtest_init_double_buffer_pair_rand( e, eref, n);
lapacke_gtest_init_double_buffer_pair_rand( b, bref, b_bufsize);
} /* end of Constructor */
sytrs_3_double_parameters:: ~sytrs_3_double_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" sytrs_3_double_parameters object: destructor invoked. \n");
#endif
sytrs_3_free();
}
// Test fixture class definition
class dsytrs_3_test : public ::testing::Test {
public:
sytrs_3_double_parameters *dsytrs_3_obj;
void SetUp();
void TearDown () { delete dsytrs_3_obj; }
};
void dsytrs_3_test::SetUp(){
/* LAPACKE DSYTRS_3 prototype */
typedef int (*Fptr_NL_LAPACKE_dsytrs_3) ( int matrix_layout, char uplo,
lapack_int n, lapack_int nrhs, const double *a,
lapack_int lda, const double *e, const lapack_int *ipiv,
double * b, lapack_int ldb );
Fptr_NL_LAPACKE_dsytrs_3 DSYTRS_3;
/* LAPACKE DSYTRF_RK prototype */
typedef int (*Fptr_NL_LAPACKE_dsytrf_rk) ( int matrix_layout, char uplo,
lapack_int n, double* a, lapack_int lda, double *e, lapack_int* ipiv );
Fptr_NL_LAPACKE_dsytrf_rk DSYTRF_RK;
dsytrs_3_obj = new sytrs_3_double_parameters(lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].Uplo,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].lda,
lin_solver_paramslist[idx].nrhs,
lin_solver_paramslist[idx].ldb );
idx = Circular_Increment_Index(idx);
dsytrs_3_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
dsytrs_3_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(dsytrs_3_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(dsytrs_3_obj->hModule != NULL) << "Netlib lapacke handle NULL";
DSYTRS_3 = (Fptr_NL_LAPACKE_dsytrs_3)dlsym(dsytrs_3_obj->hModule, "LAPACKE_dsytrs_3");
ASSERT_TRUE(DSYTRS_3 != NULL) << "failed to get the Netlib LAPACKE_dsytrs_3 symbol";
DSYTRF_RK = (Fptr_NL_LAPACKE_dsytrf_rk)dlsym(dsytrs_3_obj->hModule,"LAPACKE_dsytrf_rk");
ASSERT_TRUE(DSYTRF_RK != NULL) << "failed to get the Netlib LAPACKE_dsytrf_rk symbol";
/* Pre condition: need to call sytrf_rk - before calling sytrs_3 function */
/* Compute the Netlib-Lapacke's reference o/p */
dsytrs_3_obj->inforef = DSYTRF_RK( dsytrs_3_obj->matrix_layout,
dsytrs_3_obj->uplo,
dsytrs_3_obj->n,
dsytrs_3_obj->aref,
dsytrs_3_obj->lda,
dsytrs_3_obj->eref,
dsytrs_3_obj->ipivref);
dsytrs_3_obj->inforef = DSYTRS_3( dsytrs_3_obj->matrix_layout,
dsytrs_3_obj->uplo,
dsytrs_3_obj->n,
dsytrs_3_obj->nrhs,
(const double *)dsytrs_3_obj->aref,
dsytrs_3_obj->lda,
(const double *)dsytrs_3_obj->eref,
dsytrs_3_obj->ipivref,
dsytrs_3_obj->bref,
dsytrs_3_obj->ldb);
/* Compute the Libflme lapacke o/p */
dsytrs_3_obj->info = LAPACKE_dsytrf_rk( dsytrs_3_obj->matrix_layout,
dsytrs_3_obj->uplo,
dsytrs_3_obj->n,
dsytrs_3_obj->a,
dsytrs_3_obj->lda,
dsytrs_3_obj->e,
dsytrs_3_obj->ipiv);
dsytrs_3_obj->info = LAPACKE_dsytrs_3( dsytrs_3_obj->matrix_layout,
dsytrs_3_obj->uplo,
dsytrs_3_obj->n,
dsytrs_3_obj->nrhs,
(const double *)dsytrs_3_obj->a,
dsytrs_3_obj->lda,
(const double *)dsytrs_3_obj->e,
dsytrs_3_obj->ipiv,
dsytrs_3_obj->b,
dsytrs_3_obj->ldb );
if( dsytrs_3_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame LAPACKE_dsytrs_3 is wrong\n",
dsytrs_3_obj->info );
}
if( dsytrs_3_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_dsytrs_3 is wrong\n",
dsytrs_3_obj->inforef );
}
}
TEST_F(dsytrs_3_test, dsytrs_31) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_d( dsytrs_3_obj->b_bufsize,
dsytrs_3_obj->b,
dsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dsytrs_3_test, dsytrs_32) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_d( dsytrs_3_obj->b_bufsize,
dsytrs_3_obj->b,
dsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dsytrs_3_test, dsytrs_33) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_d( dsytrs_3_obj->b_bufsize,
dsytrs_3_obj->b,
dsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(dsytrs_3_test, dsytrs_34) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_d( dsytrs_3_obj->b_bufsize,
dsytrs_3_obj->b,
dsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
/* Begin sytrs_3_float_parameters class definition */
class sytrs_3_float_parameters{
public:
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char uplo; // Must be 'U' or 'L'
lapack_int n; // The order of A; the number of rows in B
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
float *a, *aref; //The array 'a' contains the matrix A
float *e, *eref; // superdiagonal (or subdiagonal) elements of
// the symmetric block diagonal matrix D
lapack_int *ipiv, *ipivref; // The pivot indices
void *hModule, *dModule;
int b_bufsize;
/* Input/ Output parameters */
float *b, *bref; //right-hand sides for the systems of equations.
/* Return Values */
lapack_int info, inforef;
public:
sytrs_3_float_parameters (int matrix_layout_i, char uplo_i,
lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i);
~sytrs_3_float_parameters ();
}; /* end of sytrs_3_float_parameters class definition */
/* Constructor sytrs_3_float_parameters definition */
sytrs_3_float_parameters:: sytrs_3_float_parameters ( int matrix_layout_i,
char uplo_i, lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i) {
matrix_layout = matrix_layout_i;
n = n_i;
uplo = uplo_i;
lda = lda_i;
ldb = ldb_i;
nrhs = nrhs_i;
hModule = NULL;
dModule = NULL;
#if LAPACKE_TEST_VERBOSE
printf(" \n sytrs_3 float: n: %d, uplo: %c lda: %d ldb: %d nrhs: %d \n",
n, uplo, lda, ldb, nrhs);
#endif
if(matrix_layout==LAPACK_COL_MAJOR){
b_bufsize = ldb*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
b_bufsize = ldb*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
/* Memory allocation of the buffers */
lapacke_gtest_alloc_float_buffer_pair( &a, &aref, (lda*n));
lapacke_gtest_alloc_float_buffer_pair( &e, &eref, n);
lapacke_gtest_alloc_float_buffer_pair( &b, &bref, b_bufsize);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n);
if( (a==NULL) || (aref==NULL) || \
(b==NULL) || (bref==NULL) || \
(e==NULL) || (eref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "sytrs_3_double_parameters object: malloc error.";
sytrs_3_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_float_buffer_pair_rand( a, aref, lda*n);
lapacke_gtest_init_float_buffer_pair_rand( e, eref, n);
lapacke_gtest_init_float_buffer_pair_rand( b, bref, b_bufsize);
} /* end of Constructor */
sytrs_3_float_parameters:: ~sytrs_3_float_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" sytrs_3_float_parameters object: destructor invoked. \n");
#endif
sytrs_3_free();
}
// Test fixture class definition
class ssytrs_3_test : public ::testing::Test {
public:
sytrs_3_float_parameters *ssytrs_3_obj;
void SetUp();
void TearDown () { delete ssytrs_3_obj; }
};
void ssytrs_3_test::SetUp(){
/* LAPACKE SSYTRS_3 prototype */
typedef int (*Fptr_NL_LAPACKE_ssytrs_3) ( int matrix_layout,
char uplo, lapack_int n, lapack_int nrhs,
const float * a, lapack_int lda,
const float *e, const lapack_int * ipiv,
float * b, lapack_int ldb );
Fptr_NL_LAPACKE_ssytrs_3 SSYTRS_3;
/* LAPACKE SSYTRF_RK prototype */
typedef int (*Fptr_NL_LAPACKE_ssytrf_rk) ( int matrix_layout, char uplo,
lapack_int n, float* a, lapack_int lda,
float* e, lapack_int* ipiv );
Fptr_NL_LAPACKE_ssytrf_rk SSYTRF_RK;
ssytrs_3_obj = new sytrs_3_float_parameters(lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].Uplo,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].lda,
lin_solver_paramslist[idx].nrhs,
lin_solver_paramslist[idx].ldb );
idx = Circular_Increment_Index(idx);
ssytrs_3_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
ssytrs_3_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(ssytrs_3_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(ssytrs_3_obj->hModule != NULL) << "Netlib lapacke handle NULL";
SSYTRS_3 = (Fptr_NL_LAPACKE_ssytrs_3)dlsym(ssytrs_3_obj->hModule, "LAPACKE_ssytrs_3");
ASSERT_TRUE(SSYTRS_3 != NULL) << "failed to get the Netlib LAPACKE_ssytrs_3 symbol";
SSYTRF_RK = (Fptr_NL_LAPACKE_ssytrf_rk)dlsym(ssytrs_3_obj->hModule,"LAPACKE_ssytrf_rk");
ASSERT_TRUE(SSYTRF_RK != NULL) << "failed to get the Netlib LAPACKE_ssytrf_rk symbol";
/* Pre condition: need to call sytrf_rk - before calling sytrs_3 function */
/* Compute the Netlib-Lapacke's reference o/p */
ssytrs_3_obj->inforef = SSYTRF_RK( ssytrs_3_obj->matrix_layout,
ssytrs_3_obj->uplo,
ssytrs_3_obj->n,
ssytrs_3_obj->aref,
ssytrs_3_obj->lda,
ssytrs_3_obj->eref,
ssytrs_3_obj->ipivref);
ssytrs_3_obj->inforef = SSYTRS_3( ssytrs_3_obj->matrix_layout,
ssytrs_3_obj->uplo,
ssytrs_3_obj->n,
ssytrs_3_obj->nrhs,
(const float *)ssytrs_3_obj->aref,
ssytrs_3_obj->lda,
(const float *)ssytrs_3_obj->eref,
ssytrs_3_obj->ipivref,
ssytrs_3_obj->bref,
ssytrs_3_obj->ldb);
/* Compute the Libflme lapacke o/p by invoking Netlib-Lapack's API */
ssytrs_3_obj->info = LAPACKE_ssytrf_rk( ssytrs_3_obj->matrix_layout,
ssytrs_3_obj->uplo,
ssytrs_3_obj->n,
ssytrs_3_obj->a,
ssytrs_3_obj->lda,
ssytrs_3_obj->e,
ssytrs_3_obj->ipiv);
ssytrs_3_obj->info = LAPACKE_ssytrs_3( ssytrs_3_obj->matrix_layout,
ssytrs_3_obj->uplo,
ssytrs_3_obj->n,
ssytrs_3_obj->nrhs,
(const float *)ssytrs_3_obj->a,
ssytrs_3_obj->lda,
(const float *)ssytrs_3_obj->e,
ssytrs_3_obj->ipiv,
ssytrs_3_obj->b,
ssytrs_3_obj->ldb );
if( ssytrs_3_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame LAPACKE_ssytrs_3 is wrong\n",
ssytrs_3_obj->info );
}
if( ssytrs_3_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_ssytrs_3 is wrong\n",
ssytrs_3_obj->inforef );
}
}
TEST_F(ssytrs_3_test, ssytrs_31) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_s( ssytrs_3_obj->b_bufsize,
ssytrs_3_obj->b,
ssytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(ssytrs_3_test, ssytrs_32) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_s( ssytrs_3_obj->b_bufsize,
ssytrs_3_obj->b,
ssytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(ssytrs_3_test, ssytrs_33) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_s( ssytrs_3_obj->b_bufsize,
ssytrs_3_obj->b,
ssytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(ssytrs_3_test, ssytrs_34) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_s( ssytrs_3_obj->b_bufsize,
ssytrs_3_obj->b,
ssytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
/* Begin sytrs_3_scomplex_parameters class definition */
class sytrs_3_scomplex_parameters{
public:
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char uplo; // Must be 'U' or 'L'
lapack_int n; // The order of A; the number of rows in B
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
lapack_complex_float *a, *aref; //The array 'a' contains the matrix A
lapack_complex_float *e, *eref; // superdiagonal (or subdiagonal) elements of
// the symmetric block diagonal matrix D
lapack_int *ipiv, *ipivref; // The pivot indices
void *hModule, *dModule;
int b_bufsize;
/* Input/ Output parameters */
lapack_complex_float *b, *bref; //right-hand sides for the systems of equations.
/* Return Values */
lapack_int info, inforef;
public:
sytrs_3_scomplex_parameters ( int matrix_layout_i, char uplo_i,
lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i);
~sytrs_3_scomplex_parameters ();
}; /* end of sytrs_3_scomplex_parameters class definition */
/* Constructor sytrs_3_scomplex_parameters definition */
sytrs_3_scomplex_parameters:: sytrs_3_scomplex_parameters ( int matrix_layout_i,
char uplo_i, lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i) {
matrix_layout = matrix_layout_i;
n = n_i;
uplo = uplo_i;
lda = lda_i;
ldb = ldb_i;
nrhs = nrhs_i;
hModule = NULL;
dModule = NULL;
#if LAPACKE_TEST_VERBOSE
printf(" \n sytrs_3 scomplex: n: %d, uplo: %c lda: %d ldb: %d nrhs: %d \n",
n, uplo, lda, ldb, nrhs);
#endif
if(matrix_layout==LAPACK_COL_MAJOR){
b_bufsize = ldb*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
b_bufsize = ldb*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
/* Memory allocation of the buffers */
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &a, &aref, (n*lda));
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &e, &eref, n);
lapacke_gtest_alloc_lapack_scomplex_buffer_pair( &b, &bref, b_bufsize);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n);
if( (a==NULL) || (aref==NULL) || \
(e==NULL) || (eref==NULL) || \
(b==NULL) || (bref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "sytrs_3_scomplex_parameters object: malloc error.";
sytrs_3_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_scomplex_buffer_pair_rand( a, aref, n*lda);
lapacke_gtest_init_scomplex_buffer_pair_rand( e, eref, n);
lapacke_gtest_init_scomplex_buffer_pair_rand( b, bref, b_bufsize);
} /* end of Constructor */
sytrs_3_scomplex_parameters:: ~sytrs_3_scomplex_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" sytrs_3_scomplex_parameters object: destructor invoked. \n");
#endif
sytrs_3_free();
}
// Test fixture class definition
class csytrs_3_test : public ::testing::Test {
public:
sytrs_3_scomplex_parameters *csytrs_3_obj;
void SetUp();
void TearDown () { delete csytrs_3_obj; }
};
void csytrs_3_test::SetUp(){
/* LAPACKE CSYTRS_3 prototype */
typedef int (*Fptr_NL_LAPACKE_csytrs_3) ( int matrix_layout, char uplo,
lapack_int n, lapack_int nrhs,
const lapack_complex_float *a,
lapack_int lda,
const lapack_complex_float *e,
const lapack_int *ipiv,
lapack_complex_float *b,
lapack_int ldb );
Fptr_NL_LAPACKE_csytrs_3 CSYTRS_3;
/* LAPACKE CSYTRF_RK prototype */
typedef int (*Fptr_NL_LAPACKE_csytrf_rk) ( int matrix_layout, char uplo,
lapack_int n, lapack_complex_float *a, lapack_int lda,
lapack_complex_float *e, lapack_int* ipiv );
Fptr_NL_LAPACKE_csytrf_rk CSYTRF_RK;
csytrs_3_obj = new sytrs_3_scomplex_parameters(lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].Uplo,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].lda,
lin_solver_paramslist[idx].nrhs,
lin_solver_paramslist[idx].ldb );
idx = Circular_Increment_Index(idx);
csytrs_3_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
csytrs_3_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(csytrs_3_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(csytrs_3_obj->hModule != NULL) << "Netlib lapacke handle NULL";
CSYTRS_3 = (Fptr_NL_LAPACKE_csytrs_3)dlsym(csytrs_3_obj->hModule, "LAPACKE_csytrs_3");
ASSERT_TRUE(CSYTRS_3 != NULL) << "failed to get the Netlib LAPACKE_csytrs_3 symbol";
CSYTRF_RK = (Fptr_NL_LAPACKE_csytrf_rk)dlsym(csytrs_3_obj->hModule,"LAPACKE_csytrf_rk");
ASSERT_TRUE(CSYTRF_RK != NULL) << "failed to get the Netlib LAPACKE_csytrf_rk symbol";
/* Pre condition: need to call sytrf_rk - before calling sytrs_3 function */
/* Compute the Netlib-Lapacke's reference o/p */
csytrs_3_obj->inforef = CSYTRF_RK( csytrs_3_obj->matrix_layout,
csytrs_3_obj->uplo,
csytrs_3_obj->n,
csytrs_3_obj->aref,
csytrs_3_obj->lda,
csytrs_3_obj->eref,
csytrs_3_obj->ipivref );
csytrs_3_obj->inforef = CSYTRS_3( csytrs_3_obj->matrix_layout,
csytrs_3_obj->uplo, csytrs_3_obj->n,
csytrs_3_obj->nrhs,
(const lapack_complex_float *)csytrs_3_obj->aref,
csytrs_3_obj->lda,
(const lapack_complex_float *)csytrs_3_obj->eref,
csytrs_3_obj->ipivref,
csytrs_3_obj->bref, csytrs_3_obj->ldb);
/* Compute the Libflme lapacke o/p */
csytrs_3_obj->info = LAPACKE_csytrf_rk( csytrs_3_obj->matrix_layout,
csytrs_3_obj->uplo, csytrs_3_obj->n,
csytrs_3_obj->a,
csytrs_3_obj->lda,
csytrs_3_obj->e,
csytrs_3_obj->ipiv);
csytrs_3_obj->info = LAPACKE_csytrs_3( csytrs_3_obj->matrix_layout,
csytrs_3_obj->uplo,
csytrs_3_obj->n,
csytrs_3_obj->nrhs,
(const lapack_complex_float *)csytrs_3_obj->a,
csytrs_3_obj->lda,
(const lapack_complex_float *)csytrs_3_obj->e,
csytrs_3_obj->ipiv,
csytrs_3_obj->b,
csytrs_3_obj->ldb );
if( csytrs_3_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame LAPACKE_csytrs_3 is wrong\n",
csytrs_3_obj->info );
}
if( csytrs_3_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_csytrs_3 is wrong\n",
csytrs_3_obj->inforef );
}
}
TEST_F(csytrs_3_test, csytrs_31) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_c( csytrs_3_obj->b_bufsize,
csytrs_3_obj->b, csytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(csytrs_3_test, csytrs_32) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_c( csytrs_3_obj->b_bufsize,
csytrs_3_obj->b, csytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(csytrs_3_test, csytrs_33) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_c( csytrs_3_obj->b_bufsize,
csytrs_3_obj->b,
csytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(csytrs_3_test, csytrs_34) {
float diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_c( csytrs_3_obj->b_bufsize,
csytrs_3_obj->b,
csytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
/* Begin sytrs_3_dcomplex_parameters class definition */
class sytrs_3_dcomplex_parameters{
public:
/* Input parameters */
int matrix_layout; // storage layout LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR
char uplo; // Must be 'U' or 'L'
lapack_int n; // The order of A; the number of rows in B
lapack_int nrhs; // The number of right-hand sides
lapack_int lda; // leading dimension of 'a'
lapack_int ldb; // leading dimension of 'b'
lapack_complex_double *a, *aref; //The array 'a' contains the matrix A
lapack_complex_double *e, *eref; // superdiagonal (or subdiagonal) elements of
// the symmetric block diagonal matrix D
lapack_int *ipiv, *ipivref; // The pivot indices
void *hModule, *dModule;
int b_bufsize;
/* Input/ Output parameters */
lapack_complex_double *b, *bref; //right-hand sides for the systems of equations.
/* Return Values */
lapack_int info, inforef;
public:
sytrs_3_dcomplex_parameters ( int matrix_layout_i, char uplo_i,
lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i);
~sytrs_3_dcomplex_parameters ();
}; /* end of sytrs_3_dcomplex_parameters class definition */
/* Constructor sytrs_3_dcomplex_parameters definition */
sytrs_3_dcomplex_parameters:: sytrs_3_dcomplex_parameters ( int matrix_layout_i,
char uplo_i, lapack_int n_i, lapack_int lda_i,
lapack_int nrhs_i, lapack_int ldb_i) {
matrix_layout = matrix_layout_i;
n = n_i;
uplo = uplo_i;
lda = lda_i;
ldb = ldb_i;
nrhs = nrhs_i;
hModule = NULL;
dModule = NULL;
#if LAPACKE_TEST_VERBOSE
printf(" \n sytrs_3 DComplex: n: %d, uplo: %c lda: %d ldb: %d nrhs: %d \n",
n, uplo, lda, ldb, nrhs);
#endif
if(matrix_layout==LAPACK_COL_MAJOR){
b_bufsize = ldb*nrhs;
}
else if(matrix_layout==LAPACK_ROW_MAJOR){
b_bufsize = ldb*n;
}
else
{
EXPECT_TRUE(false) << "matrix_layout invalid";
}
/* Memory allocation of the buffers */
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &a, &aref, (n*lda));
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &e, &eref, n);
lapacke_gtest_alloc_lapack_dcomplex_buffer_pair( &b, &bref, b_bufsize);
lapacke_gtest_alloc_int_buffer_pair ( &ipiv, &ipivref, n);
if( (a==NULL) || (aref==NULL) || \
(e==NULL) || (eref==NULL) || \
(b==NULL) || (bref==NULL) || \
(ipiv==NULL) || (ipivref==NULL) ){
EXPECT_FALSE( true) << "sytrs_3_dcomplex_parameters object: malloc error.";
sytrs_3_free();
exit(-1);
}
/* Initialization of input Buffers */
lapacke_gtest_init_dcomplex_buffer_pair_rand( a, aref, n*lda);
lapacke_gtest_init_dcomplex_buffer_pair_rand( e, eref, n);
lapacke_gtest_init_dcomplex_buffer_pair_rand( b, bref, b_bufsize);
} /* end of Constructor */
sytrs_3_dcomplex_parameters:: ~sytrs_3_dcomplex_parameters ()
{
#if LAPACKE_TEST_VERBOSE
printf(" sytrs_3_dcomplex_parameters object: destructor invoked. \n");
#endif
sytrs_3_free();
}
// Test fixture class definition
class zsytrs_3_test : public ::testing::Test {
public:
sytrs_3_dcomplex_parameters *zsytrs_3_obj;
void SetUp();
void TearDown () { delete zsytrs_3_obj; }
};
void zsytrs_3_test::SetUp(){
/* LAPACKE ZSYTRS_3 prototype */
typedef int (*Fptr_NL_LAPACKE_zsytrs_3)( int matrix_layout, char uplo,
lapack_int n, lapack_int nrhs,
const lapack_complex_double * a,
lapack_int lda,
const lapack_complex_double * e,
const lapack_int * ipiv,
lapack_complex_double *b,
lapack_int ldb );
Fptr_NL_LAPACKE_zsytrs_3 ZSYTRS_3;
/* LAPACKE ZSYTRF_RK prototype */
typedef int (*Fptr_NL_LAPACKE_zsytrf_rk) ( int matrix_layout,char uplo,
lapack_int n,
lapack_complex_double* a,
lapack_int lda,
lapack_complex_double* e,
lapack_int* ipiv );
Fptr_NL_LAPACKE_zsytrf_rk ZSYTRF_RK;
zsytrs_3_obj = new sytrs_3_dcomplex_parameters(lin_solver_paramslist[idx].matrix_layout,
lin_solver_paramslist[idx].Uplo,
lin_solver_paramslist[idx].n,
lin_solver_paramslist[idx].lda,
lin_solver_paramslist[idx].nrhs,
lin_solver_paramslist[idx].ldb );
idx = Circular_Increment_Index(idx);
zsytrs_3_obj->dModule = dlopen(NETLIB_BLAS_LIB, RTLD_NOW | RTLD_GLOBAL);
zsytrs_3_obj->hModule = dlopen(NETLIB_LAPACKE_LIB, RTLD_NOW);
ASSERT_TRUE(zsytrs_3_obj->dModule != NULL) << "Netlib Blas handle NULL";
ASSERT_TRUE(zsytrs_3_obj->hModule != NULL) << "Netlib lapacke handle NULL";
ZSYTRS_3 = (Fptr_NL_LAPACKE_zsytrs_3)dlsym(zsytrs_3_obj->hModule, "LAPACKE_zsytrs_3");
ASSERT_TRUE(ZSYTRS_3 != NULL) << "failed to get the Netlib LAPACKE_zsytrs_3 symbol";
ZSYTRF_RK = (Fptr_NL_LAPACKE_zsytrf_rk)dlsym(zsytrs_3_obj->hModule,"LAPACKE_zsytrf_rk");
ASSERT_TRUE(ZSYTRF_RK != NULL) << "failed to get the Netlib LAPACKE_zsytrf_rk symbol";
/* Pre condition: need to call sytrf_rk - before calling sytrs_3 function */
/* Compute the Netlib-Lapacke's reference o/p */
zsytrs_3_obj->inforef = ZSYTRF_RK( zsytrs_3_obj->matrix_layout,
zsytrs_3_obj->uplo,
zsytrs_3_obj->n,
zsytrs_3_obj->aref,
zsytrs_3_obj->lda,
zsytrs_3_obj->eref,
zsytrs_3_obj->ipivref );
zsytrs_3_obj->inforef = ZSYTRS_3(zsytrs_3_obj->matrix_layout,
zsytrs_3_obj->uplo, zsytrs_3_obj->n,
zsytrs_3_obj->nrhs,
(const lapack_complex_double *)zsytrs_3_obj->aref,
zsytrs_3_obj->lda,
(const lapack_complex_double *)zsytrs_3_obj->eref,
zsytrs_3_obj->ipivref,
zsytrs_3_obj->bref, zsytrs_3_obj->ldb);
/* Compute the Libflme lapacke o/p */
zsytrs_3_obj->info = LAPACKE_zsytrf_rk( zsytrs_3_obj->matrix_layout,
zsytrs_3_obj->uplo, zsytrs_3_obj->n,
zsytrs_3_obj->a,
zsytrs_3_obj->lda,
zsytrs_3_obj->e,
zsytrs_3_obj->ipiv);
zsytrs_3_obj->info = LAPACKE_zsytrs_3( zsytrs_3_obj->matrix_layout,
zsytrs_3_obj->uplo,
zsytrs_3_obj->n,
zsytrs_3_obj->nrhs,
(const lapack_complex_double *)zsytrs_3_obj->a,
zsytrs_3_obj->lda,
(const lapack_complex_double *)zsytrs_3_obj->e,
zsytrs_3_obj->ipiv,
zsytrs_3_obj->b,
zsytrs_3_obj->ldb );
if( zsytrs_3_obj->info < 0 ) {
printf( "\n warning: The i:%d th argument with libflame LAPACKE_zsytrs_3 is wrong\n",
zsytrs_3_obj->info );
}
if( zsytrs_3_obj->inforef < 0 ) {
printf( "The i:%d th argument with Netlib LAPACKE_zsytrs_3 is wrong\n",
zsytrs_3_obj->inforef );
}
}
TEST_F(zsytrs_3_test, zsytrs_31) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_z( zsytrs_3_obj->b_bufsize,
zsytrs_3_obj->b,
zsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zsytrs_3_test, zsytrs_32) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_z( zsytrs_3_obj->b_bufsize,
zsytrs_3_obj->b,
zsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zsytrs_3_test, zsytrs_33) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_z( zsytrs_3_obj->b_bufsize,
zsytrs_3_obj->b,
zsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
}
TEST_F(zsytrs_3_test, zsytrs_34) {
double diff;
/* Compute Difference between libflame and Netlib o/ps */
diff = computeDiff_z( zsytrs_3_obj->b_bufsize,
zsytrs_3_obj->b,
zsytrs_3_obj->bref );
EXPECT_NEAR(0.0, diff, LAPACKE_GTEST_THRESHOLD);
} | true |
1be821f4c6522e8dc2901ada84f812a1aceddcab | C++ | JdeRobot/ThirdParty | /gazebo-5.3.0/gazebo/math/Vector2d.hh | UTF-8 | 6,275 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2012-2015 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUdouble WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* Desc: Two dimensional vector
* Author: Nate Koenig
* Date: 3 Apr 2007
*/
#ifndef _VECTOR2D_HH_
#define _VECTOR2D_HH_
#include <math.h>
#include <iostream>
#include <fstream>
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace math
{
/// \addtogroup gazebo_math
/// \{
/// \class Vector2d Vector2D.hh math/gzmath.hh
/// \brief Generic double x, y vector
class GAZEBO_VISIBLE Vector2d
{
/// \brief Constructor
public: Vector2d();
/// \brief Constructor
/// \param[in] _x value along x
/// \param[in] _y value along y
public: Vector2d(const double &_x, const double &_y);
/// \brief Copy constructor
/// \param[in] _v the value
public: Vector2d(const Vector2d &_v);
/// \brief Destructor
public: virtual ~Vector2d();
/// \brief Calc distance to the given point
/// \param[in] _pt The point to measure to
/// \return the distance
public: double Distance(const Vector2d &_pt) const;
/// \brief Normalize the vector length
public: void Normalize();
/// \brief Set the contents of the vector
/// \param[in] _x value along x
/// \param[in] _y value along y
public: void Set(double _x, double _y);
/// \brief Return the dot product of this vector and _v
/// \param[in] _v the vector
/// \return the dot product
public: double Dot(const Vector2d &_v) const;
/// \brief Assignment operator
/// \param[in] _v a value for x and y element
/// \return this
public: Vector2d &operator =(const Vector2d &_v);
/// \brief Assignment operator
/// \param[in] _v the value for x and y element
/// \return this
public: const Vector2d &operator =(double _v);
/// \brief Addition operator
/// \param[in] _v vector to add
/// \return sum vector
public: Vector2d operator+(const Vector2d &_v) const;
/// \brief Addition assignment operator
/// \param[in] _v the vector to add
// \return this
public: const Vector2d &operator+=(const Vector2d &_v);
/// \brief Subtraction operator
/// \param[in] _v the vector to substract
/// \return the subtracted vector
public: Vector2d operator-(const Vector2d &_v) const;
/// \brief Subtraction assignment operator
/// \param[in] _v the vector to substract
/// \return this
public: const Vector2d &operator-=(const Vector2d &_v);
/// \brief Division operator
/// \remarks this is an element wise division
/// \param[in] _v a vector
/// \result a result
public: const Vector2d operator/(const Vector2d &_v) const;
/// \brief Division operator
/// \remarks this is an element wise division
/// \param[in] _v a vector
/// \return this
public: const Vector2d &operator/=(const Vector2d &_v);
/// \brief Division operator
/// \param[in] _v the value
/// \return a vector
public: const Vector2d operator/(double _v) const;
/// \brief Division operator
/// \param[in] _v the divisor
/// \return a vector
public: const Vector2d &operator/=(double _v);
/// \brief Multiplication operators
/// \param[in] _v the vector
/// \return the result
public: const Vector2d operator*(const Vector2d &_v) const;
/// \brief Multiplication assignment operator
/// \remarks this is an element wise multiplication
/// \param[in] _v the vector
/// \return this
public: const Vector2d &operator*=(const Vector2d &_v);
/// \brief Multiplication operators
/// \param[in] _v the scaling factor
/// \return a scaled vector
public: const Vector2d operator*(double _v) const;
/// \brief Multiplication assignment operator
/// \param[in] _v the scaling factor
/// \return a scaled vector
public: const Vector2d &operator*=(double _v);
/// \brief Equal to operator
/// \param[in] _v the vector to compare to
/// \return true if the elements of the 2 vectors are equal within
/// a tolerence (1e-6)
public: bool operator ==(const Vector2d &_v) const;
/// \brief Not equal to operator
/// \return true if elements are of diffent values (tolerence 1e-6)
public: bool operator!=(const Vector2d &_v) const;
/// \brief See if a point is finite (e.g., not nan)
/// \return true if finite, false otherwise
public: bool IsFinite() const;
/// \brief Array subscript operator
/// \param[in] _index the index
/// \return the value, or 0 if _index is out of bounds
public: double operator[](unsigned int _index) const;
/// \brief x data
public: double x;
/// \brief y data
public: double y;
/// \brief Stream extraction operator
/// \param[in] _out output stream
/// \param[in] _pt Vector2d to output
/// \return The stream
public: friend std::ostream &operator<<(std::ostream &_out,
const gazebo::math::Vector2d &_pt)
{
_out << _pt.x << " " << _pt.y;
return _out;
}
/// \brief Stream extraction operator
/// \param[in] _in input stream
/// \param[in] _pt Vector3 to read values into
/// \return The stream
public: friend std::istream &operator>>(std::istream &_in,
gazebo::math::Vector2d &_pt)
{
// Skip white spaces
_in.setf(std::ios_base::skipws);
_in >> _pt.x >> _pt.y;
return _in;
}
};
/// \}
}
}
#endif
| true |
cd21bbcbb2d2a67a1aa17cf835027c972b30215b | C++ | mgomezch/Pekomin | /Arrive.cpp | UTF-8 | 1,604 | 2.53125 | 3 | [] | no_license | #include <vector>
#include "Arrive.hpp"
#include "Mobile.hpp"
#include "Triple.hpp"
//#define DEBUG_ARRIVE
#ifdef DEBUG_ARRIVE
#include <iostream>
#endif
Arrive::Arrive(std::string name, Mobile *character, Mobile *target, double maxSpeed, double targetRadius, double slowRadius):
DirectKinematicV(name),
character(character),
target(target),
maxSpeed(maxSpeed),
targetRadius(targetRadius),
slowRadius(slowRadius)
{}
std::vector<Triple> Arrive::getVel(unsigned int ticks, unsigned int delta_ticks) {
Triple steering;
Triple direction, targetVelocity;
double distance, targetSpeed;
Triple cp, tp;
std::tie(cp, tp) = points(this->character, this->target);
direction = tp - cp;
distance = direction.length();
direction.normalize();
if (distance < targetRadius) {
steering = target->vel;
if (steering.length() > maxSpeed) {
steering.normalize();
steering *= maxSpeed;
}
return std::vector<Triple>(1, steering);
}
// targetSpeed = maxSpeed - character->vel.dot(direction);
targetSpeed = maxSpeed;
if (distance < slowRadius) {
targetSpeed *= (distance - targetRadius) / (slowRadius - targetRadius);
}
// if (targetSpeed < 0 ) targetSpeed = 0 ;
// if (targetSpeed > maxSpeed) targetSpeed = maxSpeed;
steering = direction * targetSpeed;
return std::vector<Triple>(1, steering);
}
| true |
4c4c6f67a07a2f950d2f47aa0bbb56504803c615 | C++ | marcellfischbach/CobaltSKY | /Editor/imageimporter/imageimporterfactory.cc | UTF-8 | 878 | 2.609375 | 3 | [] | no_license |
#include <imageimporter/imageimporterfactory.hh>
#include <imageimporter/imageimporter.hh>
ImageImporterFactory::ImageImporterFactory()
{
}
const std::string ImageImporterFactory::GetName() const
{
return std::string("Images");
}
const std::vector<std::string> ImageImporterFactory::GetExtensions() const
{
std::vector<std::string> extensions;
extensions.push_back("png");
extensions.push_back("jpeg");
extensions.push_back("jpg");
extensions.push_back("bmp");
extensions.push_back("tif");
extensions.push_back("tiff");
return extensions;
}
bool ImageImporterFactory::CanImport(const std::filesystem::path &path) const
{
return true;
}
std::vector<iAssetImporter*> ImageImporterFactory::Import(const std::filesystem::path &path) const
{
std::vector<iAssetImporter*> importers;
importers.push_back(new ImageImporter(path));
return importers;
}
| true |
1b169c899f79707765a6f9446f6b03bb4b45a252 | C++ | Monksc/TrieSort | /sort_string_node.cpp | UTF-8 | 590 | 3.046875 | 3 | [] | no_license | //
// sort_string_node.cpp
// TrieSort
//
// Created by Cameron Monks on 12/21/18.
// Copyright © 2018 Cameron Monks. All rights reserved.
//
#include "sort_string_node.hpp"
unsigned SortStringNode::size() const { return 26; }
unsigned SortStringNode::maxIndex() const {
return (unsigned) str.size() - 1;
}
unsigned SortStringNode::hash(int index) const {
char c = str[index];
if (c >= 'a' && c <= 'z') {
return c - 'a';
}
throw "ERROR: SortStringNode only accepts lowercase letters";
}
void SortStringNode::add(unsigned index) {
str += 'a' + index;
}
| true |
5fc3b344135f6a98873372be42dc20ce5d49ef9e | C++ | viktorkuznietsov1986/algorithms | /Sorting/SearchingTest/BinarySearchSTTest.cpp | UTF-8 | 870 | 2.78125 | 3 | [] | no_license | #ifdef WINDOWS
#include "stdafx.h"
#include "CppUnitTest.h"
#include "BinarySearchST.h"
#include <string>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace SearchingTest
{
TEST_CLASS(BinarySearchSTTest)
{
public:
TEST_METHOD(BinarySearchST_BasicFlowTest)
{
// TODO: Your test code here
BinarySearchST<int, std::string> st;
st.put(1, "test1");
st.put(5, "test5");
st.put(2, "test2");
Assert::IsTrue(st.size() == 3);
Assert::IsFalse(st.contains(3));
Assert::IsTrue(st.contains(5));
Assert::IsTrue(*st.get(5) == "test5");
st.Delete(5);
Assert::IsFalse(st.contains(5));
Assert::IsTrue(st.size() == 2);
st.put(3, "test3");
Assert::IsTrue(*st.get(3) == "test3");
Assert::IsTrue(st.size() == 3);
Assert::IsTrue(st.min() < st.max());
}
};
}
#endif
| true |
24591017c4dbe4bb0ad26eca6b19e4fa2fa64197 | C++ | SimonKocurek/Algorithms-and-Fun | /c++/binary-add.cpp | UTF-8 | 434 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int digit_a[]{1, 1, 0, 1};
int digit_b[]{1, 0, 0, 0};
int result[5]{0};
int carry = 0;
for (int i = 3; i >= 0; --i) {
result[i + 1] = (digit_a[i] + digit_b[i] + carry) % 2;
carry = digit_a[i] + digit_b[i] + carry > 1 ? 1 : 0;
}
result[0] = carry;
for (int i = 0; i < 5; ++i) {
cout << result[i];
}
return 0;
}
| true |
7094a3382a26e55705ed5b5e1af3412724659817 | C++ | GondoTheBoo/bak2 | /common/textureCube.cpp | UTF-8 | 2,830 | 2.65625 | 3 | [] | no_license | #include "textureCube.h"
#include "sfml.h"
#include <iostream>
namespace cg2
{
std::shared_ptr<TextureCube> TextureCube::import(std::array< fs::path, 6 > files, const TextureFilter filter, const TextureWrap wrap, const glm::vec4 border)
{
std::shared_ptr<TextureCube> result(new TextureCube, TextureCube::Deleter());
try
{
glGenTextures(1, &result->mHandle);
glBindTexture(GL_TEXTURE_CUBE_MAP, result->mHandle);
sf::Image imgs[6];
for (unsigned int i = 0; i<6; ++i)
{
if (!imgs[i].loadFromFile(files[i].string()))
{
std::cout << "could not load " << files[i] << std::endl;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA8, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
}
else
{
std::cout << "successfully loaded " << files[i] << std::endl;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA8, imgs[i].getSize().x, imgs[i].getSize().y, 0,
GL_RGBA, GL_UNSIGNED_BYTE, imgs[i].getPixelsPtr());
}
}
if (filter == TextureFilter::Bilinear)
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else if (filter == TextureFilter::Trilinear)
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
}
else
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
if (wrap == TextureWrap::Repeat)
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_REPEAT);
}
else if (wrap == TextureWrap::Clamp)
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
else
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterfv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BORDER_COLOR, &border[0]);
result->mBorder = border;
}
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
catch (std::exception &e)
{
std::cout << "SFML import error " << e.what() << std::endl;
}
return result;
}
void TextureCube::Deleter::operator()(TextureCube *& p) const
{
if (p == nullptr)
return;
glDeleteTextures(1, std::addressof(p->mHandle));
delete p;
p = nullptr;
}
}
| true |
11dcc7b3dce2784ba5a0bbc3fd80b5eef870c1bf | C++ | pepeakaseniordeveloper/SpaceRocks | /space_rocks/scenes/scene_menu.cpp | UTF-8 | 10,782 | 2.640625 | 3 | [] | no_license | #include "scene_menu.h"
#include "../game.h"
#include <SFML/Window/Keyboard.hpp>
#include <iostream>
#include <vector>
#include "system_renderer.h"
#include "..\components\components.h"
#include <functional>
using namespace std;
using namespace sf;
//Entities
std::shared_ptr<Entity> txtTitle;
std::shared_ptr<Entity> menu;
std::shared_ptr<Entity> settings;
std::shared_ptr<Entity> controls;
std::shared_ptr<Entity> high;
std::shared_ptr<Entity> graphics;
std::shared_ptr<PanelComponent> menuPanel;
std::shared_ptr<PanelComponent> settingsPanel;
std::shared_ptr<PanelComponent> controlsPanel;
std::shared_ptr<PanelComponent> highscoresPanel;
std::shared_ptr<PanelComponent> graphicsPanel;
PanelComponent* currentPanel;
Input::KeyCode changeKeyCode = (Input::KeyCode)-1;
Input::KeyCode changeTextEntered = (Input::KeyCode)-1;
bool switchWindow = false;
// Create FloatRect to fits Game into Screen while preserving aspect
sf::FloatRect CalculateViewport(const sf::Vector2u& screensize,
const sf::Vector2u& gamesize) {
const Vector2f screensf(screensize.x, screensize.y);
const Vector2f gamesf(gamesize.x, gamesize.y);
const float gameAspect = gamesf.x / gamesf.y;
const float screenAspect = screensf.x / screensf.y;
float scaledWidth; // final size.x of game viewport in piels
float scaledHeight; //final size.y of game viewport in piels
bool scaleSide = false; // false = scale to screen.x, true = screen.y
//Work out which way to scale
if (gamesize.x > gamesize.y) { // game is wider than tall
// Can we use full width?
if (screensf.y < (screensf.x / gameAspect)) {
//no, not high enough to fit game height
scaleSide = true;
}
else {
//Yes, use all width available
scaleSide = false;
}
}
else { // Game is Square or Taller than Wide
// Can we use full height?
if (screensf.x < (screensf.y * gameAspect)) {
// No, screensize not wide enough to fit game width
scaleSide = false;
}
else {
// Yes, use all height available
scaleSide = true;
}
}
if (scaleSide) { // use max screen height
scaledHeight = screensf.y;
scaledWidth = floor(scaledHeight * gameAspect);
}
else { //use max screen width
scaledWidth = screensf.x;
scaledHeight = floor(scaledWidth / gameAspect);
}
//calculate as percent of screen
const float widthPercent = (scaledWidth / screensf.x);
const float heightPercent = (scaledHeight / screensf.y);
return sf::FloatRect(0, 0, widthPercent, heightPercent);
}
void UpdateScaling()
{
const sf::Vector2u screensize = Engine::getWindowSize();
const sf::Vector2u gamesize(GAMEX, GAMEY);
//set View as normal
Engine::getWindow().setSize(screensize);
sf::FloatRect visibleArea(0.f, 0.f, gamesize.x, gamesize.y);
auto v = sf::View(visibleArea);
// figure out how to scale and maintain aspect;
auto viewport = CalculateViewport(screensize, gamesize);
//Optionally Center it
bool centered = true;
if (centered) {
viewport.left = (1.0 - viewport.width) * 0.5;
viewport.top = (1.0 - viewport.height) * 0.5;
}
//set!
v.setViewport(viewport);
Engine::getWindow().setView(v);
}
void switchPanel(PanelComponent* panel)
{
if (currentPanel != NULL)
currentPanel->setVisible(false);
currentPanel = panel;
currentPanel->setVisible(true);
}
void MenuScene::load() {
cout << "Menu Load \n";
// Loading data from files
Files::loadControls();
highscores = Files::loadHighscores();
// Title
txtTitle.swap(makeEntity());
auto txt = txtTitle->addComponent<TextComponent>("SPACE ROCKS");
txt->setSize(64);
txtTitle->setPosition(Vector2f(640.0f, 64.0f));
// Menu
menu = makeEntity();
menu->setPosition(sf::Vector2f(GAMEX / 2, GAMEY / 2 + 96.0f));
menuPanel = (menu->addComponent<PanelComponent>(sf::Vector2f(0.5f, 0.5f), 96.0f));
menuPanel->addButton("Start", []() { gotoGame(); });
menuPanel->addButton("High Scores", []() { switchPanel(highscoresPanel.get()); });
menuPanel->addButton("Settings", []() { switchPanel(settingsPanel.get()); });
menuPanel->addButton("Exit", []() { Engine::getWindow().close(); });
menuPanel->setVisible(true);
switchPanel(menuPanel.get());
// Settings
settings.swap(makeEntity());
settings->setPosition(sf::Vector2f(GAMEX / 2, GAMEY / 2 + 96.0f));
settingsPanel.swap(settings->addComponent<PanelComponent>(sf::Vector2f(0.5f, 0.5f), 96.0f));
settingsPanel->addText("Settings", 48.0f);
settingsPanel->addButton("Controls", []() { switchPanel(controlsPanel.get()); });
settingsPanel->addButton("Graphics", []() { switchPanel(graphicsPanel.get()); });
settingsPanel->addButton("Back", []() { switchPanel(menuPanel.get()); });
settingsPanel->setVisible(false);
// Graphics
graphics.swap(makeEntity());
graphics->setPosition(sf::Vector2f(GAMEX / 2, GAMEY / 2 + 96.0f));
graphicsPanel.swap(graphics->addComponent<PanelComponent>(sf::Vector2f(0.5f, 0.5f), 96.0f));
graphicsPanel->addText("Graphics", 48.0f);
graphicsPanel->addButton("1920x1080", []() { Engine::getWindow().setSize(sf::Vector2u(1920, 1080)); UpdateScaling(); });
graphicsPanel->addButton("1600x900", []() { Engine::getWindow().setSize(sf::Vector2u(1600, 900)); UpdateScaling(); });
graphicsPanel->addButton("1280x720", []() { Engine::getWindow().setSize(sf::Vector2u(1280, 720)); UpdateScaling(); });
graphicsPanel->addButton("Window Mode", []() { Engine::switchWindowMode(); UpdateScaling(); });
graphicsPanel->addButton("Back", []() { Files::saveSettings(); switchPanel(settingsPanel.get()); });
graphicsPanel->setVisible(false);
// Controls
controls.swap(makeEntity());
controls->setPosition(sf::Vector2f(GAMEX / 2, GAMEY / 2 + 96.0f));
controlsPanel.swap(controls->addComponent<PanelComponent>(sf::Vector2f(0.5f, 0.5f), 96.0f));
controlsPanel->addButton(
[]() -> std::string { return "Thrust/Up: " + Input::keys[Input::KeyCode::P1_THRUST].second; },
[]() { Input::keys[Input::KeyCode::P1_THRUST].second = "";
changeKeyCode = Input::KeyCode::P1_THRUST;
});
controlsPanel->addButton(
[]() -> std::string { return "Down: " + Input::keys[Input::KeyCode::P1_DOWN].second; },
[]() { Input::keys[Input::KeyCode::P1_DOWN].second = "";
changeKeyCode = Input::KeyCode::P1_DOWN;
});
controlsPanel->addButton(
[]() -> std::string { return "Left: " + Input::keys[Input::KeyCode::P1_LEFT].second; },
[]() { Input::keys[Input::KeyCode::P1_LEFT].second = "";
changeKeyCode = Input::KeyCode::P1_LEFT;
});
controlsPanel->addButton(
[]() -> std::string { return "Right: " + Input::keys[Input::KeyCode::P1_RIGHT].second; },
[]() { Input::keys[Input::KeyCode::P1_RIGHT].second = "";
changeKeyCode = Input::KeyCode::P1_RIGHT;
});
controlsPanel->addButton(
[]() -> std::string { return "Shoot: " + Input::keys[Input::KeyCode::P1_FIRE].second; },
[]() { Input::keys[Input::KeyCode::P1_FIRE].second = "";
changeKeyCode = Input::KeyCode::P1_FIRE;
});
controlsPanel->addButton("Back", []() { Files::saveControls(); switchPanel(settingsPanel.get()); });
controlsPanel->setVisible(false);
// Highscores
high.swap(makeEntity());
high->setPosition(sf::Vector2f(GAMEX / 2, GAMEY / 2 + 64.0f));
highscoresPanel.swap(high->addComponent<PanelComponent>(sf::Vector2f(0.5f, 0.5f), 38.0f));
highscoresPanel->addText("High Scores", 48.0f);
highscoresPanel->addText("", 8.0f);
// Adding highscores
if (highscores.size() == 0)
{
// Add text to indicate that there's no highscores so far
highscoresPanel->addText("No high scores!", 32.0f);
}
else
{
// Display highscores
for(auto it = highscores.rbegin(); it != highscores.rend(); ++it)
highscoresPanel->addText(it->second + "\t" + std::to_string(it->first), 32.0f);
}
// Add empty text to fit the back button
highscoresPanel->addText("");
highscoresPanel->addButton("Back", []() { switchPanel(menuPanel.get()); });
highscoresPanel->setVisible(false);
// Load graphics settings
if (!Files::loadSettings() && Engine::isWindowed())
switchWindow = true;
UpdateScaling();
setLoaded(true);
}
void MenuScene::onKeyPressed(std::variant<Keyboard::Key, unsigned int> k)
{
if (!menuScene.isLoaded())
return;
Keyboard::Key keyboardKey = Keyboard::Unknown;
unsigned int joystickButton = 0;
// Keyboard
if (std::holds_alternative<Keyboard::Key>(k))
keyboardKey = std::get<Keyboard::Key>(k);
// Joystick
else
joystickButton = std::get<unsigned int>(k);
// Changing player controls
if (changeKeyCode != (Input::KeyCode)-1)
{
// Keyboard
if (keyboardKey != Keyboard::Unknown)
{
Input::keys[changeKeyCode].first = keyboardKey;
// Handling some keys that don't trigger TextEntered event or don't return key names
switch (keyboardKey)
{
case Keyboard::Space: Input::keys[changeKeyCode].second = "Space"; break;
case Keyboard::Up: Input::keys[changeKeyCode].second = "Up"; break;
case Keyboard::Down: Input::keys[changeKeyCode].second = "Down"; break;
case Keyboard::Left: Input::keys[changeKeyCode].second = "Left"; break;
case Keyboard::Right: Input::keys[changeKeyCode].second = "Right"; break;
case Keyboard::Enter: Input::keys[changeKeyCode].second = "Enter"; break;
case Keyboard::LControl: Input::keys[changeKeyCode].second = "LControl"; break;
case Keyboard::RControl: Input::keys[changeKeyCode].second = "RControl"; break;
case Keyboard::LAlt: Input::keys[changeKeyCode].second = "LAlt"; break;
case Keyboard::RAlt: Input::keys[changeKeyCode].second = "RAlt"; break;
default: changeTextEntered = changeKeyCode; break;
}
}
// Joystick
else
{
Input::keys[changeKeyCode].first = joystickButton;
Input::keys[changeKeyCode].second = std::to_string(joystickButton);
}
changeKeyCode = (Input::KeyCode)-1;
return;
}
// Menu navigation
if (std::holds_alternative<unsigned int>(k))
return;
if (keyboardKey == Keyboard::Up)
{
currentPanel->pointerPrevious();
}
else if (keyboardKey == Keyboard::Down)
{
currentPanel->pointerNext();
}
else if (keyboardKey == Keyboard::Enter)
{
currentPanel->executeButton();
}
}
void MenuScene::onTextEntered(std::string text)
{
if (!menuScene.isLoaded())
return;
if (changeTextEntered != (Input::KeyCode)-1)
{
Input::keys[changeTextEntered].second = text;
changeTextEntered = (Input::KeyCode) - 1;
}
}
void MenuScene::update(const double& dt) {
if (switchWindow)
{
Engine::switchWindowMode();
UpdateScaling();
switchWindow = false;
}
Scene::update(dt);
}
// Switch scene to menu safely
void MenuScene::gotoGame()
{
// Resetting all shared_ptr
txtTitle.reset();
menuPanel.reset();
menu->setForDelete();
settingsPanel.reset();
settings->setForDelete();
graphicsPanel.reset();
graphics->setForDelete();
controlsPanel.reset();
controls->setForDelete();
highscoresPanel.reset();
high->setForDelete();
currentPanel = nullptr;
Engine::changeScene(&gameScene);
} | true |
69696b08549ba3396fc1e29ae39fd5af5cb2b9b4 | C++ | PillowCJY/8PUZZLE | /algorithm.h | UTF-8 | 10,551 | 3.453125 | 3 | [] | no_license | /*
*/
#ifndef __ALGORITHM_H__
#define __ALGORITHM_H__
#include <ctime>
#include <string>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include "puzzle.h"
#include <vector>
#include <set>
#include <map>
const heuristicFunction HEURISTIC_FUNCTION=manhattanDistance;
//Function prototypes
string progressiveDeepeningSearch_No_VisitedList(string const initialState, string const goalState, int &numOfStateExpansions, int& maxQLength, float &actualRunningTime, int ultimateMaxDepth);
string progressiveDeepeningSearch_with_NonStrict_VisitedList(string const initialState, string const goalState, int &numOfStateExpansions, int& maxQLength, float &actualRunningTime, int ultimateMaxDepth);
string breadthFirstSearch_with_VisitedList(string const initialState, string const goalState, int &numOfStateExpansions, int& maxQLength, float &actualRunningTime);
string breadthFirstSearch(string const initialState, string const goalState, int &numOfStateExpansions, int& maxQLength, float &actualRunningTime);
string aStar_ExpandedList(string const initialState, string const goalState, int &numOfStateExpansions, int& maxQLength,
float &actualRunningTime, int &numOfDeletionsFromMiddleOfHeap, int &numOfLocalLoopsAvoided, int &numOfAttemptedNodeReExpansions, heuristicFunction heuristic);
#endif
/*Node*/
struct Node{
Puzzle* puzzle;
Node *next;
};
/*Visited list*/
struct VisitedList{
std::set<int> data;/*A set data structure that contains the states in integer format*/
};
/*Non Strict list*/
struct NonStrictList{
/*Using map data structue which contains the state as key and depth level as value*/
std::map<int, int> data;
};
/*Queue data structure for breadth first search*/
class BfsQueue{
private :
Node *front, *rear;
int count; /*Keep track of the number of elements in queue*/
public :
/*Constructor*/
BfsQueue(){
front = NULL;
rear = NULL;
count = 0;
}
/*Function that joins the new puzzle to the rear of the queue*/
void join(Puzzle *newPuzzle){
Node *temp = new Node;
temp->puzzle = newPuzzle;
temp -> next = NULL;
if(rear != NULL){
rear -> next = temp;
}
rear = temp;
if(front == NULL){
front = temp;
}
count += 1;
}
/*Remove the first element of the queue*/
void leave(){
if(front == NULL){
return;
}
Node *temp = front;
front = front -> next;
if(front == NULL){
rear = NULL;
}
delete temp->puzzle;
delete temp;
count -= 1;
}
/*Check if queue is empty. True if empty, false otherwise.*/
bool isEmpty() {
if (front == NULL) {
return true;
}
else {
return false;
}
}
/*Return the first(front) element of the queue*/
Node *Front() {
return front;
};
Puzzle * frontPuzzle(); /*function return the front puzzle inside the queue*/
};
/*Stack data structure for PDS*/
class Stack {
private:
Node * front;
public :
/*Constructor*/
Stack() {
front = NULL;
}
/*Put a new element at the top of the stack*/
void push(Puzzle * newPuzzle) {
Node *temp = new Node;
temp->puzzle = newPuzzle;
temp->next = front;
front = temp;
}
/*Remove the top element of the stack*/
void pop() {
Node *temp = front;
if(front != NULL){
front = front->next;
delete temp;
}
}
/*Return the top(first) element of the stack*/
Puzzle* Top() {
if (front != NULL)
{
return front->puzzle;
}
return NULL;
}
/*Check if stack is empty.*/
bool isEmpty() {
return (front == NULL);
}
};
/*Heap data structure for A star search*/
class Heap {
private:
vector<Puzzle*> data; /*Vector structure that contains Puzzle data*/
int last; /*Index of the last element*/
public:
/*Heap constructor*/
Heap() {
last = -1;
}
/*Get the index of last element. -1 means empty*/
int getLast(){
return last;
}
void printHeap(){
for(int i = 0; i <= last;i++){
cout<<data[i]->toNumber()<<" "<<data[i]->getFCost()<<endl;
}
}
/*Function to check if there is a state that is the same as the new one but has smaller Fcost*/
/*If the state of new puzzle is visited and stored in the heap but with smaller FCOST then we dont add it. return -1 */
/*If the state of new puzzle is visited and stored in the heap but with greater FCOST, we return the index of the old puzzle.*/
/*If the state of new puzzle is not visited yet return -2*/
int hasSmallerCost(Puzzle *puzzle) {
/*get the string representation of the state*/
int state = puzzle->toNumber();
int fcost = puzzle->getFCost();
for (int i = 0; i <= last;i++) {
/*check if the state is the same and has lower fcost */
if (data[i]->toNumber() == state){
if(data[i]->getFCost() <= fcost) {
return -1;
} else if (data[i]->getFCost() > fcost) {
return i;
}
}
}
/*the state is the same as the new puzzle but has a lager fcost*/
return -2;
}
/*Function that does the attempt to insert the new element into the heap. Rerurn true if insertion is executed, false otherwise.*/
bool insertToHeap(Puzzle* puzzle, int &numOfDeletionsFromMiddleOfHeap) {
/*check if the state of the new puzzle is visited with smaller or larger fcost, or it is not visited*/
int index = hasSmallerCost(puzzle);
if (index == -1) {/*The state is already existed in heap and with lower FCost. No need to add it*/
numOfDeletionsFromMiddleOfHeap++;
return false;
}
/*The state is already existed in heap but with greater FCost. Replace the old state with the new one*/
else if (index != -1 && index != -2) {
numOfDeletionsFromMiddleOfHeap++;
deleteFromMiddle(index);
}
/*Add the data to the end of the vector*/
data.push_back(puzzle);
/*Keep track of the index of last puzzle in the vector*/
last++;
if (last == 0) {/*The first puzzle in the heap, no need to do the swapping below*/
return true;
}
/*Start sorting the heap by swapping the element.*/
/*Put the puzzle in order with smallest FCOST at the front and puzzle with biggest FCOST at the end*/
bool swap = true;
/*index of the leaf node*/
int leaf = last;
/*index of the parent node*/
int root = 0;
while (swap) {
swap = false;
/*get the index of the parent node*/
root = (leaf - 1) / 2;
/*if leaf puzzle has a lower FCOST swap it with the parent puzzle*/
if(root >= 0){
if (data[leaf]->getFCost() < data[root]->getFCost()) {
Puzzle*temp = data[leaf];
data[leaf] = data[root];
data[root] = temp;
swap = true;
leaf = root;
}
}
}
return true;
}
/*Function that delete the puzzle from the middle of the heap*/
void deleteFromMiddle(int index) {
/*swaping*/
Puzzle* temp = data[index];
data[index] = data[last];
delete temp;
last--;
data.pop_back();
int root = index;
int left = (root * 2) + 1; /*Left child of the root*/
int right = (root * 2) + 2; /*Right child of the root*/
/*Only one puzzle left in the heap*/
if (left > last) {
return;
}
/*Only two puzzles left in the heap*/
else if (right > last) {
/*Check if the last leaf has smaller fcost, swap if true*/
if (data[left]->getFCost() < data[root]->getFCost()) {
Puzzle *temp = data[left];
data[left] = data[root];
data[root] = temp;
}
return;
}
int side;
/*check which leaf of the root has a lower FCOST swap with that side*/
if (data[left]->getFCost() <= data[right]->getFCost()) {
side = left;
}
else {
side = right;
}
while (data[side]->getFCost() < data[root]->getFCost()) {
/*Swaping*/
Puzzle* temp = data[side];
data[side] = data[root];
data[root] = temp;
/*Keep trakcing the FCOST for next leaves*/
root = side;
left = (root * 2) + 1;
right = (root * 2) + 2;
/*Only one puzzle in the heap*/
if (left > last) {
break;
}
/*Only two puzzles in the heap*/
else if (right > last) {
/*Do the swap if necessary and break the loop*/
if (data[left]->getFCost() < data[root]->getFCost()) {
Puzzle *temp = data[left];
data[left] = data[root];
data[root] = temp;
}
break;
}
else {
/*Check which leaf of the current root has a lower FCOST swap with that side*/
if (data[left]->getFCost() <= data[right]->getFCost()) {
side = left;
}
else {
side = right;
}
}
}
}
/*Function that delete the root of the heap and return its reference*/
void deleteHeapRoot(Puzzle **front) {/*reference to get the puzzle in the front which has the smallest fcost*/
/*no puzzle inside the heap*/
if (last < 0) {
(*front) = NULL;
return;
}
/*retrive first puzzle of the heap which has lowest FCOST*/
(*front) = data[0];
/*Copy the last puzzle to the first and delete the last puzzle*/
data[0] = data[last];
data[last] = NULL;
last--;
data.pop_back();
int root = 0;
int left = 1;
int right = 2;
/*Only one puzzle left in the heap*/
if (left > last) {
return;
}
/*Only two puzzles left in the heap*/
else if (right > last) {
/*check if the last leaf has smaller fcost, swap if true*/
if (data[left]->getFCost() < data[root]->getFCost()) {
Puzzle *temp = data[left];
data[left] = data[root];
data[root] = temp;
}
return;
}
int side;
/*Check which leaf of the root has a lower FCOST swap with that side*/
if (data[left]->getFCost() <= data[right]->getFCost()) {
side = left;
}
else {
side = right;
}
while (data[side]->getFCost() < data[root]->getFCost()) {
/*Swaping*/
Puzzle* temp = data[side];
data[side] = data[root];
data[root] = temp;
/*Keep trakcing the FCOST for next leaves*/
root = side;
left = (root * 2) + 1;
right = (root * 2) + 2;
/*One puzzle in the heap*/
if (left > last) {
break;
}
/*Two puzzle in the heap*/
else if (right > last) {
/*do the swap if necessary and break the loop*/
if (data[left]->getFCost() < data[root]->getFCost()) {
Puzzle *temp = data[left];
data[left] = data[root];
data[root] = temp;
}
break;
}
else {
/*check which leaf of the root has a lower FCOST swap with that side*/
if (data[left]->getFCost() <= data[right]->getFCost()) {
side = left;
}
else {
side = right;
}
}
}
}
};
| true |
68ba75bdebec33bf5251c3bb04ee7bf782e2e2d1 | C++ | tylerwinkler/msg-game | /src/Inventory.cpp | UTF-8 | 230 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "Inventory.hpp"
void Inventory::addItem(std::string item)
{
m_items.push_back(item);
}
std::string Inventory::getItemInSlot(int i)
{
return m_items[i];
}
int Inventory::getSize()
{
return m_items.size();
}
| true |
068e50f03d4319d9d9cda2bded06bd5d89afbbf6 | C++ | viveknath93/NavigationSystem | /Ex1_NavigationSystem/NavigationSystem/myCode/NaviSystem/CRoute.h | UTF-8 | 1,212 | 2.546875 | 3 | [] | no_license | /***************************************************************************
*============= Copyright by Darmstadt University of Applied Sciences =======
****************************************************************************
* Filename : CROUTE.H
* Author : Viveknath Thulasi
* Description : Include file for CRoute class
*
*
****************************************************************************/
#ifndef CROUTE_H
#define CROUTE_H
//Own Include Files
#include "CPOI.h"
#include "CPoiDatabase.h"
class CRoute {
private:
CWaypoint* m_pWaypoint;
unsigned int m_maxWp;
unsigned int m_nextWp;
CPOI** m_pPoi;
unsigned int m_maxPoi;
unsigned int m_nextPoi;
CPoiDatabase* m_pPoiDatabase;
public:
CRoute(unsigned int maxWp =1 ,unsigned int maxPoi =1);
CRoute(CRoute const & origin);
void connectToPoiDatabase(CPoiDatabase* pPoiDB);
void addWaypoint(CWaypoint const & wp);
void addPoi(std::string namePoi);
double getDistanceNextPoi(CWaypoint const& wp, CPOI& poi);
void print();
~CRoute();
};
/********************
** CLASS END
*********************/
#endif /* CROUTE_H */
| true |
c0dbb00272c60968a4dcc4bcdd8078e38e10f2db | C++ | hyrise-mp/hyrise | /src/test/storage/reference_segment_test.cpp | UTF-8 | 4,840 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base_test.hpp"
#include "gtest/gtest.h"
#include "operators/abstract_operator.hpp"
#include "operators/get_table.hpp"
#include "operators/print.hpp"
#include "operators/table_scan.hpp"
#include "storage/chunk_encoder.hpp"
#include "storage/reference_segment.hpp"
#include "storage/storage_manager.hpp"
#include "storage/table.hpp"
#include "types.hpp"
namespace opossum {
class ReferenceSegmentTest : public BaseTest {
virtual void SetUp() {
TableColumnDefinitions column_definitions;
column_definitions.emplace_back("a", DataType::Int, true);
column_definitions.emplace_back("b", DataType::Float);
_test_table = std::make_shared<opossum::Table>(column_definitions, TableType::Data, 3);
_test_table->append({123, 456.7f});
_test_table->append({1234, 457.7f});
_test_table->append({12345, 458.7f});
_test_table->append({NULL_VALUE, 458.7f});
_test_table->append({12345, 458.7f});
TableColumnDefinitions column_definitions2;
column_definitions2.emplace_back("a", DataType::Int);
column_definitions2.emplace_back("b", DataType::Int);
_test_table_dict = std::make_shared<opossum::Table>(column_definitions2, TableType::Data, 5, UseMvcc::Yes);
for (int i = 0; i <= 24; i += 2) _test_table_dict->append({i, 100 + i});
ChunkEncoder::encode_chunks(_test_table_dict, {ChunkID{0}, ChunkID{1}});
StorageManager::get().add_table("test_table_dict", _test_table_dict);
}
public:
std::shared_ptr<opossum::Table> _test_table, _test_table_dict;
};
TEST_F(ReferenceSegmentTest, RetrievesValues) {
// PosList with (0, 0), (0, 1), (0, 2)
auto pos_list = std::make_shared<PosList>(
std::initializer_list<RowID>({RowID{ChunkID{0}, 0}, RowID{ChunkID{0}, 1}, RowID{ChunkID{0}, 2}}));
auto ref_segment = ReferenceSegment(_test_table, ColumnID{0}, pos_list);
auto& segment = *(_test_table->get_chunk(ChunkID{0})->get_segment(ColumnID{0}));
EXPECT_EQ(ref_segment[0], segment[0]);
EXPECT_EQ(ref_segment[1], segment[1]);
EXPECT_EQ(ref_segment[2], segment[2]);
}
TEST_F(ReferenceSegmentTest, RetrievesValuesOutOfOrder) {
// PosList with (0, 1), (0, 2), (0, 0)
auto pos_list = std::make_shared<PosList>(
std::initializer_list<RowID>({RowID{ChunkID{0}, 1}, RowID{ChunkID{0}, 2}, RowID{ChunkID{0}, 0}}));
auto ref_segment = ReferenceSegment(_test_table, ColumnID{0}, pos_list);
auto& segment = *(_test_table->get_chunk(ChunkID{0})->get_segment(ColumnID{0}));
EXPECT_EQ(ref_segment[0], segment[1]);
EXPECT_EQ(ref_segment[1], segment[2]);
EXPECT_EQ(ref_segment[2], segment[0]);
}
TEST_F(ReferenceSegmentTest, RetrievesValuesFromChunks) {
// PosList with (0, 2), (1, 0), (1, 1)
auto pos_list = std::make_shared<PosList>(
std::initializer_list<RowID>({RowID{ChunkID{0}, 2}, RowID{ChunkID{1}, 0}, RowID{ChunkID{1}, 1}}));
auto ref_segment = ReferenceSegment(_test_table, ColumnID{0}, pos_list);
auto& segment_1 = *(_test_table->get_chunk(ChunkID{0})->get_segment(ColumnID{0}));
auto& segment_2 = *(_test_table->get_chunk(ChunkID{1})->get_segment(ColumnID{0}));
EXPECT_EQ(ref_segment[0], segment_1[2]);
EXPECT_TRUE(variant_is_null(ref_segment[1]) && variant_is_null(segment_2[0]));
EXPECT_EQ(ref_segment[2], segment_2[1]);
}
TEST_F(ReferenceSegmentTest, RetrieveNullValueFromNullRowID) {
// PosList with (0, 0), (0, 1), NULL_ROW_ID, (0, 2)
auto pos_list = std::make_shared<PosList>(
std::initializer_list<RowID>({RowID{ChunkID{0u}, ChunkOffset{0u}}, RowID{ChunkID{0u}, ChunkOffset{1u}},
NULL_ROW_ID, RowID{ChunkID{0u}, ChunkOffset{2u}}}));
auto ref_segment = ReferenceSegment(_test_table, ColumnID{0u}, pos_list);
auto& segment = *(_test_table->get_chunk(ChunkID{0u})->get_segment(ColumnID{0u}));
EXPECT_EQ(ref_segment[0], segment[0]);
EXPECT_EQ(ref_segment[1], segment[1]);
EXPECT_TRUE(variant_is_null(ref_segment[2]));
EXPECT_EQ(ref_segment[3], segment[2]);
}
TEST_F(ReferenceSegmentTest, MemoryUsageEstimation) {
/**
* WARNING: Since it's hard to assert what constitutes a correct "estimation", this just tests basic sanity of the
* memory usage estimations
*/
const auto pos_list_a = std::make_shared<PosList>();
pos_list_a->emplace_back(RowID{ChunkID{0}, ChunkOffset{0}});
pos_list_a->emplace_back(RowID{ChunkID{0}, ChunkOffset{1}});
const auto pos_list_b = std::make_shared<PosList>();
ReferenceSegment reference_segment_a(_test_table, ColumnID{0}, pos_list_a);
ReferenceSegment reference_segment_b(_test_table, ColumnID{0}, pos_list_b);
EXPECT_EQ(reference_segment_a.estimate_memory_usage(),
reference_segment_b.estimate_memory_usage() + 2 * sizeof(RowID));
}
} // namespace opossum
| true |
645fbbc7eee1d94f81edf4828891808006a5d2c0 | C++ | Kishwara/JU-admission-Project-cpp- | /JU ADMISSION PROJECT (cpp)/bunit.cpp | UTF-8 | 579 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#include "bunit.h"
void bunit :: show_bdepts()
{
cout<<setw(40)<<"Faculty of Social Science (B unit)"<<endl;
cout<<"Total number of seats: 340"<<endl;
cout<<"\nDepartments: \n";
cout<<"\n**Economics\n**Geography & Environment\n**Government & Politics\n**Anthropology\n";
cout<<"**Urban & Regional Planing\n**Public Administration\n"<<endl;
}
void bunit :: show_bmarksdist()
{
cout<<"\nMarks Distribution : ";
cout<<"\nMathematics=15, \nGeneral Knowledge=25, \nBangla=10, \nEnglish=15, \nIQ=15"<<endl;
}
| true |
00e384d58b298b805e0c224b662044816c92b22c | C++ | rohitsinghkcodes/DAILY_PROGRAMMING | /2. LearnCodeOnline Challenges/C++ Questions/Challenge30.cpp | UTF-8 | 820 | 4 | 4 | [] | no_license | //Challenge 30:
#include<iostream>
using namespace std;
void sum(int a,int b)
{
cout<<"The sum is: "<<a+b<<endl;
}
void diff(int a,int b)
{
if(a>b)
{
cout<<"The max value is: "<<a<<endl;
cout<<"The min value is: "<<b<<endl;
cout<<"The difference is: "<<a-b<<endl;
}
else
{
{
cout<<"The max value is: "<<b<<endl;
cout<<"The min value is: "<<a<<endl;
cout<<"The difference is: "<<b-a<<endl;
}
}
}
void product(int a,int b)
{
cout<<"The product is: "<<a*b<<endl;
}
void avg(int a,int b)
{
cout<<"The average is: "<<(a+b)/2<<endl;
}
int main()
{
int x1,x2;
cout<<"Enter the two intergers: ";
cin>>x1>>x2;
sum(x1,x2);
diff(x1,x2);
product(x1,x2);
avg(x1,x2);
return 0;
} | true |
1053ffe44d37be35ac798fc35ce97c0ddf591c0b | C++ | drescherjm/QtExamples | /Concurrent/MapAndMapped/BlockingMapMemberFunction.cpp | UTF-8 | 284 | 2.765625 | 3 | [] | no_license | #include <QtConcurrentMap>
#include <iostream>
class MyClass
{
public:
void Test()
{
std::cout << "Test" << std::endl;
}
};
int main()
{
QVector<MyClass> v;
MyClass a;
v.push_back(a);
QtConcurrent::blockingMap(v.begin(), v.end(), &MyClass::Test);
return 0;
}
| true |
b2ecdbf253bd5500437e3160d24135677b8a773f | C++ | a-kashirin-official/spbspu-labs-2018 | /turkin.sergey/A1/rectangle.cpp | UTF-8 | 924 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include "rectangle.hpp"
Rectangle::Rectangle(const double width, const double height, const point_t &pos) :
center_(pos)
{
if (width <= 0 || height <= 0) {
std::cerr << "Width and height of the rectangle must be > 0!";
}
width_ = width;
height_ = height;
}
Rectangle::Rectangle(double x, double y, double width, double height) :
width_(width),
height_(height),
center_({x, y})
{
if (width <= 0 || height <= 0) {
std::cerr << "Width and height of the rectangle must be > 0!";
}
}
double Rectangle::getArea() const
{
return width_ * height_;
}
rectangle_t Rectangle::getFrameRect() const
{
return {height_, width_, {center_.x, center_.y}};
}
void Rectangle::move(const point_t &pos)
{
center_ = pos;
}
void Rectangle::move(double Ox, double Oy)
{
center_.x += Ox;
center_.y += Oy;
}
void Rectangle::printInfo()
{
std::cout << "RECTANGLE:" << std::endl;
}
| true |
e485852a00fb98787f2ae2341542d1b18d262f8b | C++ | yiyunalu/DS | /lab/lab6/check1.cpp | UTF-8 | 2,371 | 4.1875 | 4 | [] | no_license | #include <vector>
#include <iostream>
void reverse_vector(std::vector<int>& vec) {
int temp;
int front;
int back;
if (vec.size() == 1 || vec.size() == 0) {
}
else {
//odd number of elements....
if ( vec.size()%2 != 0 ) {
front = (vec.size() / 2) - 1;
back = (vec.size() / 2) + 1;
}
//even number of elements.....
else if (vec.size()%2 == 0 ) {
front = (vec.size() / 2) - 1;
back = (vec.size() / 2);
}
//swap values.....
while (front >= 0 && back < vec.size()) {
temp = vec[front];
vec[front] = vec[back];
vec[back] = temp;
front--;
back++;
}
}
}
void print_vector (const std::vector<int>& vec) {
std::cout << "The size of the vector is: " << vec.size() << std::endl;
std::cout << "The contents of the vecotr: ";
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> odd;
for (int i = 0; i < 15; ++i) {
odd.push_back(i);
}
std::vector<int> even;
for (int i = 0; i < 20; ++i) {
even.push_back(i);
}
std::vector<int> zero;
std::vector<int> one(1,1);
std::vector<int> two;
two.push_back(1);
two.push_back(2);
std::cout<<"The vector with odd number of elements:"<<std::endl;
std::cout<<"The original one: "<<std::endl;
print_vector(odd);
reverse_vector(odd);
std::cout<<"The reverse one: "<<std::endl;
print_vector(odd);
std::cout<<std::endl;
std::cout<<"The vector with even number of elements:"<<std::endl;
std::cout<<"The original one: "<<std::endl;
print_vector(even);
reverse_vector(even);
std::cout<<"The reverse one: "<<std::endl;
print_vector(even);
std::cout<<std::endl;
std::cout<<"The vector with zero number of elements:"<<std::endl;
std::cout<<"The original one: "<<std::endl;
print_vector(zero);
reverse_vector(zero);
std::cout<<"The reverse one: "<<std::endl;
print_vector(zero);
std::cout<<std::endl;
std::cout<<"The vector with one number of elements:"<<std::endl;
std::cout<<"The original one: "<<std::endl;
print_vector(one);
reverse_vector(one);
std::cout<<"The reverse one: "<<std::endl;
print_vector(one);
std::cout<<std::endl;
std::cout<<"The vector with two number of elements:"<<std::endl;
std::cout<<"The original one: "<<std::endl;
print_vector(two);
reverse_vector(two);
std::cout<<"The reverse one: "<<std::endl;
print_vector(two);
return 0;
} | true |
f1d1dbc19c6d8adfd6aef345b75d7a0caf765585 | C++ | kineticsystem/catkin_ws_robot | /src/add_markers/src/add_markers.cpp | UTF-8 | 2,407 | 2.671875 | 3 | [] | no_license | #include <ros/ros.h>
#include <visualization_msgs/Marker.h>
#include <actionlib/client/simple_action_client.h>
#include "pick_objects/OperationStatus.h"
static pick_objects::OperationStatus status;
// Create a message to display a marget at a given position.
visualization_msgs::Marker createAddMarkerMessage(double x, double y) {
visualization_msgs::Marker marker;
marker.header.frame_id = "map";
marker.header.stamp = ros::Time::now();
marker.ns = "basic_shapes";
marker.id = 0;
marker.type = visualization_msgs::Marker::CUBE;
marker.action = visualization_msgs::Marker::ADD;
marker.pose.position.x = x;
marker.pose.position.y = y;
marker.pose.orientation.w = 1.0;
marker.scale.x = 0.4;
marker.scale.y = 0.4;
marker.scale.z = 0.4;
marker.color.r = 1.0f;
marker.color.g = 0.0f;
marker.color.b = 0.0f;
marker.color.a = 1.0;
marker.lifetime = ros::Duration();
return marker;
}
// Create a message to delete all markers.
visualization_msgs::Marker createDeletionMarkersMessage() {
visualization_msgs::Marker marker;
marker.header.frame_id = "map";
marker.header.stamp = ros::Time::now();
marker.ns = "basic_shapes";
marker.id = 0;
marker.action = visualization_msgs::Marker::DELETEALL;
return marker;
}
// Receive information about a item being loaded or deployed.
void processOperationStatus(const pick_objects::OperationStatusConstPtr &msg) {
status = *msg;
}
int main( int argc, char** argv )
{
ros::init(argc, argv, "marker_node");
ros::NodeHandle n;
ros::Rate r(1);
// Generate markers.
ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("/visualization_marker", 1);
// Read goals.
ros::Subscriber status_sub = n.subscribe<pick_objects::OperationStatus>("/operation_status", 10, processOperationStatus);
while (ros::ok()) {
ros::spinOnce();
if (status.type == "deployed") {
marker_pub.publish(createAddMarkerMessage(status.x, status.y));
ROS_INFO("Package deployed at (x:%f,y:%f)", status.x, status.y);
status.type = "";
} else if (status.type == "loaded") {
marker_pub.publish(createDeletionMarkersMessage());
ROS_INFO("Package loaded at (x:%f,y:%f)", status.x, status.y);
status.type = "";
}
r.sleep();
}
}
| true |
c4bf8d82b8bbaef16f5df4a3971a2c756a67fea9 | C++ | omerb01/CompetitiveProgramming | /class/uva_10363.cpp | UTF-8 | 2,170 | 2.59375 | 3 | [] | no_license | #include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int, int> pii;
int main() {
int n;
cin >> n;
while (n--) {
int nx = 0;
int no = 0;
string line;
char board[3][3];
for (int i = 0; i < 3; i++) {
cin >> line;
for (int j = 0; j < 3; j++) {
board[i][j] = line[j];
if (line[j] == 'X') nx++;
else if (line[j] == 'O') no++;
}
}
int x_win_counter = 0;
int o_win_counter = 0;
//check rows:
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
if (board[i][0] == 'X') x_win_counter++;
else if (board[i][0] == 'O') o_win_counter++;
}
}
//check columns:
for (int i = 0; i < 3; i++) {
if (board[0][i] == board[1][i] && board[1][i] == board[2][i]) {
if (board[0][i] == 'X') x_win_counter++;
else if (board[0][i] == 'O') o_win_counter++;
}
}
//check diags:
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
if (board[0][0] == 'X') x_win_counter++;
else if (board[0][0] == 'O') o_win_counter++;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
if (board[0][2] == 'X') x_win_counter++;
else if (board[0][2] == 'O') o_win_counter++;
}
bool isvalid = true;
if (!(nx == no || nx == no + 1)) isvalid = false;
if (nx == no && x_win_counter > 0) isvalid = false;
if (nx == no + 1 && o_win_counter > 0) isvalid = false;
if (isvalid) cout << "yes" << endl;
else cout << "no" << endl;
}
return 0;
} | true |
811d329854f09762b6aa48ea06525d1c656314fa | C++ | nlarosa/CPlusPlusProgramming | /RationalNumbers/part3/Rational.cpp | UTF-8 | 6,145 | 3.84375 | 4 | [] | no_license | // Nicholas LaRosa
// CSE 20212, Lab 2
//
// Implementation for Rational class
// Allows for non-default constructor
// Overloads arithmetic operators
//
#include <iostream>
#include "Rational.h"
using namespace std;
Rational::Rational() // default constructor initializes rational to 1/1
{
numerator = 1;
denominator = 1;
}
Rational::Rational( int userNumerator, int userDenominator ) // non-default constructor allows the user to specify the numerator and denominator
{
if( userNumerator == 0 )
{
numerator = 0;
denominator = 1; // simplify the denominator if number is zero
}
else if( userDenominator == 0 )
{
numerator = userNumerator;
cout << "A denominator of 0 is not allowed; it has instead been set to 1." << endl;
denominator = 1;
}
else
{
numerator = userNumerator;
denominator = userDenominator;
findGCD(); // if neither is zero, we can proceed to reduce if necessary
if( denominator < 0 ) // if negative, we want the numerator to have the sign
{
numerator *= -1;
denominator *= -1;
}
}
}
ostream & operator<<( ostream &output, const Rational &ourNumber ) // overload the output stream to print a rational object
{
output << "( " << ourNumber.getNumerator() << "/" << ourNumber.getDenominator() << " )";
return output;
}
int Rational::getNumerator() const // get function for instance numerator
{
return numerator;
}
int Rational::getDenominator() const // get function for instance denominator
{
return denominator;
}
void Rational::findGCD() // member function that reduces the numerator and denominator
{ // ie. divides both numerator and denominator by GCD, storing in class variables
int larger = 1;
int smaller = 1; // for Euclidean algorithm, we need to store which number is larger, smaller
int modulus = 1;
if( numerator == denominator ) // if the numerator and denominator are the same, we know the total number is 1
{
numerator = 1;
denominator = 1;
return; // end if this is the case
}
else if( numerator > denominator ) // numerator is bigger
{
larger = numerator;
smaller = denominator;
}
else // denominator is bigger
{
larger = denominator;
smaller = numerator;
}
while( modulus != 0 ) // this is the Euclidean algorithm for the GCD
{
modulus = larger % smaller; // first find the modulus of the two numbers of interest
larger = smaller; // the former divisor is then divided by the modulus on the next pass
smaller = modulus; // until the modulus remainder is zero, then we know the GCD
}
numerator /= larger; // the larger variable is the GCD (because the smaller is 0)
denominator /= larger; // so divide both the numerator and denominator by it to simplify
return;
}
Rational Rational::operator+( const Rational &ourRational ) // allows for the addition of two rational numbers
{
int numerator1 = numerator;
int denominator1 = denominator;
int numerator2 = ourRational.getNumerator();
int denominator2 = ourRational.getDenominator();
denominator1 *= ourRational.getDenominator();
denominator2 *= denominator;
// multiplying numerator and denominator of each rational number by same number
numerator1 *= ourRational.getDenominator(); // to get a common denominator
numerator2 *= denominator;
Rational temp( numerator1+numerator2, denominator1 );
return temp;
}
Rational Rational::operator-( const Rational &ourRational ) // allows for the subtraction of two rational numbers
{
int numerator1 = numerator;
int denominator1 = denominator;
int numerator2 = ourRational.getNumerator();
int denominator2 = ourRational.getDenominator();
denominator1 *= ourRational.getDenominator();
denominator2 *= denominator;
// multiplying numerator and denominator of each rational number by same number
numerator1 *= ourRational.getDenominator(); // to get a common denominator
numerator2 *= denominator;
Rational temp( numerator1-numerator2, denominator1 );
return temp;
}
Rational Rational::operator*( const Rational &ourRational ) // allows for the multiplication of two rational numbers
{
int numerator1 = numerator;
int denominator1 = denominator;
int numerator2 = ourRational.getNumerator();
int denominator2 = ourRational.getDenominator();
numerator1 *= numerator2;
denominator1 *= denominator2; // multiply both the numerator and denominator by eachother
Rational temp( numerator1, denominator1 );
return temp;
}
Rational Rational::operator/( const Rational &ourRational ) // allows for the division of two rational numbers
{
int numerator1 = numerator;
int denominator1 = denominator;
int numerator2 = ourRational.getNumerator();
int denominator2 = ourRational.getDenominator();
numerator1 *= denominator2; // multiply the first rational by the reciprocal of the second
denominator1 *= numerator2;
Rational temp( numerator1, denominator1 ); // and return the first (order matters)
return temp;
}
Rational Rational::operator%( const Rational &ourRational ) // returns the modulus of two rational numbers
{
int numerator1 = numerator;
int denominator1 = denominator;
int numerator2 = ourRational.getNumerator();
int denominator2 = ourRational.getDenominator();
denominator1 *= ourRational.getDenominator();
denominator2 *= denominator;
// multiplying numerator and denominator of each rational number by same number
numerator1 *= ourRational.getDenominator(); // to get common denominator
numerator2 *= denominator; // then we will return the numerator as the modulus
if( numerator2 == 0 )
{
cout << "The modulus operator cannot be performed with a value of zero. The zero value has been changed to 1 for this operation." << endl;
numerator2 = 1;
}
Rational temp( numerator1%numerator2, denominator1 );
return temp;
}
int Rational::operator==( const Rational &ourRational ) // returns true if the rationals are the same, false otherwise
{
if( numerator == ourRational.getNumerator() )
{
if( denominator == ourRational.getDenominator() )
{
return 1; // if both the numerator and denominator are the same, we know the rationals are the same
}
}
return 0;
}
| true |
79a0f263468bab3a79de0a784b2e49955ddae368 | C++ | Dawodu-Johnson/Solutions-to-programming-principles-and-practice-by-Bjarne | /chapter 6/main.cpp | UTF-8 | 11,751 | 3.59375 | 4 | [] | no_license | #include<iostream>
#include<string.h>
#include<vector>
using namespace std;
void error(string s) // for exceptions
{
throw runtime_error(s);
}
void error(string s, string m)
{
throw runtime_error(s+m);
}
/*
class Name_value { // much like Token from 6.3.3
public:
Name_value(string n, int s);
string name;
int score;
};
Name_value::Name_value(string n, int s){
cout << "Was i called" << endl;
name=n;
score=s;
}
int main()
try
{
vector<Name_value> pairs; // pairs is not an object here, it is only of type Name-value hence uses it properties.
string n;
int v;
while (cin>>n>>v) {
for (int i=0; i<pairs.size(); ++i)
if (n==pairs[i].name) error("duplicated name not allowed");
pairs.push_back(Name_value(n,v)); // Note only the constructor function can fill these black hole no other function can
}
for (int i=0; i<pairs.size(); ++i)
cout << '(' << pairs[i].name << ',' << pairs[i].score << ")\n";
return 0;}
catch(runtime_error e){
cout << e.what() <<endl;}
*/
/*int main()
try{
vector<char> numbers;
vector <string> name(4);
name[0]="Ones";
name[1]="Tens";
name[2]="Hundred";
name[3]="Thousand";
char x;
while(cin >> x){
numbers.push_back(x);
}
if(numbers.size()<=4){
for(int i=0; i< numbers.size();++i){
cout << numbers[i] - '0' << name[numbers.size()-i-1] << " ";
}
}
else error("5 or more digits are not accounted for here");
return 0;
}
catch(runtime_error e){
cout << e.what() << endl;}*/
/*
solution to number 10.
int Factorial(int a);
int Permutation(int x, int y);
int Combination(int l, int m);
int main()
try{
cout << "Hi,computations of permutations and combinations is my duty\n";
cout << "Enter two numbers separated by space\n";
cout << "Note <a is the set >, and <b is the subset> i.e a>=b\n";
int a,b;
if(!(cin >>a>>b))error("One or both is not an integer, check again"); // check if read operation was a success.
cout << "Enter 'p' for permutation 'c' for combination or 'pc' for both"<< endl;
string x;
cin >> x;
if(x=="p") cout << " p(" << a << ',' << b << ")" << Permutation(a,b) << endl;
else if(x=="c") cout << " c(" << a << ',' << b << ")" << Combination(a,b) << endl;
else if(x=="pc") {
cout << " p(" << a << ',' << b << ")" << Permutation(a,b) << endl;
cout << " c(" << a << ',' << b << ")" << Combination(a,b) << endl;}
else error("check that wasnt a p or c nor pc");
return 0;}
catch(runtime_error e){
cout << e.what() << endl;}
int Factorial(int a){
// compute a!.
int p=1;
if(a<0) error("Cant compute negative factorial values, try again");
else if(a==0) return 1;
else if(a==1) return 1;
while(a>1){
p*=a;
--a;
}
return p;
}
int Permutation(int x, int y){
if(x<y) error("set cant be less than a subset");
return Factorial(x)/Factorial(x-y);
}
int Combination(int l, int m){
return Permutation(l,m)/Factorial(m);
}
*/
/*This is based on the principle of grammars
sentence :
Noun verb // i.e the most basic of them all
sentence conjunction sentence The basic form extended to another basic more sophisticated form.*/
// vectors of words, appropriately classified:
/*vector<string> nouns;
vector<string> verbs;
vector<string> conjunctions;
void init()
// initialize word classes
{
nouns.push_back("birds");
nouns.push_back("fish");
nouns.push_back("C++"); // I didn't suggest adding "C+" to this exercise
// but it seems some people like that
verbs.push_back("rules");
verbs.push_back("fly");
verbs.push_back("swim");
conjunctions.push_back("and");
conjunctions.push_back("or");
conjunctions.push_back("but");
}
// noun,verb,conjunction function are checkers(i.e they check to see that a function is correct.)
bool is_noun(string w)
{ cout << "THis is the noun function\n";
for(int i = 0; i<nouns.size(); ++i)
if (w==nouns[i]) return true;
return false;
}
bool is_verb(string w)
{
for(int i = 0; i<verbs.size(); ++i)
if (w==verbs[i]) return true;
return false;
}
bool is_conjunction(string w)
{
for(int i = 0; i<conjunctions.size(); ++i)
if (w==conjunctions[i]) return true;
return false;
}
bool sentence()
{
string w;
cin >> w;
if (!is_noun(w)) return false; // return statements can act as a pause to a flow.
string w2;
cin >> w2;
if (!is_verb(w2)) return false;
string w3;
cin >> w3;
if (w3 == ".") return true; // end of sentence
if (!is_conjunction(w3)) return false; // not end of sentence and not conjunction
return sentence(); // look for another sentence provided the last input was a conjunction.
}
int main()
try // error handling.
{
init(); // initialize word tables
while (cin)
{ //The essence of cin is to make the loop run at first then still run at last.
bool b = sentence(); // it is when returns a value before the next line runs.
if (b)
cout << "OK\n";
else
cout << "not OK\n";
cout << "Try again: ";
}
}
catch (runtime_error e) { // It outputs error messages during runtime .
cout << e.what() << '\n';
}
*/
/*
// Exercise 4.
class NameValue
{
public:
string name;
double score;
NameValue(string n, double s): name(n), score(s) {}
};
int main()
try{
vector<NameValue>pairs; // vector of classes.
string name;
double score;
cout << "Enter a name and score separated by a white space e.g Johnson 33 \n";
cout << "Enter \"no more\" to terminate i.e no more \n";
while(cin >> name >> score)
{
for(int i=0; i<pairs.size(); ++i) // checking asynchronously...
{
if(pairs[i].name==name) error(name, " repeated twice. not allowed ");
}
pairs.push_back(NameValue(name,score)); // the constructor does the initializing here.
}
cin.clear();
cin.ignore(100,'\n'); // makes the input stream available again.
cout << "\n\n(Name,Score)" << endl;
for(int i=0; i<pairs.size(); ++i)
{
cout << '(' << pairs[i].name << ',' << pairs[i].score << ')' << endl;
}
return 0;
}
catch(runtime_error &e)
{ cerr << e.what() << endl;
}
catch(...){ cerr << "An error occured " << endl;}
*/
// exercise 5, ans: "the have been added to the grammar /
//Exercise 6.
/*
bool verb(string);
bool noun(string );
bool conjuction(string);
bool sentence();
int main()
{
if(sentence()) cout << "OK" << endl;
else cout << "Not OK " << endl;
return 0;
}
bool noun(string noun)
{
vector<string>nouns;
nouns.push_back("birds");
nouns.push_back("fish");
nouns.push_back("C++");
for(int i=0; i<nouns.size();++i)
{
if(noun==nouns[i]) return true;
}
return false;
}
bool verb(string verb)
{
vector<string>verbs;
verbs.push_back("rule");
verbs.push_back("fly");
verbs.push_back("swim");
for(int i=0; i<verbs.size();++i)
{
if(verb==verbs[i])return true;
}
return false;
}
bool conjuction(string conjuction)
{
vector<string>conjuctions;
conjuctions.push_back("and");
conjuctions.push_back("but");
conjuctions.push_back("or");
for(int i=0; i<conjuction.size();++i)
{
if(conjuction==conjuctions[i])return true;
}
return false;
}
bool sentence()
{
char space,t;
string n,v,c,trial;
cin >> n;
if(noun(n))
{
cin >> v;
if(verb(v))
{
//cin.get(space); // alternative method check if it was a space.
//cin.putback(space); // put it back
cin >> trial; // if the next input is now a "." then we are done.
if(trial == ".")return true;
else if(conjuction(trial)) return sentence();
}
}
return false;
}
*/
// Exercise 7 ans, just write a grammar similar to the calculation operators, replacing *+/, with necessary symbols.
// placing the unary operators in the number category.
/*
//Exercise 8.
// the key to the solution is to create an index monitor for the individual character being entered.
int main()
{
vector<string> letters;
letters.push_back("j");
letters.push_back("o");
letters.push_back("h");
letters.push_back("n");
int cows=0, bulls=0;
cout << "Enter 4 letters separated by a space \n";
cout << "e.g j h n p \n";
while(bulls!=4)
{
bulls=0,cows=0;
// placed at the top,reseting the bulls and the cows,
// note that if it is placed at the end.
// the loop wont end even when
// bull is 4, because it will have been reset before getting to the conditions.
string test;
int index=0; // the index monitor for your variable test.
for(int j=0; j<letters.size();++j)
{
cin>> test;
for(int i=0; i<letters.size();++i)
{
if(test==letters[i] && index==i) {++bulls; ++index;}
else if(test==letters[i])
{
++cows;
++ index;
}
}
}
cout << "bulls = " << bulls << " cows = " << cows << endl;
index=0; // reset
}
return 0;
// there is still more to make this solution more elegant (error handling)
//but no time.
}
*/
/*//Exercise 9
int main()
try{
vector<int>digits;
vector<string>position;
position.push_back("ones");
position.push_back("tens");
position.push_back("hundred");
position.push_back("Thousand");
char ch; // this represents individual digits...
cout << "Enter a number not more than 4 digits " << endl;
cout << "Enter ';' to terminate \n";
cout << "I.e 2000 ; \n";
while(cin >> ch)
{
if(ch<'0' || ch>'9')break; // break, if ch-'0' is not a number.
digits.push_back(ch-'0'); // The logic; coverts the character to an integer.
}
if(digits.size()==0) error("No value entered");
if(position.size()<digits.size()) error("Too many digits");
int num=0;
for(int i=0; i<digits.size(); ++i)
{
if(digits[i])cout << digits[i] << position[digits.size()-i-1] << ' ';
// we dont want to print 1000 as 1 thousand 0 hundred 0 tens 0 ones
// so we encompass the cout in an if statement depending on the number.
num = num*10 + digits[i]; // composition of digits.(decomposition was done in chapter 4 or 5).
}
cout << endl;
cout << "The number is " << num << endl;
return 0;
}
catch(runtime_error &e)
{
cerr << e.what() << endl;
}
catch (...)
{
cerr << "An error occured \n";
}
*/
/*
//Exercise 10;
double permutation(int a, int b);
double combination(int, int);
int factorial(int);
int main()
try
{
int a=0,b=0;
char choice;
cout << "Enter two numbers of your choice \n";
cin >> a >> b;
cout << "Enter p for permutation or c for combination \n";
cin >> choice;
if(choice=='p')
{
cout << "The permutation of " << a << " And " << b
<< " = " << permutation(a,b) << endl;
}
else if(choice=='c')
{
cout << "The combination of " << a << " And " << b
<< " = " << combination(a,b) << endl;
}
else error("The choice of calculation here isn't recognized, try p or c");
}
catch(runtime_error &e)
{
cerr << e.what() << endl;
}
catch(...)
{
cerr << "An error occured " << endl;
}
int factorial(int a)
{
if(a<0) error("Negative numbers aren't allowed");
else if(a==1) return 1;
else return a * factorial(a-1);
}
double permutation(int a, int b)
{
if(a <0 || b<0 )error ("negative number is not allowed ");
double m=0;
m= factorial(a)/factorial(a-b);
return m;
}
double combination(int a,int b)
{
if(a<0 || b<0) error (" negative number is not allowed" );
double m=0;
m= permutation(a,b)/factorial(b); // notice the chaining;
// i made permutation depend on factorial.
//while combination depends on both.
return m;
}
*/
| true |
42f126627684680629acfb87186e137c7c8a322b | C++ | rpbrandau/OSU-Coursework | /162 - Intro pt 2 - Labs/LabH/LabH_iMergesort.cpp | UTF-8 | 2,098 | 3.390625 | 3 | [] | no_license | //Source: http://stackoverflow.com/questions/22866585/c-implementation-of-iterative-merge-sort-crashing-at-large-input-sizes-due-to
//Notes: this program was not very intuitive for me to use. Especially with defining a global variable, and using namespace std
//#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
#define SIZE 100000
int L[100000];
int R[100000];
using namespace std;
int min(int a, int b);
void Merge(int data[], int p, int q, int r);
void MergeSort(int data[], int p, int r);
bool IsSorted(int data[], int size);
int main()
{
int data[SIZE];
for (int i = 0; i < 10; i++)
{
for (int i = 0; i < SIZE; i++)
{
data[i] = rand() % 10000;
}
int iStart, iStop, iTotal;
iStart = clock();
MergeSort(data, 0, SIZE - 1);
iStop = clock();
iTotal = (iStop - iStart) / double(CLOCKS_PER_SEC) * 1000;
if (IsSorted(data, SIZE))
cout << "Sorted correctly" << endl;
else
cout << "incorrect sorting" << endl;
cout << "Time to run " << iTotal << endl;
}
return 0;
}
bool IsSorted(int data[], int size)
{
int i;
for (i = 0; i<(size - 1); i++)
{
if (data[i] > data[i + 1])
return false;
}
return true;
}
void MergeSort(int data[], int p, int r)
{
for (int i = 1; i< SIZE; i *= 2)
for (int j = 0; j < SIZE; j += 2 * i)
Merge(data, j, j + i - 1, min((j + 2 * i - 1), SIZE - 1));
}
void Merge(int data[], int p, int q, int r)
{
if (q >= SIZE)q = (r + p) / 2;
int sizeL = q - p + 2;
int sizeR = r - q + 1;
for (int i = 0; i < sizeL - 1; i++)
L[i] = data[i + p];
for (int i = 0; i < sizeR - 1; i++)
R[i] = data[i + q + 1];
int max;
if (L[sizeL - 2]>R[sizeR - 2])
max = L[sizeL - 2] + 1;
else
max = R[sizeR - 2] + 1;
L[sizeL - 1] = R[sizeR - 1] = max;
int indexL = 0, indexR = 0;
for (int i = p; i <= r; i++) {
if (L[indexL] <= R[indexR]) {
data[i] = L[indexL];
indexL++;
}
else {
data[i] = R[indexR];
indexR++;
}
}
}
int min(int a, int b) {
return !(b<a) ? a : b;
}
| true |
9f9882a0b0c89b51ce777ef1be1acdb2a084102f | C++ | bi3mer/northeastern_game_ai | /a_star/a_star/Map.cpp | UTF-8 | 2,863 | 3.03125 | 3 | [] | no_license | #include "Map.h"
Map::Map(Json::Value root)
{
Json::Value matrix = root.get("Map", Json::arrayValue);
h = matrix.size();
w = (int) matrix[0].asString().size();
for (int i = 0; i < h; ++i)
{
std::vector<int> newVector;
std::string row = matrix[i].asString();
for (int j = 0; j < w; ++j)
{
if (row[j] == 'X')
{
newVector.push_back(0); // I've decided 0 to represent a wall.
}
else
{
newVector.push_back((int)row[j] - 48);
}
}
costs.push_back(newVector);
}
}
Map::Map(const Map& map)
{
w = map.w;
h = map.h;
for (int y = 0; y < h; ++y)
{
costs.push_back(std::vector<int>(map.costs[y]));
}
}
// not doing error checking. I'll let it crash if it gets here without having
// already had error checking. For this I need to re-orient the Y value since
// the map is oriented from the bottom left.
const int Map::getCost(int x, int y)
{
return costs[(size_t) h - 1 - y][x];
}
// implemented for all eight directions
const std::vector<std::pair<int, Point>> Map::getTaxiCabNeighbors(const int x, const int y)
{
std::vector<std::pair<int, Point>> neighbors;
for (int yMod = -1; yMod <= 1; ++yMod)
{
for (int xMod = -1; xMod <= 1; ++xMod)
{
if ((xMod == 0 && yMod != 0) || (xMod != 0 && yMod == 0))
{
int newX = x + xMod;
int newY = y + yMod;
if (newX < 0 || newX >= w) continue;
if (newY < 0 || newY >= h) continue;
int cost = getCost(newX, newY);
if (cost > 0)
{
neighbors.push_back(std::make_pair(cost, Point(newX, newY)));
}
}
}
}
return neighbors;
}
const std::vector<std::pair<int, Point>> Map::getNeighbors(const int x, const int y)
{
std::vector<std::pair<int, Point>> neighbors;
for (int yMod = -1; yMod <= 1; ++yMod)
{
for (int xMod = -1; xMod <= 1; ++xMod)
{
if (xMod == 0 && yMod == 0) continue;
int newX = x + xMod;
int newY = y + yMod;
if (newX < 0 || newX >= w) continue;
if (newY < 0 || newY >= h) continue;
int cost = getCost(newX, newY);
if (cost > 0)
{
neighbors.push_back(std::make_pair(cost, Point(newX, newY)));
}
}
}
return neighbors;
}
// alternatively, I could compare the two resulting hash codes.
const bool Map::equals(Map& map)
{
if (w != map.w || h != map.h)
{
return false;
}
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
if (costs[y][x] != map.costs[y][x])
{
return false;
}
}
}
return true;
}
const std::string Map::getHash()
{
std::string hash = "";
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
hash += std::to_string(costs[y][x]);
}
}
return hash;
}
const void Map::print()
{
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
std::cout << costs[i][j];
}
std::cout << std::endl;
}
}
const int Map::getHeight()
{
return h;
}
const int Map::getWidth()
{
return w;
}
| true |
15e0d181fc51d58b02bff84c9c823ebde1a0eeb9 | C++ | thomaspiccolo/Projet-LG | /analyseur/xmlNode.h | UTF-8 | 381 | 2.796875 | 3 | [] | no_license | #ifndef XMLNODE_H
#define XMLNODE_H
#include <string>
#include <iostream>
/* XML Node : Classe mère de notre structure XML */
class xmlNode
{
public:
/*Constructeur*/
xmlNode();
/*Destructeur*/
virtual ~ xmlNode();
/*Affichage de l'arbre dans le terminal */
virtual void display();
/*Ecriture de l'arbdre dans un string */
virtual std::string write();
};
#endif
| true |
7a3cc45bc52301a62e09ad9be55619485b1251d6 | C++ | HarrisonJM/ProtocolDeveloper | /myLibraries/networkCommunication/src/networkCommunication.cpp | UTF-8 | 7,233 | 2.796875 | 3 | [] | no_license | /*!
* @brief Handles communication
*
* Deals with outgoing and incoming communication and passes the information
* to whatever requires it
*
* @addtogroup NetworkCommunication Library
* @{
* @date March 2018
*
* @todo perror needs changing to try catch blocks the use strerror
* @todo refactor out setInterface. Do it in the constructor
*/
#include <iostream>
#include <cstdarg>
#include <freeFunctionsAndWrappers/cStdLib.h>
#include <freeFunctionsAndWrappers/cNetComm.h>
#include "libnetworkCommunication/networkCommunication.h"
namespace networkCommunication
{
bool NetworkCommunication::_alreadyConnected = false;
/*!
* @brief Constructor
*/
NetworkCommunication::NetworkCommunication()
:
_portToSendTo(9687)
, _destinationAddress("localhost")
, _outSocket(-1)
, _tcpOrUDP(1)
, _servInfo(nullptr)
, _netCommFunctions(std::make_shared<cFunctions::cNetComm>())
{
}
/*!
* @brief Constrcutor, provides an iOInterface set
* @param iOInterface The iOFunctions we'd like to use (put through an I_cNetComm interface.
* Only used for testing purposes)
*/
NetworkCommunication::NetworkCommunication(std::shared_ptr<cFunctions::I_cNetComm> iOInterface)
: _portToSendTo(9687)
, _destinationAddress("127.0.0.1")
, _outSocket(-1)
, _tcpOrUDP(1)
, _servInfo(nullptr)
, _netCommFunctions(std::move(iOInterface))
{
}
/*!
* @brief Returns the plugins name
* @return The name of the plugin (as a const char*)
*/
const char* NetworkCommunication::getPluginName()
{
return "NetworkCommunication-def";
}
/*!
* @brief Returns the version of the plugin
* @return The plugin version
*/
const char* NetworkCommunication::getPluginVersion()
{
return "1.0";
}
/*!
* @brief Returns the plugin _type_
* @return The the plugin is (as an enum)
*/
pluginLoader::PLUGINTYPE_t NetworkCommunication::getPluginType()
{
return pluginLoader::PLUGINTYPE_t::COMMUNICATION;
}
/*!
* @brief Sends the provided data on the socket
* @param payLoad_p A pointer to the information we want to send
* @param size The size of the information we want to send
* @return True on success, otherwise false
*/
ssize_t NetworkCommunication::SendData(void* payLoad_p
, size_t size)
{
ssize_t numBytes = _netCommFunctions->sendTo(_outSocket
, payLoad_p
, size
, MSG_NOSIGNAL);
if (-1 == numBytes)
{
perror("Send");
}
return numBytes;
}
/*!
* @brief Receives data ready to pass be processed
* @param payLoad_p A pointer to where to store the data
* @param size The size of the received data
* @return None
*/
ssize_t NetworkCommunication::ReceiveData(void* payLoad_p
, size_t size)
{
ssize_t numBytes = _netCommFunctions->recvFrom(_outSocket
, payLoad_p
, size
, 0);
if (-1 == numBytes)
{
perror("Recv");
}
return numBytes;
}
/*!
* @brief Establishes a connection with the remote
* @return True on success, otherwise false
*/
bool NetworkCommunication::EstablishConnection()
{
if (!_alreadyConnected)
if (SetupAddrInfo())
if (DoSocketAndConnect())
{
_alreadyConnected = true;
return _alreadyConnected;
}
return _alreadyConnected;
}
/*!
* @brief Disconnects form the remote
* @return None
*/
void NetworkCommunication::Disconnect()
{
close(_outSocket);
}
/*!
* @brief Sets the port we wish to send to
* @param port The port we wish to send to
*/
void NetworkCommunication::SetPortToSendTo(int port)
{
_portToSendTo = port;
}
/*!
* @brief Sets the destination address we wish to send to
* @param destinationAddress The destionation address we wisht o send to
*/
void NetworkCommunication::SetDestinationAddress(char* destinationAddress)
{
_destinationAddress = destinationAddress;
}
/*!
* @brief Sets whether we are a TCP or UDP connection
* @param tcpOrUDP 1 for TCP 0 for UDP
*/
void NetworkCommunication::SetTCPOrUDP(int tcpOrUDP)
{
_tcpOrUDP = tcpOrUDP;
}
/*!
* @brief Sets additional server info with the addrinfo struct
* @param _servinfo The additional server info
*/
void NetworkCommunication::SetServInfo(addrinfo* _servinfo)
{
_servInfo = _servinfo;
}
/*!
* @brief Sets the interface we'll be using to communicate with
* @param iOInterface A shared_ptr to the interface we'll be using
*
* @return None
*/
void NetworkCommunication::SetInterface(std::shared_ptr<cFunctions::I_cNetComm> iOInterface)
{
_netCommFunctions = iOInterface;
}
/*!
* @brief setups up the ProtDev connection/client Information
* @return None
*/
bool NetworkCommunication::SetupAddrInfo()
{
addrinfo hints = {0};
addrinfo* addrsGotten;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = _tcpOrUDP ? SOCK_STREAM : SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // Do *my* IP for me
int status = 0;
status = _netCommFunctions->getaddressinfo(_destinationAddress.c_str()
, std::to_string(_portToSendTo).c_str()
, &hints
, &addrsGotten);
/*!
* @todo Change when using [out] values worked out
* See related tests for this class
*/
if (0 != status)
if (nullptr == _servInfo)
{
//! @todo exception handling
fprintf(stderr
, "getaddr failure in SetupAddrInfo():#%d: %s"
, __LINE__
, gai_strerror(status));
return false;
}
_servInfo = addrsGotten;
return true;
}
/*!
* @brief sets up the socket and connects to the remote
* @return None
*/
bool NetworkCommunication::DoSocketAndConnect()
{
addrinfo* p;
// Loop through all the results and bind to each
for (p = _servInfo; nullptr != p; p = p->ai_next)
{
_outSocket = _netCommFunctions->createSocket(p->ai_family
, p->ai_socktype
, p->ai_protocol);
if (-1 == _outSocket)
{
perror("client socket");
continue;
}
if (-1 == _netCommFunctions->connectToRemote(_outSocket
, p->ai_addr
, p->ai_addrlen))
{
_netCommFunctions->closeConnection(_outSocket);
perror("client connect");
continue;
}
break;
}
if (nullptr == p)
{
//! @todo exception handling
fprintf(stderr
, "Could not connect to remote\n");
return false;
}
_netCommFunctions->freeaddressinfo(_servInfo);
return true;
}
} /* namespace NetworkCommunication */
/*! @} */
| true |
ac94fa77ab3639ac5af3d1005cb28fbbf1ff088e | C++ | indra215/coding | /geeksforgeeks/stack/Easy string.cpp | UTF-8 | 801 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <stack>
using namespace std;
string compress(string inp)
{
int len = inp.length(), i = 0;
stack<char> s;
string res = "";
while(i < len){
if(s.empty() || s.top() == tolower(inp[i])){
s.push(tolower(inp[i]));
i++;
}else{
int count = 0;
char ch = s.top();
// cout << ch << "\n";
while(!s.empty()){
count++;
s.pop();
}
res += (to_string(count) + ch);
// cout << res << "\n";
}
}
int count = 0;
char ch = s.top();
// cout << ch << "\n";
while(!s.empty()){
count++;
s.pop();
}
res += (to_string(count) + ch);
// cout << res << "\n";
return res;
}
int main() {
int T;
cin >> T;
for(int i=0;i<T;i++){
string inp;
cin >> inp;
string res = compress(inp);
cout << res << "\n";
}
return 0;
} | true |
a824cd3a2e4d0a92551270c48027a8bdf6d4463e | C++ | Zmestabrook/CSC150Projects | /pp03/pp03.cpp | UTF-8 | 2,333 | 3.671875 | 4 | [] | no_license | /*
PP03 - Zackary Estabrook & Brennan Lamoreaux
Computer Science 150 10am
09/17/2018
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double sum = 0;
double average = 0;
double max = 0;
double stdDev = 0;
double curve = 0;
int numGrades = 0;
int grade;
int A = 0;
int B = 0;
int C = 0;
int D = 0;
int F = 0;
double sumSquares = 0;
int curveFinal = 0;
cout << endl << "SDSMT Test Curve Calculator" << endl;
cout << endl << "Enter the number of students: ";
cin >> numGrades;
for (int i = 0; i < numGrades; i++)
{
cout << "Enter the grade for student " << i + 1 << ": ";
cin >> grade;
if (grade <= 100 && grade >= 90)
{
A++;
}
else if (grade < 90 && grade >= 80)
{
B++;
}
else if (grade < 80 && grade >= 70)
{
C++;
}
else if (grade < 70 && grade >= 60)
{
D++;
}
else if (grade < 60)
{
F++;
}
if (i == 0) {
max = grade;
}
else if (max < grade) {
max = grade;
}
sumSquares = sumSquares + pow(grade, 2);
sum = sum + grade;
if (i == (numGrades - 1)) {
// standard deviation
stdDev = sqrt(((numGrades * sumSquares) - pow(sum, 2)) / pow(numGrades, 2));
//average
average = sum / numGrades;
//curve
if (average < 70 && max != 100)
{
curve = ((75 - average) * 0.9) + 0.5;
curveFinal = (int)curve;
}
}
}
cout << endl << "Number of A's : " << A;
cout << endl << "Number of B's : " << B;
cout << endl << "Number of C's : " << C;
cout << endl << "Number of D's : " << D;
cout << endl << "Number of F's : " << F;
cout << endl;
cout << endl << "Max : " << max;
cout << fixed << setprecision(3);
cout << endl << "Average : " << average;
cout << endl << "Std Dev : " << stdDev;
cout << endl << "Curve : " << curveFinal;
cout << endl;
return 0;
} | true |
0a1a4d83f8ecb97d1dc3b30217da3af4a130dcb6 | C++ | panditprogrammer/CPP | /class5.cpp | UTF-8 | 538 | 3.59375 | 4 | [] | no_license | //class and contructor
#include <iostream>
#include <stdlib.h>
using namespace std;
//creating class
class complex
{
private:
int a,b;
public:
void setValue(int x,int y)
{
a = x; b = y;
}
void getValue()
{
cout<<" a = "<<a<<"b = "<<b<<endl;
}
//creating constructor
complex()
{
cout<<"this is constructor\n";
}
};
int main()
{
system("cls");
complex c1,c,c2; //constructor is implicitly invoked when object is created
system("pause");
return 0;
} | true |
614fc9816b22cdadc88404d6b92e3b7ae66b4d2e | C++ | alexvelea/lot-info-2018-2 | /sortall/bc_n3.cc | UTF-8 | 569 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
ifstream cin("sortall.in");
ofstream cout("sortall.out");
int n; cin >> n;
vector<int> v(n);
for (auto& iter : v) {
cin >> iter;
}
unsigned cost = 0;
for (int i = 0; i < n; ++i) {
set<int> s;
for (int j = i; j < n; ++j) {
s.insert(v[j]);
int num = 1;
for (auto&& iter : s) {
cost += unsigned(iter) * num++;
}
}
}
cout << cost << endl;
return 0;
} | true |
588f4f9d3bed8b2212affe50a6e05e0bc4702139 | C++ | Stevethe12/CarteFPGA | /TemplateVector/TemplateVector/myVector.cpp | UTF-8 | 3,546 | 3.671875 | 4 | [
"Apache-2.0"
] | permissive | #include "myVector.h"
template <typename T>
myVector<T> myVector<T>::getObj()
{
return this->m_vector;
}
template <typename T>
int myVector<T>::getCapacity()
{
return this->capacity;
}
template <typename T>
bool myVector<T>::clear()
{
for (int i = 0; i < size; i++)
{
m_vector[i] = NULL;
}
return true;
}
template <typename T>
bool myVector<T>::insert(T data, int index)
{
if (index == capacity)
push(data);
else
m_vector[index] = data;
if (m_vector[index] == nullptr)
{
return EXIT_FAILURE;
}
else
{
return true;
}
}
/**************************************************************************
* Add an element at last
*
*
*
*
***************************************************************************/
template <typename T>
bool myVector<T>::push_back(T element)
{
bool IsAdded = false;
/* Check if we have enough space */
if (size == capacity)
{
myVector <T>* temp = new myVector<T>[2 * capacity];
if (temp == nullptr)
{
return EXIT_FAILURE;
}
for (int i = 0; i < capacity; i++)
{
temp[i] = m_vector[i];
}
delete[] m_vector;
capacity *= 2;
m_vector = temp;
}
m_vector[size] = element;
if (m_vector != nullptr)
{
IsAdded = true;
size++;
}
return IsAdded;
}
/**************************************************************************
*
*
*
*
*
***************************************************************************/
template <typename T>
bool myVector<T>::pop_back()
{
m_vector[size] = NULL;
size--;
return true;
}
/**************************************************************************
*
*
*
*
*
***************************************************************************/
template <typename T>
bool myVector<T>::resize()
{
if (capacity > size)
capacity = size;
return true;
}
/**************************************************************************
*
*
*
*
*
***************************************************************************/
template <typename T>
myVector<T> myVector<T>::operator[](int index )
{
if (index > size)
{
std::cout << "Index out of bound" << std::endl;
}
else
{
return m_vector[index];
}
}
/**************************************************************************
*
*
*
*
*
***************************************************************************/
template <typename T>
myVector<T> myVector<T>::operator++(T m_vector)
{
return 0;
}
/**************************************************************************
*
*
*
*
*
***************************************************************************/
template <typename T>
myVector<T> myVector<T>::operator--(T m_vector )
{
return 0;
}
/**************************************************************************
*
*
*
***************************************************************************/
template <typename T>
myVector<T> myVector<T>::operator+=(T m_vector)
{
return 0;
}
/**************************************************************************
*
*
*
***************************************************************************/
template <typename T>
myVector<T> myVector<T>::operator-=(T m_vector)
{
return 0;
}
/**************************************************************************
*
*
*
***************************************************************************/
template <typename T>
std::ostream & operator<<(std::ostream & os,const myVector<T> vec)
{
//os << vec[]
}
| true |
5371b198c50bf1f003f57cf2601355943b377106 | C++ | icsfy/some_little_stuff | /c++/ch13/cd.h | UTF-8 | 1,914 | 3.296875 | 3 | [] | no_license | #ifndef CD_H
#define CD_H
class Cd {
private:
char performers[50];
char label[20];
int selections;
double playtime;
public:
Cd(const char * s1, const char * s2, int n, double x);
Cd(const Cd & d);
Cd();
virtual ~Cd();
virtual void Report() const;
virtual Cd & operator=(const Cd & d);
};
#endif
#ifndef CD_CPP
#define CD_CPP
#include <iostream>
Cd::Cd(const char * s1, const char * s2, int n, double x)
{
for(int i=0; s1[i] != '\0' && i<50; i++){
performers[i] = s1[i];
i!=49?performers[i+1]='\0':performers[49]='\0';
}
for(int i=0; s2[i] != '\0' && i<20; i++){
label[i] = s2[i];
i!=19?label[i+1]='\0':label[19]='\0';
}
selections = n;
playtime = x;
}
Cd::Cd(const Cd & d)
{
for(int i=0; d.performers[i] != '\0' && i<50; i++){
performers[i] = d.performers[i];
i!=49?performers[i+1]='\0':performers[49]='\0';
}
for(int i=0; d.label[i] != '\0' && i<20; i++){
label[i] = d.label[i];
i!=19?label[i+1]='\0':label[19]='\0';
}
selections = d.selections;
playtime = d.playtime;
}
Cd::Cd()
{
performers[0]='p', performers[1]='\0';
label[0]='l', label[1]='\0';
selections = 0;
playtime = 0.0;
}
Cd::~Cd()
{
}
void Cd::Report() const
{
std::cout << " Performers: " << performers << std::endl
<< " Label: " << label << std::endl
<< " Number of selections: " << selections << std::endl
<< " Playing time in minutes: " << playtime << std::endl;
}
Cd & Cd::operator=(const Cd & d)
{
if(this == &d)
return *this;
for(int i=0; d.performers[i] != '\0' && i<50; i++){
performers[i] = d.performers[i];
i!=49?performers[i+1]='\0':performers[49]='\0';
}
for(int i=0; d.label[i] != '\0' && i<20; i++){
label[i] = d.label[i];
i!=19?label[i+1]='\0':label[19]='\0';
}
selections = d.selections;
playtime = d.playtime;
return *this;
}
#endif
| true |
763490915322ea34de0c83cdb11ffaa31321be91 | C++ | kkunalguptaaa/codingBlocks | /6-sorting/kthRoot.cpp | UTF-8 | 614 | 2.875 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
long long kthRoot(long long n,long long k){
long long l=0;
long long h=n;
long long mid=(l+h)/2;
long long ans;
while(l<=h){
mid=(l+h)/2;
if(pow(mid,k)==n){
return mid;
}
else if(pow(mid,k)<n){
ans=mid;
l=mid+1;
}
else{
h=mid-1;
}
}
return ans;
}
int main(){
int t;
cin >> t;
while(t--){
long long n,k;
cin >> n >> k;
long long res=kthRoot(n,k);
cout << res << endl;
}
} | true |
ebe21ed5e901b38ee3e99cda0e748347fcadaed5 | C++ | Rohan7546/Coding_Ninjas_Competitive_Programming | /Dynamic_Programming_2/trader_profit.cpp | UTF-8 | 2,277 | 3.390625 | 3 | [] | no_license | /*
Trader Profit
Send Feedback
Mike is a stock trader and makes a profit by buying and selling stocks. He buys a stock at a lower price and sells it at a higher price to book a profit. He has come to know the stock prices of a particular stock for n upcoming days in future and wants to calculate the maximum profit by doing the right transactions (single transaction = buying + selling). Can you help him maximize his profit?
Note: A transaction starts after the previous transaction has ended. Two transactions can't overlap or run in parallel.
The stock prices are given in the form of an array A for n days.
Given the stock prices and a positive integer k, find and print the maximum profit Mike can make in at most k transactions.
Input Format:
The first line of input contains an integer T(number of test cases).
The first line of each test case contains a positive integer k, denoting the number of transactions.
The second line of each test case contains a positive integer n, denoting the length of the array A.
The third line of each test case contains n space-separated positive integers, denoting the prices of each day in the array A.
Output Format
For each test case print the maximum profit earned by Mike on a new line.
Constraints:
1 <= T <= 10^3
0 < k <= 10
2 <= n <= 10^4
0 <= elements of array A <= 10^5
Sample Input
3
2
6
10 22 5 75 65 80
3
4
20 580 420 900
1
5
100 90 80 50 25
Sample Output
87
1040
0
*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll dp[10001][11][2];
ll transaction (ll *a, ll n, ll k, ll cur_status) {
if (k <= 0) {
return 0;
}
if (n == 0) {
return 0;
}
if (dp[n][k][cur_status] != -1) {
return dp[n][k][cur_status];
}
if (cur_status) {
return dp[n][k][cur_status] = max(transaction(a + 1, n - 1, k, 1), transaction(a + 1, n - 1, k - 1, 0) + a[0]);
}
else {
if (k > 0) {
return dp[n][k][cur_status] = max(transaction(a + 1, n - 1, k, 0), transaction(a + 1, n - 1, k, 1) - a[0]);
}
}
}
int main() {
ll t;
cin >> t;
while (t--) {
ll n, m;
cin >> n >> m;
ll a[m];
for (ll i = 0; i < m; i++) {
cin >> a[i];
}
memset(dp, -1, sizeof(dp));
cout << transaction(a, m, n, 0) << "\n";
}
} | true |
05146a06148ecf220fdc93f854bfe0d454bf3422 | C++ | AsulconS/CompetitiveProgramming | /URI/uri1014.cpp | UTF-8 | 181 | 2.671875 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int km;
double l;
cin >> km >> l;
printf("%.3lf km/l\n", (double)km / l);
return 0;
}
| true |
f6160b61b21c8ce7f252f5bc383e76d45043fd1f | C++ | jbatea/Abstract_Vm | /includes/Lexer.class.hpp | UTF-8 | 986 | 2.765625 | 3 | [] | no_license | #ifndef LEXER_CLASS_HPP
#define LEXER_CLASS_HPP
class Lexer {
public:
Lexer( void ); // Default constructor
Lexer( Lexer const & src ); // Copy constructor
~Lexer( void ); // Destructor
Lexer & operator=( Lexer const & rhs );// Assignement
void getArg( int ac, char **av ) noexcept(false);
std::deque<const Lexeme *> const & getLexemes( void ) const;
private:
void _lexer( std::string const & line ) noexcept(false);
eCategory _getLexemeCategory(std::string const & _lexeme);
void _getLines(std::vector<std::string> lines) noexcept(false);
void _getFile(char *av ) noexcept(false);
void _getInput( void );
void _checkArgs(int ac) const noexcept(false);
void _timeoutHandler(bool *timeout);
std::deque<const Lexeme *> _lexemes;
};
#endif | true |
c54ce77034eaaf9390ec29f9a3e28b8fa29a7c86 | C++ | dimazilla123/graph-battle | /src/headers/unit.h | UTF-8 | 1,073 | 2.609375 | 3 | [] | no_license | #ifndef UNIT_H
#define UNIT_H
#include <vector>
#include "item.h"
#ifndef SUCCSES_SHOT
#define SUCCSES_SHOT 0
#endif
#ifndef FAIL_SHOT
#define FAIL_SHOT 1
#endif
#ifndef DESTROYED
#define DESTROYED 1
#endif
#ifndef ALIVE
#define ALIVE 0
#endif
#ifndef INV_PUSHED
#define INV_PUSHED 0
#endif
class Unit {
public:
/* data */
int attack(Unit* target);
void dealDamage(int dmg);
void wait();
virtual void onDestroy()=0;
std::vector<Item*> Inventory;
char* Name;
int Str;
int Dx;
int Intt;
int Wis;
int Speed;
int Imm;
int MaxHp;
int Hp;
int Dmg;
int AC;
int RegRate;
int MovePoints;
int MaxMana;
int Mana;
int RegManaRate;
Unit(char* name,int str,int dx,int intt,int wis,int speed,int imm);
//virtual ~Unit ();
void updateChars();
void prapareToMove();
void regenerate();
int addItemToInventory(Item* item);
void removeItemFromInventory(int n);
int update(std::vector<Unit*> unitList,std::vector<Item*> itemList);
virtual void makeMove(std::vector<Unit*> unitList,std::vector<Item*> itemList)=0;
};
#endif
| true |
66f2c45927390411ca392bbe6a303f055f931aac | C++ | chiseungii/HONGIK | /2_1/객체지향프로그래밍/실습/14주차/lab9/1.cpp | UTF-8 | 471 | 3.578125 | 4 | [
"MIT"
] | permissive | /*
14주차 lab9
#1
*/
#include <iostream>
#include "Complex.h"
using namespace std;
Complex &operator +(Complex &c1, Complex &c2) {
double real = c1.getReal() + c2.getReal();
double img = c1.getImg() + c2.getImg();
Complex tmp(real, img);
return tmp;
}
template <class T>
T add(T a, T b) { return a + b; }
int main() {
int a = 5, b = 2;
cout << add(a, b) << endl;
cout << add(2.5, 3.7) << endl;
Complex c1(1, 3), c2(3, 4);
cout << add(c1, c2) << endl;
}
| true |
08217c8d2e32f99665686119f89204105b8a48bc | C++ | whodoesntloveramen/Radnaev_Labs | /life.h | UTF-8 | 811 | 2.71875 | 3 | [] | no_license | #ifndef LIFE_H
#define LIFE_H
#include <cstdint>
#include <fstream>
#include <SFML/Graphics.hpp>
class life {
int32_t m;
int32_t n;
std::vector<std::vector<bool>> board;
public:
life();
life(int32_t rows, int32_t columns);
void set(int32_t row, int32_t column, bool value);
void DoSteps(int32_t number_of_iterations);
bool isAlive(int32_t row, int32_t column);
void DoStep();
int32_t numb_of_alive_neighboors(int32_t row, int32_t column);
/*friend std::ofstream& operator
<< (std::ofstream& o, life& A);*/
friend std::ifstream& operator
>> (std::ifstream& in, life& A);
friend void drow(sf::RenderWindow& window,
life& A,
int32_t win_width,
int32_t win_height);
};
#endif // LIFE_H | true |
f298580a340247082e89c6095ca0afb7c83a7369 | C++ | maksmaisak/Engine | /src/engine/utils/Bounds.cpp | UTF-8 | 3,021 | 3.203125 | 3 | [
"MIT"
] | permissive | //
// Created by Maksym Maisak on 2019-04-04.
//
#include "Bounds.h"
using namespace utils;
Bounds::Bounds() : min(0), max(0) {}
Bounds::Bounds(const glm::vec3& min, const glm::vec3& max) : min(min), max(max) {}
Bounds::Bounds(const Bounds2D& other) :
min(other.min.x, 0.f, other.min.y),
max(other.max.x, 0.f, other.max.y)
{}
bool Bounds::contains(const glm::vec3& position) const {
for (int i = 0; i < 3; ++i) {
if (position[i] > max[i] || position[i] < min[i]) {
return false;
}
}
return true;
}
bool Bounds::intersects(const Bounds& other) const {
for (int i = 0; i < 3; ++i)
if (other.min[i] > max[i] || other.max[i] < min[i])
return false;
return true;
}
glm::vec3 Bounds::clamp(const glm::vec3& other) const {
return glm::clamp(other, min, max);
}
Bounds Bounds::clamp(const Bounds& other) const {
const glm::vec3 otherHalfSize = (other.max - other.min) * 0.5f;
const glm::vec3 shrunkMin = min + otherHalfSize;
const glm::vec3 shrunkMax = max - otherHalfSize;
const glm::vec3 center = glm::clamp(other.max - otherHalfSize, shrunkMin, shrunkMax);
return {center - otherHalfSize, center + otherHalfSize};
}
void Bounds::add(const glm::vec3& point) {
min = glm::min(min, point);
max = glm::max(max, point);
}
void Bounds::expandByMovement(const glm::vec3& movement) {
for (int i = 0; i < 3; ++i) {
if (movement[i] > 0.f)
max[i] += movement[i];
else
min[i] += movement[i];
}
}
Bounds2D::Bounds2D() : min(0), max(0) {}
Bounds2D::Bounds2D(const glm::vec2& min, const glm::vec2& max) : min(min), max(max) {}
Bounds2D::Bounds2D(const Bounds& other) : min(other.min.x, other.min.z), max(other.max.x, other.max.z) {}
bool Bounds2D::contains(const glm::vec2& position) const {
for (int i = 0; i < 2; ++i) {
if (position[i] > max[i] || position[i] < min[i]) {
return false;
}
}
return true;
}
bool Bounds2D::intersects(const Bounds2D& other) const {
for (int i = 0; i < 2; ++i)
if (other.min[i] > max[i] || other.max[i] < min[i])
return false;
return true;
}
glm::vec2 Bounds2D::clamp(const glm::vec2& other) const {
return glm::clamp(other, min, max);
}
Bounds2D Bounds2D::clamp(const Bounds2D& other) const {
const glm::vec2 otherHalfSize = (other.max - other.min) * 0.5f;
const glm::vec2 shrunkMin = min + otherHalfSize;
const glm::vec2 shrunkMax = max - otherHalfSize;
const glm::vec2 center = glm::clamp(other.max - otherHalfSize, shrunkMin, shrunkMax);
return {center - otherHalfSize, center + otherHalfSize};
}
void Bounds2D::add(const glm::vec2& point) {
min = glm::min(min, point);
max = glm::max(max, point);
}
void Bounds2D::expandByMovement(const glm::vec2& movement) {
for (int i = 0; i < 2; ++i) {
if (movement[i] > 0.f)
max[i] += movement[i];
else
min[i] += movement[i];
}
}
| true |
24a05f0472305340b37314d489f422080cfdd893 | C++ | bryancjd1/trabajo | /Practica 2/10.cpp | UTF-8 | 380 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int arreglo[400000],a;
srand (time(NULL));
cout<<"Ingrese numero"<<endl;
cin>>a;
for(int i=0;i<400000;i++)
{
arreglo[i]=rand()%100;
}
for(int i=0;i<400000;i++)
{
if(arreglo[i]==a)
{
cout<<i<<" ";
}
}
}
| true |
ce14a7d48418ee7c4ec4545d801bf05d46fc4ccb | C++ | angelinelee22/CIS-054 | /Test/horoscope.cpp | UTF-8 | 3,105 | 3.15625 | 3 | [] | no_license | // File: horoscope.h
// Purpose: Implementation file for ZodiacSign, Horoscope, and Person classes.
// Author & copyright: Monza Lui
// Date: Dec 2, 2019
#include <iostream>
#include <string>
#include "horoscope.h"
using namespace std;
// ================= PERSON CLASS =================
Person::Person(string the_name, int bmonth, int bday, const Horoscope& the_orcale) {
name = the_name;
birthday = bday;
birthmonth = bmonth;
sign = the_orcale.get_sign_n_cusp(bmonth, bday, cusp);
}
bool compatible(const Person& p1, const Person& p2) {
return compatible(p1.sign, p2.sign);
}
void Person::print_person() {
cout << name << " is a " << sign.get_name() << ". ";
if (!cusp.get_name().empty()) {
cout << "He/she is also a cusp of " << cusp.get_name() << ". ";
}
cout << endl;
}
void print_compatible(const Person& p1, const Person& p2) {
cout << p1.name << " is ";
if (!compatible(p1,p2)) { cout << "not ";}
cout << "compatible with ";
cout << p2.name << ".\n";
}
// ================= ZODIACSIGN CLASS =================
ZodiacSign::ZodiacSign(const string& sign_name, string sign_element) {
name = sign_name;
element = sign_element;
//cout << "creating " << name << ", " << element << endl;
}
ZodiacSign::ZodiacSign() {
// do nothing
}
bool compatible(const ZodiacSign& s1, const ZodiacSign& s2) {
//cout << s1.element << " and " << s2.element << endl;
return (s1.element == s2.element);
}
string ZodiacSign::get_name() const {
return name;
}
string ZodiacSign::get_element() const {
return element;
}
// ================= HOROSCOPE CLASS =================
const string Horoscope::SignName[13] = {"CAPRICORN", "AQUARIUS", "PISCES", "ARIES", "TAURAUS", "GEMINI", "CANCER", "LEO", "VIRGO", "LIBRA", "SCORPIO", "SAGITTARIUS", "CAPRICORN" };
const int Horoscope::FirstDay[14] = {0, 20, 50, 81, 111, 142, 174, 205, 236, 267, 297, 327, 357, 366};
const string Horoscope::ElementName[4] = { "Earth", "Air", "Water", "FIre" };
Horoscope::Horoscope() {
for (int i=0; i < 13; i++) {
signs[i] = ZodiacSign(SignName[i], ElementName[i%4]);
}
}
int Horoscope::day_of_year(int month, int day) const{
int month_length[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int day_of_year = 0;
for (int i = 0; i < month - 1; i++) {
day_of_year += month_length[i];
}
day_of_year += day;
//cout << "day of year " << day_of_year << endl;
return day_of_year;
}
ZodiacSign Horoscope::get_sign_n_cusp(int month, int day, ZodiacSign& cusp_sign) const {
int day_of_year_born = day_of_year(month, day);
int i;
int cusp_index = -1;
for (i=0; i < 13; i++) {
//cout << "index is " << i << endl;
if ((FirstDay[i] <= day_of_year_born) && (day_of_year_born < FirstDay[i+1])) {
if (day_of_year_born - FirstDay[i] < 2) {
//cout << "in cusp\n";
cusp_index = (i == 0) ? 11 : i-1;
cusp_sign = signs[cusp_index];
} else if (FirstDay[i+1] - day_of_year_born <= 2) {
cusp_index = (i == 12) ? 0 : i+1;
cusp_sign = signs[cusp_index];
}
break;
}
}
//cout << " sign index is " << i << endl;
//cout << " cusp index is " << cusp_index << endl;
return signs[i];
} | true |
727a39815ef84f850feef2a0d3b38bd0552a2193 | C++ | tunelipt/robosimples | /roboesp32/oem750.h | UTF-8 | 632 | 2.703125 | 3 | [
"MIT"
] | permissive |
#ifndef _OEM750_H_
#define _OEM750_H_
#define MAX_VEL 50000
#define MAX_ACCEL 50000
class MoveAxis{
public:
MoveAxis(int pinstep, int pindir, int vel, int acc);
int move(int tostep);
int rmove(int nstep);
int set_position(int pos=0);
int get_position();
int set_velocity(int vel);
int get_velocity();
int set_acceleration(int acc);
int get_acceleration();
private:
int _position; ///< Actual position
int _pstep; ///< Step pin
int _pdir; ///< Direction pin
int _vel; ///< Velocity steps/s
int _acc; ///< Acceleration steps/s^2
};
#endif //_OEM750_H_
| true |
b47552bfa1b04476ac77d1bfdad328a949efb31e | C++ | shunlqing/DoCode | /algo/Algorithms4/2-Sorting/2.1-ElementarySorts/Test.cc | UTF-8 | 459 | 2.9375 | 3 | [] | no_license | #include "BaseSort.h"
#include "Selection.h"
#include "Insertion.h"
#include "Merge.h"
#include "Shell.h"
#include <string>
int main()
{
Selection<std::string> s;
std::string a[10] = {
"x",
"a",
"s",
"j",
"z",
"h",
"l",
"o",
"m",
"g"};
s.test(a, 10);
Insertion<int> x;
int b[5] = {1, 4, 5, 3, 2};
x.test(b, 5);
Shell<int> she;
she.test(b, 5);
} | true |
05771bd17ac97307b3d3a1fbdfe131f49d15281e | C++ | chipstewart/Spanner2 | /src/FastaFile.cpp | UTF-8 | 6,049 | 2.671875 | 3 | [] | no_license | /*
* FastaFile.cpp
*
* Created by Chip Stewart on 11/5/07.
* Copyright 2007 Boston College. All rights reserved.
*
*/
#include "FastaFile.h"
struct ToLower
{
char operator() (char c) const { return std::tolower(c); }
};
struct ToUpper
{
char operator() (char c) const { return std::toupper(c); }
};
// constructor
FastaObj::FastaObj()
{
numberSeq=0;
FastaFile="";
seq.clear();
seqNames.clear();
}
//---------------------------------------------------------------------------------
// FastaObj is the container class for a Fasta file sequence
//---------------------------------------------------------------------------------
// constructor
FastaObj::FastaObj(const string & fn, const string & sn)
{
this->FastaFile=fn;
this->numberSeq=0; // number of sequences
if (fn.length()==0) {
return;
}
//-------------------------------------------------------------------------------
// if first argument is "ace", then forgo loading ace file here
//-------------------------------------------------------------------------------
if (fn=="ace") {
return;
}
// boost regex matches
//boost::smatch match,match2;
string match, match2;
// Patterns to match
//string patternFastaHeader("^>(\\s*\\S+\\s*.*)$");
//string patternFastaName("^\\s*(\\S+)");
//boost::regex patternFastaHeader("^>(\\s*\\S+\\s*.*)$");
//boost::regex patternFastaName("^\\s*(\\S+)");
// unregistered flag to indicate if dna still has to be registered with sequence
bool registered = true;
// select seqName flag to indicate if this sequence is to be registered with sequence
bool selected = false;
// sequence counter
int seqCount = 0;
// sequence name
string seqName;
// sequence dna
string seqDna;
// sequence header
string seqHeader;
// input line
string line;
//----------------------------------------------------------------------------
// input FASTA DNA file
//----------------------------------------------------------------------------
// open
ifstream dnaIn(this->FastaFile.c_str(), ios::in);
if (!dnaIn) {
cerr << "Unable to open file: " << this->FastaFile << endl;
exit(1);
}
while (getline(dnaIn, line)) {
// header line (long format): register previous sequence and start new
// if (boost::regex_search(line, match, patternFastaHeader)) {
//if (RE2::FullMatch(line.c_str(),patternFastaName.c_str(),&match) ) {
if (line.size()<2) continue;
if ( line[0]=='>') {
//RE2::FullMatch(line.c_str(),patternFastaHeader.c_str(),&match) ) {
match=line.substr(1);
// if previous sequence info not yet registred, register it
if ( (!registered)&(selected) ) {
// add sequence
string sn1=seqName;
transform(sn1.begin(), sn1.end(), sn1.begin(), ToUpper());
this->seq[sn1]=seqDna;
this->seqNames.push_back(sn1);
}
// increment read count
seqCount++;
// reset seqDna
seqDna = "";
// retreive info for new sequence
seqHeader = match;
// parse out sequence name
seqName = seqHeader;
vector<string> vs;
int ns= split(vs , seqHeader, " ");
if (ns>1)
seqName=vs[0];
//if (RE2::FullMatch(seqHeader.c_str(),patternFastaName.c_str(),&match2) ) {
// seqName = match2;
//}
// select sequence by name
string sn1=seqName;
string sn2=sn;
transform(sn1.begin(), sn1.end(), sn1.begin(), ToUpper());
transform(sn2.begin(), sn2.end(), sn2.begin(), ToUpper());
selected = true;
if (sn.length()>0) {
selected = (sn1==sn2);
}
// set registered read info flag
registered = false;
}
else if (selected) {
seqDna += line;
}
}
// register last DNA entry if necessary
if ( (!registered)&(selected) ) {
// add sequence
string sn1=seqName;
std::transform(sn1.begin(), sn1.end(), sn1.begin(), ToUpper());
this->seq[sn1]=seqDna;
this->seqNames.push_back(sn1);
//this->seq[seqName]=seqDna;
//this->seqNames.push_back(seqName);
}
this->numberSeq = int(this->seq.size()); // number of sequences
dnaIn.close();
}
void FastaObj::addSeq(const string & contigName1, const string & seqDna)
{
if (seqDna.length()==0) {
return;
}
this->seq[contigName1]=seqDna;
this->seqNames.push_back(contigName1);
this->numberSeq = int(this->seq.size()); // number of sequences
}
//========================================================================
// fetch a sequence of name s
//========================================================================
string FastaObj::getSeq(const string & s)
{
return this->seq[s];
}
//========================================================================
// fetch a sequence of name s at p of length n
//========================================================================
string FastaObj::getSubSeq(const string & s, size_t p, size_t n)
{
return this->seq[s].substr(p,n);
}
//========================================================================
// fetch Number of sequences
//========================================================================
int FastaObj::getNumberSeq()
{
return this->numberSeq;
}
size_t FastaObj::getSeqLength(const string & s)
{
return this->seq[s].size();
}
| true |
b523477d8338a4588a9b2d7b5548f5c3d377c901 | C++ | robotpy/robotpy-build | /tests/cpp/rpytest/ft/include/type_caster_nested.h | UTF-8 | 394 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive |
#pragma once
#include <functional>
#include <vector>
struct NestedTypecaster
{
// only works if pybind11/stl.h and functional.h is included -- our type
// caster detection mechanism should include it automatically
void callWithList(std::function<void(std::vector<int>)> fn)
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
fn(v);
}
}; | true |
5a6e2a73f164f5a9101d3712e4f7fc4d7f1dada4 | C++ | biug/xNN | /xNN/input_neuron.hpp | WINDOWS-1252 | 2,301 | 3.1875 | 3 | [] | no_license | /*
* input_neuron.hpp
*
* Created on: 201663
* Author: Administrator
*/
#ifndef INPUT_NEURON_HPP_
#define INPUT_NEURON_HPP_
#include <vector>
using std::vector;
template<typename DType>
class InputNeuron {
// vector length
int m_nEmbeddingLen;
int m_nVecLen;
// vector z
DType * m_pInput;
// dLoss / dz
DType * m_pInputDiff;
bool m_bDropout;
public:
InputNeuron(int embeddingLen, int vecLen);
~InputNeuron();
void loadEmbedding(const DType * embeddingMatrix, const vector<int> & ids);
void updateEmbedding(DType * embeddingMatrixDiff, const vector<int> & ids);
inline int getVecLen() const {
return m_nVecLen;
}
inline DType * getMutableInput() {
return m_pInput;
}
inline DType * getMutableInputDiff() {
return m_pInputDiff;
}
inline const DType * const getInput() const {
return m_pInput;
}
inline const DType * const getInputDiff() const {
return m_pInputDiff;
}
inline const bool getDropout() const {
return m_bDropout;
}
inline void setDropout(bool bDrop) {
m_bDropout = bDrop;
}
};
// definitions
/**
* a neuron contains up-layers' size and a vector size
* we call up-layers' size ni, and vector size m
* so weight wi is matrix which size is m * ni
*/
template<typename DType>
InputNeuron<DType>::InputNeuron(int embeddingLen, int vecLen) : m_nEmbeddingLen(embeddingLen), m_nVecLen(vecLen), m_bDropout(false) {
m_pInput = new DType[m_nVecLen];
m_pInputDiff = new DType[m_nVecLen];
}
template<typename DType>
InputNeuron<DType>::~InputNeuron() {
delete[] m_pInput;
delete[] m_pInputDiff;
}
template<typename DType>
void InputNeuron<DType>::loadEmbedding(const DType * embeddingMatrix, const vector<int> & ids) {
// skip dropout
if (m_bDropout) return;
int offset = 0;
for (const auto & id : ids) {
vector_copy_vector(&m_pInput[offset], &embeddingMatrix[id * m_nEmbeddingLen], m_nEmbeddingLen);
offset += m_nEmbeddingLen;
}
}
template<typename DType>
void InputNeuron<DType>::updateEmbedding(DType * embeddingMatrixDiff, const vector<int> & ids) {
// skip dropout
if (m_bDropout) return;
int offset = 0;
for (const auto & id : ids) {
vector_add_vector(&embeddingMatrixDiff[id * m_nEmbeddingLen], &m_pInputDiff[offset], m_nEmbeddingLen);
offset += m_nEmbeddingLen;
}
}
#endif /* INPUT_NEURON_HPP_ */
| true |
cd017812389cb391c5f8ab8adb73f19d1571be25 | C++ | attikis/HiggsAnalysis | /NtupleAnalysis/src/Tools/interface/DirectionalCut.h | UTF-8 | 3,523 | 3.34375 | 3 | [] | no_license | // -*- c++ -*-
#ifndef Tools_DirectionalCut_h
#define Tools_DirectionalCut_h
#include <string>
#include "Framework/interface/ParameterSet.h"
#include "Framework/interface/Exception.h"
/// Wrapper for more flexible cutting parameters (cut direction, value pair instead of cut value for fixed direction)
template <typename T>
class DirectionalCut {
enum DirectionalCutType {
kGT, // greater than
kGEQ, // greater than or equal to
kLT, // less than
kLEQ, // less than or equal to
kEQ, // equal to
kNEQ // not equal to
};
public:
DirectionalCut(const ParameterSet& config, const std::string& name)
: fValue(config.getParameter<T>(name+std::string("Value"))) {
// Check that direction option is valid
std::string direction = config.getParameter<std::string>(name+std::string("Direction"));
if (direction == "EQ" || direction == "==")
fCutDirection = kEQ;
else if (direction == "NEQ" || direction == "!=")
fCutDirection = kNEQ;
else if (direction == "GT" || direction == ">")
fCutDirection = kGT;
else if (direction == "GEQ" || direction == ">=")
fCutDirection = kGEQ;
else if (direction == "LT" || direction == "<")
fCutDirection = kLT;
else if (direction == "LEQ" || direction == "<=")
fCutDirection = kLEQ;
else {
throw hplus::Exception("config") << "DirectionalCut: invalid cut direction (" << direction << ")! Options are: ==, !=, >, >=, <, <=";
}
}
DirectionalCut(const std::string direction, const double value)
: fValue(value) {
// Check that direction option is valid
if (direction == "EQ" || direction == "==")
fCutDirection = kEQ;
else if (direction == "NEQ" || direction == "!=")
fCutDirection = kNEQ;
else if (direction == "GT" || direction == ">")
fCutDirection = kGT;
else if (direction == "GEQ" || direction == ">=")
fCutDirection = kGEQ;
else if (direction == "LT" || direction == "<")
fCutDirection = kLT;
else if (direction == "LEQ" || direction == "<=")
fCutDirection = kLEQ;
else {
throw hplus::Exception("config") << "DirectionalCut: invalid cut direction (" << direction << ")! Options are: ==, !=, >, >=, <, <=";
}
}
~DirectionalCut() { }
/// Check if cut has been passed
bool passedCut(const T testValue) const {
if (fCutDirection == kEQ)
return std::fabs(testValue-fValue) < 0.0001;
if (fCutDirection == kNEQ)
return std::fabs(testValue-fValue) > 0.0001;
if (fCutDirection == kGT)
return (testValue > fValue);
if (fCutDirection == kGEQ)
return (testValue >= fValue);
if (fCutDirection == kLT)
return (testValue < fValue);
if (fCutDirection == kLEQ)
return (testValue <= fValue);
return false; // never reached
}
T getCutValue(void) const{ return fValue;}
DirectionalCutType getCutDirection(void) const{ return fCutDirection;}
std::string getCutDirectionString(void) const{
if (fCutDirection == kEQ) return "==";
else if (fCutDirection == kNEQ) return "!=";
else if (fCutDirection == kGT) return ">";
else if (fCutDirection == kGEQ) return ">=";
else if (fCutDirection == kLT) return "<";
else if (fCutDirection == kLEQ) return "<=";
else
{
throw hplus::Exception("config") << "DirectionalCut: invalid cut direction (" << fCutDirection << ")! Options are: ==, !=, >, >=, <, <=";
return "UNKNOWN";
}
}
private:
T fValue;
DirectionalCutType fCutDirection;
};
#endif
| true |
29a9b90e0aeb0337656a2f6d39910a2ee8b7a169 | C++ | ss5ssmi/OJ | /codeforce/CF_1481A.cpp | UTF-8 | 457 | 2.671875 | 3 | [] | no_license | #include<stdio.h>
int main(){
int t;
scanf("%d", &t);
while(t--){
int x, y, l = 0, r = 0, u = 0, d = 0, flag1 = 0, flag2 = 0;
char s[100001];
scanf("%d%d", &x, &y);
scanf("%s", &s);
for(int i=0;s[i]!='\0';i++){
if(s[i]=='L') l--;
else if(s[i]=='R') r++;
else if(s[i]=='U') u++;
else d--;
if(l<=x && r>=x) flag1 = 1;
if(d<=y && u>=y) flag2 = 1;
}
if(flag1 && flag2) printf("YES\n");
else printf("NO\n");
}
return 0;
}
| true |
77b98dab453f1016d1ab1a69f4bb641f3dcce62e | C++ | 543877815/algorithm | /leetcode/c++/231. Power of Two.cpp | UTF-8 | 687 | 3.390625 | 3 | [] | no_license |
// 时间复杂度:O(logn)
// 空间复杂度:O(1)
bool isPowerOfTwo(int n) {
if (n % 2 == 1 && n != 1) return false;
long long int ans = 1;
while (ans != n) {
if (ans > n) return false;
ans *= 2;
}
return true;
}
// 二进制表示
// 时间复杂度:O(1)
// 空间复杂度:O(1)
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
};
// 判断是否为最大 22 的幂的约数
// 时间复杂度:O(1)
// 空间复杂度:O(1)
class Solution {
private:
static constexpr int BIG = 1 << 30;
public:
bool isPowerOfTwo(int n) {
return n > 0 && BIG % n == 0;
}
};
| true |
bab71900c8d1ab03af9d96eedaf0cb9620dbb2ca | C++ | czestmyr/dpp | /druhy/src/values/StringValue.h | UTF-8 | 576 | 2.78125 | 3 | [] | no_license | #ifndef _ARGLIB_STRING_VALUE_H_
#define _ARGLIB_STRING_VALUE_H_
#include <string>
#include "../Value.h"
#include "../ValueHandle.h"
namespace Arglib {
/// Class StringValue encapsulates type string.
class StringValue : public Value {
public:
StringValue(std::string newValue):value(newValue){}
~StringValue() {}
void set(std::string newValue) { value = newValue; }
std::string get() { return value; }
private:
std::string value; ///< field to hold the value
};
template <>
std::string ValueHandle::getValue<std::string>();
} // End namespace Arglib
#endif
| true |
760a336ec2036ffbfdc03739fa442077977f03a0 | C++ | Girl-Code-It/Beginner-CPP-Submissions | /Urvashi/milestone-22 (stack)/leetcode stack/easy/remove all adjacent duplicates.cpp | UTF-8 | 480 | 3.140625 | 3 | [] | no_license | class Solution
{
public:
string removeDuplicates(string S)
{
stack<char> s1;
for (int i = 0; i < S.size(); i++)
{
if (!s1.empty() && s1.top() == S[i])
s1.pop();
else
s1.push(S[i]);
}
string temp = "";
while (!s1.empty())
{
temp += s1.top();
s1.pop();
}
reverse(temp.begin(), temp.end());
return temp;
}
};
| true |
5b4e06a963629b75e711c58f29e025676376d673 | C++ | Leo3600Liu/HW_Seaweed_Leo | /src/main.cpp | UTF-8 | 1,631 | 3.015625 | 3 | [] | no_license | //Created by Jiteng Liu (Leo)
#line 1 "Quiz_2_1_1-2"
#include "ofMain.h"
class ofApp: public ofBaseApp
{
public:
#line 1 "Quiz_2_1_1-2"
ofPolyline polyline; //set up a polyline
ofPolyline movePolyline; //set up a polyline
void setup() { //to define the basic environment conditions before the program starts
ofSetWindowShape(500, 500); //Set the size of the window "aquatic plant"
for (int i=250; i>=-200; i-=8) polyline.addVertex(ofVec2f(0,i)); //set the position of the
movePolyline = polyline; //make the polyline equal to movepolyline
}
void draw() { //to excute the code
ofBackground(127); // Set the background color
ofSetColor(77,204,0); //Set the the color of "aquatic plant"
for (int i=0; i<polyline.size(); i++) { // To create the horizontal line on each point of tangency
ofVec3f normal = polyline.getNormalAtIndexInterpolated(i);
ofPushMatrix(); // Create the Vertical Line
ofTranslate(250,250); //the parameter of translate
movePolyline.draw();
ofPopMatrix(); //finish the push matrix
ofPushMatrix(); // Create a lot of horizontal line
ofTranslate(250, 250); //the parameter of translate
ofLine(movePolyline[i]-normal*(polyline.size() -i), movePolyline[i]+normal*(polyline.size() -i));
ofPopMatrix(); //finish the push matrix
}
}
};
int main() //hand out "main"
{
ofSetupOpenGL(320, 240, OF_WINDOW); //set up the GL
ofRunApp(new ofApp()); //run the project
}
| true |
01b90a7f6351c637fd06a47400d40f3ad2429697 | C++ | ArranGravestock/3d-printing-spike-generator | /MyFace.cpp | UTF-8 | 471 | 2.78125 | 3 | [] | no_license | #include "MyFace.h"
MyFace::MyFace(OSG::Pnt3f centre, std::vector<OSG::Pnt3f> vertices) {
faceCentre = centre;
faceVertices = vertices;
};
MyFace::~MyFace() {
};
OSG::Pnt3f MyFace::getFaceCentre() {
return faceCentre;
};
void MyFace::setFaceCentre(OSG::Pnt3f centre) {
faceCentre = centre;
};
std::vector<OSG::Pnt3f> MyFace::getFaceVertices() {
return faceVertices;
};
void MyFace::setFaceVertex(int index, OSG::Pnt3f point) {
faceVertices[index] = point;
}; | true |
258fb46d545cb09467f1f296d72533081ab4fdd2 | C++ | yoki0805/graphics | /Robots/Robots/GeneticAlgorithm.h | UTF-8 | 1,971 | 3.3125 | 3 | [] | no_license | #pragma once
#include <vector>
#include <algorithm>
#include "Utils.h"
using namespace std;
// create a structure to hold each genome
struct Genome
{
vector<double> weights;
double fitness;
Genome() : fitness(0) {}
Genome(const vector<double>& w, double f): weights(w), fitness(f) {}
// overload '<' used for sorting
friend bool operator<(const Genome& a, const Genome& b) { return (a.fitness < b.fitness); }
};
// genetic algorithm
class GeneticAlgo
{
private:
// holds the entire population of chromosomes
vector<Genome> genomes;
// population of genomes
int population;
// amount of weights per chromo
int chromoLength;
// total fitness of population
double totalFitness;
// best fitness
double bestFitness;
// average fitness
double averageFitness;
// keeps track of the best genome
int bestGenomeIndex;
// store the best genome in history
Genome bestGenomeEver;
// mutation rate
double mutationRate;
// crossover rate
double crossoverRate;
// generation counter
int generation;
void crossover(const vector<double>& mama,
const vector<double>& papa,
vector<double>& baby1,
vector<double>& baby2);
void mutate(vector<double>& chromo);
Genome getChromoRoulette();
void elitism(int nBest, int numCopiese, vector<Genome>& pop);
public:
GeneticAlgo() : totalFitness(0), bestFitness(0),
averageFitness(0), bestGenomeIndex(0), generation(0) {}
// create a randomly pool
void create(int popSize, double mutRate, double crossRate, int numWeights);
// this runs the GA for one generation
vector<Genome> epoch(const vector<Genome>& oldGenomes);
// inline functions
inline vector<Genome> getChromos() const { return this->genomes; }
inline double getAverageFitness() const { return averageFitness; }
inline double getBestFitness() const { return bestFitness; }
inline double getBestFitnessEver() const { return bestGenomeEver.fitness; }
inline int getGeneration() const { return generation; }
}; | true |
41beccd6d985eceb40d1b70be1d63b2fbdb79229 | C++ | auroraleso/Cpp-course | /examples_theory/teacher/8_designpatterns/iterator/LinkedList.hpp | UTF-8 | 5,447 | 3.734375 | 4 | [] | no_license | //#include "LinkedList.h"
// *************** LinkedList implementation ***************
template <class T>
LinkedList<T>::LinkedList() {
fNode = lNode = nullptr;
}
template <class T>
LinkedList<T>::~LinkedList() {
Node* node = fNode;
Node* next;
while ( node != nullptr ) {
next = node->nNode;
delete node;
node = next;
}
}
// first element of the list
template <class T>
typename LinkedList<T>::Iterator
LinkedList<T>::begin() {
LinkedList<T>::Iterator iter;
// if there's a first element set iterator to point there
// otherwise set iterator as "beyond the end"
if ( fNode != nullptr ) {
iter.validity = Iterator::valid;
iter.node = fNode;
}
else {
iter.validity = Iterator::fw_end;
iter.node = lNode;
}
return iter;
}
// beyond the end of the list
template <class T>
typename LinkedList<T>::Iterator
LinkedList<T>::end() {
LinkedList<T>::Iterator iter;
iter.validity = Iterator::fw_end;
iter.node = lNode;
return iter;
}
// last element of the list
template <class T>
typename LinkedList<T>::Iterator
LinkedList<T>::rbegin() {
LinkedList<T>::Iterator iter;
// if there's a last element set iterator to point there
// otherwise set iterator as "before the begin"
if ( lNode != nullptr ) {
iter.validity = Iterator::valid;
iter.node = lNode;
}
else {
iter.validity = Iterator::bw_end;
iter.node = fNode;
}
return iter;
}
// before the begin of the list
template <class T>
typename LinkedList<T>::Iterator
LinkedList<T>::rend() {
LinkedList<T>::Iterator iter;
iter.validity = Iterator::bw_end;
iter.node = fNode;
return iter;
}
// insert an element before a position
template <class T>
void LinkedList<T>::insert( const T& x, const LinkedList<T>::Iterator& iter ) {
// create a new node
Node* node = new Node( x );
Node* prev = nullptr;
Node* next = nullptr;
// find previous and next nodes
switch( iter.validity ) {
case Iterator::valid:
next = iter.node;
prev = next->pNode;
break;
case Iterator::fw_end:
prev = lNode;
break;
case Iterator::bw_end:
next = fNode;
break;
};
// link previous and next nodes to the new one
if ( prev != nullptr ) {
prev->nNode = node;
node->pNode = prev;
}
else {
fNode = node;
}
if ( next != nullptr ) {
node->nNode = next;
next->pNode = node;
}
else {
lNode = node;
}
return;
}
// *************** LinkedList::Iterator implementation ***************
template <class T>
LinkedList<T>::Iterator::Iterator() {
}
template <class T>
LinkedList<T>::Iterator::~Iterator() {
}
// dereference
template <class T>
T& LinkedList<T>::Iterator::operator*() {
if ( validity == valid ) return node->content;
static T* dum = new T;
return *dum;
}
// prefix increment
template <class T>
typename LinkedList<T>::Iterator&
LinkedList<T>::Iterator::operator++() {
switch( validity ) {
case valid:
// valid iterator:
// if there's a next element move to it,
// otherwise flag the iterator as "beyond the end"
if ( node->nNode != nullptr ) node = node->nNode;
else validity = fw_end;
break;
case fw_end:
// "beyond the end" iterator: no action
break;
case bw_end:
// "before the begin" iterator:
// if there's an element stay there and flag the iterator as valid
// otherwise flag the iterator as "beyond the end"
if ( node != nullptr ) validity = valid;
else validity = fw_end;
break;
};
return *this;
}
// postfix increment
template <class T>
typename LinkedList<T>::Iterator
LinkedList<T>::Iterator::operator++( int ) {
// save a copy
Iterator iter = *this;
// step forward
operator++();
// return the copy
return iter;
}
// prefix decrement
template <class T>
typename LinkedList<T>::Iterator&
LinkedList<T>::Iterator::operator--() {
switch( validity ) {
case valid:
// valid iterator:
// if there's a previous element move to it,
// otherwise flag the iterator as "before the begin"
if ( node->pNode != nullptr ) node = node->pNode;
else validity = bw_end;
break;
case fw_end:
// "beyond the end" iterator:
// if there's an element stay there and flag the iterator as valid
// otherwise flag the iterator as "before the begin"
if ( node != nullptr ) validity = valid;
else validity = bw_end;
break;
case bw_end:
// "before the begin" iterator: no action
break;
};
return *this;
}
// postfix decrement
template <class T>
typename LinkedList<T>::Iterator
LinkedList<T>::Iterator::operator--( int ) {
// save a copy
Iterator iter = *this;
// step backward
operator--();
// return the copy
return iter;
}
template <class T>
bool LinkedList<T>::Iterator::operator==( const Iterator& iter ) {
return ( node == iter.node ) && ( validity == iter.validity );
}
template <class T>
bool LinkedList<T>::Iterator::operator!=( const Iterator& iter ) {
return ( node != iter.node ) || ( validity != iter.validity );
}
// *************** LinkedList::Node implementation ***************
template <class T>
LinkedList<T>::Node::Node( const T& x ):
content( x ),
pNode( nullptr ),
nNode( nullptr ) {
}
template <class T>
LinkedList<T>::Node::~Node() {
}
| true |
1b6225d48660ad4aa249e37f7773f1dea1307902 | C++ | Nozomi-Takemura/Cpp_primer_5th_exercises | /6/ex6_23_ref.cpp | UTF-8 | 254 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void print(const int (&ia)[2]){
for(auto ele : ia)
cout << ele << " ";
cout << endl;
}
int main(){
int i = 0, j[2] = {0,1};
cout << "for i, ";
// print(&i);
cout << "for j[2], ";
print(j);
}
| true |
1e5f6f0c2d90c3ad4026e59248f324874b3b8086 | C++ | RinokuS/yandex-cpp-belts | /Yellow/Week4/Task10/main.cpp | UTF-8 | 1,493 | 3.296875 | 3 | [] | no_license | #include <iterator>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
template <typename RandomIt>
pair<RandomIt, RandomIt> FindStartsWith(
RandomIt range_begin, RandomIt range_end,
char prefix){
auto lb = lower_bound(range_begin, range_end, string(1, prefix));
auto ub = upper_bound(range_begin, range_end, string(1, prefix));
while (ub != range_end && (*ub)[0] == prefix){
ub++;
}
if (lb == ub){
if (lb == range_begin){
return make_pair(range_begin, range_begin);
} else{
return make_pair(lb, lb);
}
} else{
return make_pair(lb, ub);
}
}
int main() {
const vector<string> sorted_strings = {"moscow", "murmansk", "vologda"};
const auto m_result =
FindStartsWith(begin(sorted_strings), end(sorted_strings), 'm');
for (auto it = m_result.first; it != m_result.second; ++it) {
cout << *it << " ";
}
cout << endl;
const auto p_result =
FindStartsWith(begin(sorted_strings), end(sorted_strings), 'p');
cout << (p_result.first - begin(sorted_strings)) << " " <<
(p_result.second - begin(sorted_strings)) << endl;
const auto z_result =
FindStartsWith(begin(sorted_strings), end(sorted_strings), 'z');
cout << (z_result.first - begin(sorted_strings)) << " " <<
(z_result.second - begin(sorted_strings)) << endl;
return 0;
}
| true |
d060d809a227bc1d3a5d1d3b1b322a2e34ac814a | C++ | ddzmitry/CPPLearninig | /oop/Inheritance_DerivedfromExisting/src/Account.h | UTF-8 | 324 | 2.53125 | 3 | [] | no_license | /*
* Account.h
*
* Created on: Mar 10, 2020
* Author: dzmitrydubarau
*/
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
#include <iostream>
class Account {
public:
double balance;
std::string name;
void withdraw(double amount);
void deposit(double amount);
Account();
virtual ~Account();
};
#endif /* ACCOUNT_H_ */
| true |
49a2e18fef87f3a3ed9cf0748cde1b0667ef29b8 | C++ | SgtCoDFish/APG | /src/graphics/Sprite.cpp | UTF-8 | 1,270 | 2.96875 | 3 | [] | no_license | #ifndef APG_NO_GL
#include <cstdint>
#include <memory>
#include <string>
#include <sstream>
#include "APG/graphics/Sprite.hpp"
#include "APG/graphics/Texture.hpp"
#include "APG/internal/Assert.hpp"
namespace APG {
Sprite::Sprite(Texture *texture) :
Sprite(texture, 0, 0, texture->getWidth(), texture->getHeight()) {
}
Sprite::Sprite(Texture *texture, int32_t texX, int32_t texY, int32_t width, int32_t height) :
texture(texture),
texX(texX),
texY(texY),
width(width),
height(height),
logger{spdlog::get("APG")} {
if (texture == nullptr) {
logger->critical("Can't pass a null texture to create a sprite.");
return;
}
if (texX + width > texture->getWidth() || texY + height > texture->getHeight()) {
logger->error(
"Trying to create sprite with (texX, texY, w, h) = ({}, {}, {}, {}) would exceed texture size (w, h) = ({}, {})",
texX, texY, width, height, texture->getWidth(), texture->getHeight()
);
}
logger->trace("Creating sprite (x, y, w, h) = ({}, {}, {}, {})", texX, texY, width, height);
calculateUV();
}
void Sprite::calculateUV() {
u1 = texture->getInvWidth() * texX;
v1 = texture->getInvHeight() * texY;
u2 = texture->getInvWidth() * (texX + width);
v2 = texture->getInvHeight() * (texY + height);
}
}
#endif
| true |
1eef3586de807949714aeb619cb1686ee45a5be6 | C++ | shubhgkr/Codechef | /Beginner/TTENIS.cpp | UTF-8 | 681 | 3 | 3 | [] | no_license | /*
* @author Shubham Kumar Gupta (shubhgkr)
* github: http://www.github.com/shubhgkr
* Created on 3/18/20.
* Problem link: https://www.codechef.com/problems/TTENIS
*/
#include <iostream>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
std::cin >> t;
while (t--) {
std::string s;
std::cin >> s;
int opponent = 0;
int chef = 0;
std::string won = "";
for (char ch:s) {
if (ch == '0')
opponent++;
else
chef++;
if ((opponent == 11 && chef < 10) || (opponent - chef == 2))
won = "LOSE";
else if ((opponent < 10 && chef == 11) || (chef - opponent == 2))
won = "WIN";
}
std::cout << won << "\n";
}
return 0;
}
| true |
9369e1978c8c254e8ffa640e9009aaeec9ca9282 | C++ | Eaglegor/SchedulerEngine | /Engine/SceneManager/Queries/SceneQueries.h | UTF-8 | 1,267 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "OperationStopMappingQuery.h"
namespace Scheduler
{
/**
* @ingroup scene_queries
*
* @brief Interface to perform the scene queries
*
* @details Scene queries help to extract calculations of some information from the
* scene interface keeping it as small as possible. Queries can be used e.g. to find the
* iterators by the operations, to check the compatibility of orders and resources etc.
*
* Some queries implementations may use caching inside, some may not - read the docs to the
* particular query.
*
* Queries are initialized using the lazy calculations paradigm - so until the particular
* query is requested it isn't initialized (and so no cache calculations are performed and so on).
*/
class SceneQueries
{
public:
/**
* @brief Constructor
*
* @param scene Scene to perform queries for
*/
explicit SceneQueries(Scene& scene);
/**
* @brief Returns interface to find allocated stops iterators by the operations
*
* @return Interface to find allocated stops iterators by the operations
*/
OperationStopMappingQuery& operationStopMapping( ) const;
private:
Scene& scene;
mutable boost::optional<OperationStopMappingQuery> operation_stop_mapping_query;
};
} | true |
1130121d88b0c368e0e44cd09dbae15cf0f1e5b0 | C++ | sergey3f0/homework | /10M-2021-spring/959a.cpp | UTF-8 | 140 | 2.578125 | 3 | [] | no_license | #include <iostream>
int main()
{
int i;
scanf ("%d",&i);
if ((i % 2) == 0)
{
printf ("Mahmoud");
}
else
{
printf ("Ehab");
}
}
| true |
1734ae6849b33db22a92f4586d5f8156dc17fa7d | C++ | hyeseonko/Algorithm-Baekjoon | /계단오르기_baekjoon2579.cpp | UTF-8 | 998 | 3.359375 | 3 | [] | no_license | /*
TITLE: STAIRS
BAEKJOON 2579
CATEGORY: DP
DATE: 2017-06-01
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define bigger(a,b) (a>b?a:b)
int stairs[300];
int dp[300];
int main()
{
int N; scanf("%d", &N);
for (int i = 0; i < N; i++) scanf("%d", &stairs[i]);
dp[0] = stairs[0];
dp[1] = stairs[0] + stairs[1];
dp[2] = stairs[2] + bigger(stairs[0], stairs[1]);
for (int i = 3; i < N; i++)
{
dp[i] = stairs[i] + bigger(dp[i - 2], dp[i - 3] + stairs[i - 1]);
}
printf("%d\n", dp[N - 1]);
return 0;
}
/* HOW I SOLVED THIS */
/*
USING DYNAMIC PROGRAMMING
THE TRICKY PART WAS CONSIDERING 1-1-1 STEP.
To solved this, I considered not in two consecutive ones, but three consecutives.
To reach dp[x], there are two ways to go there
1) dp[x-2] + two steps = dp[x]
2) dp[x-3] + two steps + one step = dp[x]
The reason why I don't add dp[x-1] is I might calculate the case of 1-1-1 steps.
So, I need to consider from the x-3 cases.
*/
| true |
6ae1aae6d9850684b2bd6a20c299e116a5808e35 | C++ | josedoneguillen/CPP | /practica-funciones-calculo-de-nota/main.cpp | UTF-8 | 3,650 | 3.109375 | 3 | [] | no_license | /******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <iostream>
using namespace std;
char f_devuelve_literal(double pcalificacion){
char literal;
if(pcalificacion >= 90)
{
literal = 'A';
}
else if (pcalificacion >= 80){
literal = 'B';
}
else if (pcalificacion >= 70){
literal = 'C';
}
else {
literal = 'F';
}
return literal;
}
double f_devuelve_calFinal(
double CalParcial,
double PesoCalParcial,
double CalExamen,
double PesoCalExamen,
double CalActividad,
double PesoCalActividad,
double CalTareas,
double PesoCalTareas
){
double CalFinal;
CalParcial *= PesoCalParcial;
CalExamen *= PesoCalExamen;
CalActividad *= PesoCalActividad;
CalTareas *= PesoCalTareas;
CalFinal = (CalParcial + CalExamen + CalActividad + CalTareas);
return CalFinal;
}
int main()
{
//Informacion sobre el programa
std::cout<<"\t\t *** \t\t\n";
std::cout<<"\t Registro de Calificaciones \n";
std::cout<<"\t\t *** \t\t\n";
//Declaracion de variables
std::string nombre_estudiante = " ";
double CalExamen = 0.0;
double CalParcial = 0.0;
double CalActividad = 0.0;
double CalTareas = 0.0;
char lieteral = 'x';
const double PesoCalExamen = 0.30;
const double PesoCalParcial = 0.20;
const double PesoCalActividad = 0.25;
const double PesoCalTareas = 0.25;
double CalFinal = 0.0;
int control = 0;
int cantidad_estudiantes = 0;
std::cout<<"Cuantos estudiantes desea ingresar: ";
std::cin>>cantidad_estudiantes;
std::cin.ignore();
while(control < cantidad_estudiantes)
{
//Captura de datos
std::cout<<"Digite el nombre del estudiante: ";
getline(std::cin,nombre_estudiante);
std::cout<<"Digite la puntuacion del parcial: ";
std::cin>>CalParcial;
std::cout<<"Digite la puntuacion del Examen final: ";
std::cin>>CalExamen;
std::cout<<"Digite la puntuaciC3n del las actividades: ";
std::cin>>CalActividad;
std::cout<<"Digite la puntuaciC3n de las tareas: ";
std::cin>>CalTareas;
std::cin.ignore();
//Realizacion de calculos para determinar calificacion final
//LLevar a una funcion
/*CalParcial = (CalParcial * PesoCalParcial);
CalExamen = (CalExamen * PesoCalExamen);
CalActividad = (CalActividad * PesoCalActividad);
CalTareas = (CalTareas * PesoCalTareas);
CalFinal = (CalParcial + CalExamen + CalActividad + CalTareas);*/
//Llamado a la funcion para calcular calificacion final
CalFinal = f_devuelve_calFinal(
CalParcial,
PesoCalParcial,
CalExamen,
PesoCalExamen,
CalActividad,
PesoCalActividad,
CalTareas,
PesoCalTareas
);
//Determinacion del literal
lieteral = f_devuelve_literal(CalFinal);
//Muestra de resultados
std::cout<<std::endl<<"El Estdiante "<<nombre_estudiante
<<" Obtuvo una calificacion final de: "<<CalFinal
<<" lo que equivale a un literal de: "<< lieteral
<<std::endl<<std::endl;
control++;
}
return 0;
}
| true |
332c7e2c6c95c996dc0180fb6e981a1744980ca0 | C++ | google-code/algebraic-template-library | /testalt.cpp | UTF-8 | 1,138 | 2.859375 | 3 | [] | no_license | //
//testalt.cpp
//
//test program for "alt"
//
#include <iostream>
#include <vector>
#include <complex>
#include <assert.h>
#include "alt/alt.hpp"
#include "alt/io.hpp"
template<typename EqType>
void show_and_solve(const EqType& eq)
{
std::cout << "Eq:" << eq << std::endl;
typename EqType::solution_container sol = alt::get_solutions(eq);
typename EqType::solution_container::iterator it;
std::cout << "Sol:";
for(it=sol.begin();it!=sol.end();++it){
std::cout << *it << ",";
}
std::cout << "\n";
std::cout << "err:";
for(it=sol.begin();it!=sol.end();++it){
std::cout << eq(*it) << ",";
}
std::cout << "\n";
}
int main(int argc, char* argv[])
{
alt::variant x;
show_and_solve((1+x).pow<2>());
//show_and_solve(1-2+3*x/4*3+2-1);
show_and_solve(x*x + 1);
show_and_solve(x*x + 2*x - 3);
show_and_solve((1-x)*(2-x)*(3-x));
show_and_solve((1-x*x)*(x));
show_and_solve((1+x*x)*(x));
show_and_solve((1-x)*(4-x)*(1-x) + 2*11*7 + 2*3*3 - 2*(4-x)*7 - 11*3*(1-x) - (1-x)*2*3);
return 0;
}
| true |
0229029cde7bb0e30de5d159654a276623e6ee8d | C++ | wangxing0608/CtCI | /Trees_and_Graphs/PathsWithSum.cpp | UTF-8 | 1,598 | 3.59375 | 4 | [] | no_license | //
// Created by wangxing on 19-8-10.
//
// 给定一颗二叉树,其中每个节点都包含有一个整数值(正数或负数)
// 设计算法计算到给定数值的总的路径数,路径不需要从h根或叶子节点开始,但必须向下
#include <unordered_map>
#include "tree.h"
#include "treetestutils.h"
int sumsFrom(const NodePtr<int> &node, int requierdSum, int pathSum, std::unordered_map<int, int> &sums)
{
if (!node)
return 0;
pathSum += node -> getValue();
//Count of paths ending here and having required sum
int overflow = pathSum - requierdSum;
int cnt = sums.count(overflow) ? sums.at(overflow) : 0;
// Starting from root
if (pathSum == requierdSum)
++cnt;
sums[pathSum] +=1;
cnt += sumsFrom(node -> getLeft(), requierdSum, pathSum, sums);
cnt += sumsFrom(node -> getRight(), requierdSum, pathSum, sums);
// Done with this node, do not ust pathSum till this node anymore
if ((sums[pathSum] -= 1) == 0)
sums.erase(pathSum); // less memory
return cnt;
}
int countPathWithSum(const Tree<int> &tree, int sum)
{
std::unordered_map<int, int> tmp;
return sumsFrom(tree.getRoot(), sum, 0, tmp);
}
int main()
{
auto tree = TestUtils::treeFromArray({1, -2, 3, -5, 7, -11, 13, -1, 2, -3, 5, -7, 11, -1, 2, -3, 1, -2, 3, -7});
TestUtils::printTree(tree);
// From sum of negative values till sum of positive values
for (int i = -42; i <= 48; ++i)
{
std::cout << "Sum " << i << " can ne reached in " << countPathWithSum(tree, i) << " paths\n";
}
return 0;
}
| true |
ffaa9bd254fdb4c30c033ad5d16dd9b3a627bd40 | C++ | sraihan73/Lucene- | /core/src/java/org/apache/lucene/search/DocIdSetIterator.cpp | UTF-8 | 1,797 | 2.578125 | 3 | [] | no_license | using namespace std;
#include "DocIdSetIterator.h"
namespace org::apache::lucene::search
{
shared_ptr<DocIdSetIterator> DocIdSetIterator::empty()
{
return make_shared<DocIdSetIteratorAnonymousInnerClass>();
}
DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass::
DocIdSetIteratorAnonymousInnerClass()
{
}
int DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass::advance(int target)
{
assert(!exhausted);
assert(target >= 0);
exhausted = true;
return NO_MORE_DOCS;
}
int DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass::docID()
{
return exhausted ? NO_MORE_DOCS : -1;
}
int DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass::nextDoc()
{
assert(!exhausted);
exhausted = true;
return NO_MORE_DOCS;
}
int64_t DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass::cost()
{
return 0;
}
shared_ptr<DocIdSetIterator> DocIdSetIterator::all(int maxDoc)
{
return make_shared<DocIdSetIteratorAnonymousInnerClass2>(maxDoc);
}
DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass2::
DocIdSetIteratorAnonymousInnerClass2(int maxDoc)
{
this->maxDoc = maxDoc;
}
int DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass2::docID()
{
return doc;
}
int DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass2::nextDoc() throw(
IOException)
{
return outerInstance->advance(doc + 1);
}
int DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass2::advance(
int target)
{
doc = target;
if (doc >= maxDoc) {
doc = NO_MORE_DOCS;
}
return doc;
}
int64_t DocIdSetIterator::DocIdSetIteratorAnonymousInnerClass2::cost()
{
return maxDoc;
}
int DocIdSetIterator::slowAdvance(int target)
{
assert(docID() < target);
int doc;
do {
doc = nextDoc();
} while (doc < target);
return doc;
}
} // namespace org::apache::lucene::search | true |