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
362e1f039560c705e4a773578c83d8473d4671be
C++
weishichun/DesignPattnsStudy
/Mediator_2.cpp
UTF-8
1,876
3.4375
3
[]
no_license
#include<iostream> using namespace std; class Mediator; class Person{ protected: Mediator *m_pMediator; public: virtual void SetMediator(Mediator* pM) = 0; virtual void GetMsg(string strMsg) = 0;//从中介获取消息 virtual void SendMsg(string strMsg) = 0;//向中介发消息 }; class Mediator{//抽象中介 public: virtual ~Mediator(){} virtual void Send(string strMsg, Person *pPerson) = 0; virtual void SetA(Person *pA) = 0; virtual void SetB(Person *pB) = 0; }; class Renter : public Person{ public: void SetMediator(Mediator* pM) { m_pMediator = pM; } void GetMsg(string strMsg){ cout << "租客收到消息: " << strMsg << endl; } void SendMsg(string strMsg) { m_pMediator->Send(strMsg,this); } }; class Landlord: public Person{ public: void SetMediator(Mediator* pM) { m_pMediator = pM; } void GetMsg(string strMsg){ cout << "房东收到消息: " << strMsg << endl; } void SendMsg(string strMsg) { m_pMediator->Send(strMsg,this); } }; class HoseMediator : public Mediator{ private: Person *m_pA; Person *m_pB; public: HoseMediator(){ m_pA = NULL; m_pB = NULL; } void SetA(Person *pA){ m_pA = pA; } void SetB(Person *pB){ m_pB = pB; } void Send(string strMsg, Person *pPerson){ if(m_pA == pPerson){ m_pB->GetMsg(strMsg); } else{ m_pA->GetMsg(strMsg); } } }; int main(){ Mediator *pM = new HoseMediator(); Person * pR = new Renter(); Person * pL = new Landlord(); pM->SetA(pR); pM->SetB(pL); pR->SetMediator(pM); pL->SetMediator(pM); pR->SendMsg("我想租房! 可有?"); pL->SendMsg("这有一套性价比高的一房一厅待出租,欢迎看房" ); return 0; }
true
8f58e2052af438b755c0237032d1b545e49b31d2
C++
DomWilliams0/CitySimulator
/CitySimulator/src/world/world_terrain.cpp
UTF-8
8,493
2.640625
3
[]
no_license
#include "world.hpp" #include "service/logging_service.hpp" bool isCollidable(BlockType blockType) { static const std::set<BlockType> collidables( {BLOCK_WATER, BLOCK_TREE, BLOCK_BUILDING_WALL, BLOCK_BUILDING_EDGE, BLOCK_BUILDING_ROOF, BLOCK_BUILDING_ROOF_CORNER, BLOCK_BLANK}); return collidables.find(blockType) != collidables.end(); } bool isInteractable(BlockType blockType) { static const std::set<BlockType> interactables( {BLOCK_SLIDING_DOOR, BLOCK_ENTRANCE_MAT}); return interactables.find(blockType) != interactables.end(); } BlockInteractivity getInteractivity(BlockType blockType) { int bi = INTERACTIVTY_NONE; if (isCollidable(blockType)) bi = bi | INTERACTIVITY_COLLIDE; if (isInteractable(blockType)) bi |= INTERACTIVITY_INTERACT; return static_cast<BlockInteractivity>(bi); } LayerType layerTypeFromString(const std::string &s) { if (s == "underterrain") return LAYER_UNDERTERRAIN; if (s == "terrain") return LAYER_TERRAIN; if (s == "overterrain") return LAYER_OVERTERRAIN; if (s == "objects") return LAYER_OBJECTS; if (s == "collisions") return LAYER_COLLISIONS; if (s == "buildings") return LAYER_BUILDINGS; Logger::logWarning("Unknown LayerType: " + s); return LAYER_UNKNOWN; } bool isTileLayer(LayerType layerType) { return layerType == LAYER_UNDERTERRAIN || layerType == LAYER_TERRAIN || layerType == LAYER_OVERTERRAIN; } bool isOverLayer(LayerType layerType) { return layerType == LAYER_OVERTERRAIN; } WorldTerrain::WorldTerrain(World *container, const sf::Vector2i &size) : BaseWorld(container), collisionMap(container), size(size) { tileVertices.setPrimitiveType(sf::Quads); overLayerVertices.setPrimitiveType(sf::Quads); } int WorldTerrain::getBlockIndex(const sf::Vector2i &pos, LayerType layerType) { int index = (pos.x + pos.y * size.x); index += getDepth(layerType) * size.x * size.y; index *= 4; return index; } int WorldTerrain::getVertexIndex(const sf::Vector2i &pos, LayerType layerType) { int index = (pos.x + pos.y * size.x); int depth = getDepth(layerType); if (isOverLayer(layerType)) { int diff = tileLayerCount - overLayerCount; depth -= diff; } index += depth * size.x * size.y; index *= 4; return index; } void WorldTerrain::rotateObject(sf::Vertex *quad, float degrees, const sf::Vector2f &pos) { sf::Vector2f origin(pos.x, pos.y + 1); float radians(degrees * Math::degToRad); const float c(cos(radians)); const float s(sin(radians)); for (int i = 0; i < 4; ++i) { sf::Vector2f vPos(quad[i].position); vPos -= origin; sf::Vector2f rotated(vPos); rotated.x = vPos.x * c - vPos.y * s; rotated.y = vPos.x * s + vPos.y * c; rotated += origin; quad[i].position = rotated; } } void WorldTerrain::positionVertices(sf::Vertex *quad, const sf::Vector2i &pos, int delta) { positionVertices(quad, sf::Vector2f(pos.x, pos.y), delta); } void WorldTerrain::positionVertices(sf::Vertex *quad, const sf::Vector2f &pos, int delta) { quad[0].position = sf::Vector2f(pos.x, pos.y); quad[1].position = sf::Vector2f(pos.x + delta, pos.y); quad[2].position = sf::Vector2f(pos.x + delta, pos.y + delta); quad[3].position = sf::Vector2f(pos.x, pos.y + delta); } int WorldTerrain::getDepth(LayerType layerType) const { auto it = layerDepths.find(layerType); if (it == layerDepths.end()) error("Cannot get depth for invalid layer of type %d", _str(layerType)); return it->second; } sf::VertexArray &WorldTerrain::getVertices(LayerType layerType) { return isOverLayer(layerType) ? overLayerVertices : tileVertices; } void WorldTerrain::resizeVertices() { const int sizeMultiplier = size.x * size.y * 4; blockTypes.resize(tileLayerCount * sizeMultiplier); tileVertices.resize((tileLayerCount - overLayerCount) * sizeMultiplier); overLayerVertices.resize(overLayerCount * sizeMultiplier); } void WorldTerrain::setBlockType(const sf::Vector2i &pos, BlockType blockType, LayerType layer, int rotationAngle, int flipGID) { int vertexIndex = getVertexIndex(pos, layer); sf::VertexArray &vertices = getVertices(layer); sf::Vertex *quad = &vertices[vertexIndex]; positionVertices(quad, pos, 1); tileset->textureQuad(quad, blockType, rotationAngle, flipGID); blockTypes[getBlockIndex(pos, layer)] = blockType; } BlockType WorldTerrain::getBlockType(const sf::Vector2i &tile, LayerType layer) { return blockTypes.at(getBlockIndex(tile, layer)); } void WorldTerrain::addObject(const sf::Vector2f &pos, BlockType blockType, float rotationAngle, int flipGID) { std::vector<sf::Vertex> quad(4); sf::Vector2f adjustedPos = sf::Vector2f(pos.x / Constants::tilesetResolution, (pos.y - Constants::tilesetResolution) / Constants::tilesetResolution); positionVertices(&quad[0], adjustedPos, 1); tileset->textureQuad(&quad[0], blockType, 0, flipGID); if (rotationAngle != 0) rotateObject(&quad[0], rotationAngle, adjustedPos); sf::VertexArray &vertices = getVertices(LAYER_OBJECTS); for (int i = 0; i < 4; ++i) vertices.append(quad[i]); objects.emplace_back(blockType, rotationAngle, Utils::toTile(pos)); } const std::vector<WorldObject> &WorldTerrain::getObjects() const { return objects; } const std::map<LayerType, int> &WorldTerrain::getLayerDepths() const { return layerDepths; } void WorldTerrain::discoverLayers(std::vector<TMX::Layer> &tmxLayers) { int depth = 0; tileLayerCount = 0; overLayerCount = 0; auto layerIt = tmxLayers.cbegin(); while (layerIt != tmxLayers.cend()) { const TMX::Layer &layer = *layerIt; // unknown layer type LayerType layerType = layerTypeFromString(layer.name); if (layerType == LAYER_UNKNOWN) { Logger::logError("Invalid layer name: " + layer.name); layerIt = tmxLayers.erase(layerIt); continue; } // invisible layer if (!layer.visible) { layerIt = tmxLayers.erase(layerIt); continue; } if (isTileLayer(layerType)) ++tileLayerCount; if (isOverLayer(layerType)) ++overLayerCount; layerDepths.insert({layerType, depth}); Logger::logDebuggier(format("Found layer type %1% at depth %2%", _str(layerType), _str(depth))); ++depth; ++layerIt; } } void WorldTerrain::discoverFlippedTiles(const std::vector<TMX::Layer> &layers, std::unordered_set<int> &flippedGIDs) { for (const TMX::Layer &layer : layers) { for (const TMX::TileWrapper &tile : layer.items) { if (!tile.tile.isFlipped() || tile.tile.getGID() == BLOCK_BLANK) continue; int flipGID = tile.tile.getFlipGID(); // already done if (flippedGIDs.find(flipGID) == flippedGIDs.end()) flippedGIDs.insert(flipGID); } } } void WorldTerrain::applyTiles(Tileset &tileset) { this->tileset = &tileset; auto &layers = tmx->layers; for (const TMX::Layer &layer : layers) { LayerType layerType = layerTypeFromString(layer.name); if (layerType == LAYER_OBJECTS) { // objects for (const TMX::TileWrapper &tile : layer.items) { BlockType blockType = static_cast<BlockType>(tile.tile.getGID()); if (blockType == BLOCK_BLANK) continue; addObject(tile.tile.position, blockType, tile.objectRotation, tile.tile.getFlipGID()); } } else if (isTileLayer(layerType)) { sf::Vector2i tempPos; // tiles for (const TMX::TileWrapper &tile : layer.items) { BlockType blockType = static_cast<BlockType>(tile.tile.getGID()); if (blockType == BLOCK_BLANK) continue; tempPos.x = (int) tile.tile.position.x; tempPos.y = (int) tile.tile.position.y; setBlockType(tempPos, blockType, layerType, tile.tile.getRotationAngle(), tile.tile.getFlipGID()); } } } tmx = nullptr; } void WorldTerrain::loadBlockData() { collisionMap.load(); } void WorldTerrain::render(sf::RenderTarget &target, sf::RenderStates &states, bool overLayers) const { states.texture = tileset->getTexture(); target.draw(overLayers ? overLayerVertices : tileVertices, states); } void WorldTerrain::loadFromTileMap(TMX::TileMap &tileMap, std::unordered_set<int> &flippedGIDs) { tmx = &tileMap; // find layer count and depths discoverLayers(tileMap.layers); Logger::logDebug(format("Discovered %1% tile layer(s), of which %2% are overterrain", _str(tileLayerCount), _str(overLayerCount))); // resize vertex array to accommodate for layer count resizeVertices(); // collect any gids that need flipping discoverFlippedTiles(tileMap.layers, flippedGIDs); } CollisionMap *WorldTerrain::getCollisionMap() { return &collisionMap; }
true
d4b878fcac0a2735000d74789f2abf64cae69499
C++
Dijaq/SistemasInteligentes-Semana10
/main.cpp
UTF-8
949
2.640625
3
[]
no_license
#include <iostream> #include <fstream> #include <string.h> using namespace std; int main() { string line; ifstream f("testb.txt"); ofstream write("_testb.csv"); if (f.is_open()) { while ( getline (f,line) ) { //cout << line << '\n'; int j=0; string linea = ""; for(int i=0; i<line.length(); i++) { if((line.substr(i,1) == " ") || (i == (line.length()-1))) { string imp=""; for(int k=0; k<line.substr(j,i).length(); k++) { if((line.substr(j+k,1) == ",") || (line.substr(j,i) == "\"") || (line.substr(j,i) == ";")) { imp += "-"; } else { imp += line.substr(j+k,1); } } linea+=imp+","; //write << line.substr(j,i); j = i; //cout << line.substr(i,1) << '\n'; } } //write << "\n"; linea += "\n"; write << linea; //write << endl; } f.close(); } else { cout << "Unable to open file"; } return 0; }
true
b209f4453eb96d8945c22d4fb936e72d139a4006
C++
rvaughn4/dragonpoop_alpha
/dragonpoop_alpha/dragonpoop/gfx/model/model_animation_frame/model_animation_frame.cpp
UTF-8
2,263
2.625
3
[]
no_license
#include "model_animation_frame.h" #include "../../../core/dpbuffer/dpbuffer.h" namespace dragonpoop { //ctor model_animation_frame::model_animation_frame( dpid id, dpid animation_id, dpid frame_id ) : model_component( id, model_component_type_animation_frame ) { this->animation_id = animation_id; this->frame_id = frame_id; } //dtor model_animation_frame::~model_animation_frame( void ) { } //return animation id dpid model_animation_frame::getAnimationId( void ) { return this->animation_id; } //return frame id dpid model_animation_frame::getFrameId( void ) { return this->frame_id; } //set time in ms void model_animation_frame::setTime( unsigned int ms ) { this->time_ms = ms; } //get time in ms unsigned int model_animation_frame::getTime( void ) { return this->time_ms; } //returns true if has parent bool model_animation_frame::hasParent( dpid id ) { return dpid_compare( &this->frame_id, &id ) || dpid_compare( &this->animation_id, &id ); } //write data to disk/memory bool model_animation_frame::writeData( dpbuffer *b ) { model_animation_frame_header_v1 h; h.h.version = 1; h.h.size = sizeof( h ); h.animation_id = this->animation_id; h.frame_id = this->frame_id; h.time_ms = this->time_ms; return b->writeBytes( (uint8_t *)&h, sizeof( h ) ); } //read data from disk/memory bool model_animation_frame::readData( dpbuffer *b ) { model_animation_frame_header_v1 h; unsigned int rc; rc = b->getReadCursor(); if( !b->readBytes( (uint8_t *)&h, sizeof( h.h ) ) ) return 0; b->setReadCursor( rc ); if( h.h.version < 1 || h.h.size < sizeof( h ) ) return 0; if( !b->readBytes( (uint8_t *)&h, sizeof( h ) ) ) return 0; b->setReadCursor( rc + h.h.size ); this->animation_id = h.animation_id; this->frame_id = h.frame_id; this->time_ms = h.time_ms; return 1; } };
true
9ed086545fed1092df840b4234c9d5a8684a983e
C++
rathore-rahul/leetcode
/solutions/309. Best Time to Buy and Sell Stock with Cooldown.cpp
UTF-8
765
2.9375
3
[]
no_license
class Solution { public:    int maxProfit(vector<int>& prices) {        int n = prices.size();        if(n == 0)            return 0;        vector<int> sold(n,0);        vector<int> un_sold(n,0);        for(int i = 1; i < n; i++){            un_sold[i] = sold[i] = sold[i-1];            for(int j = 0; j < i; j++){                int sell = prices[i] - prices[j];                if(j == 0){                    sold[i] = max(sold[i], sell);               }                else{                    sold[i] = max(sold[i], sell + un_sold[j-1]);               }           }       }        return max(sold[n-1], un_sold[n-1]);   } };
true
ce04945a3dbfcf5e7107124bc8d6c94f0fe83bb4
C++
foolchi/QuickHull3D
/src/zonotope.h
UTF-8
5,380
3.0625
3
[]
no_license
#ifndef ZONOTOPE_H #define ZONOTOPE_H /** * @file zonotope.h * @brief class for calculate */ #include <QtGlobal> #include <QString> #include <QChar> #include "face.h" #include <vector> #include "quickhull3d.h" using namespace std; /** * @brief The Zonotope class */ class Zonotope { public: /** * @brief Constructor */ Zonotope(){ x = y = z = ""; } /** * @brief Constructor * @param x String x * @param y String y * @param z String z */ Zonotope(QString x, QString y, QString z); /** * @brief Constructor * @param zp another zonotope */ Zonotope(const Zonotope &zp){ x = zp.getStringX(); y = zp.getStringY(); z = zp.getStringZ(); tmax = zp.getmaxtime(); tstep = zp.gettimestep(); dynamic = zp.isdynamic(); transform_dynamic(x, y, z); } /** * @brief Constructor * @param x String x * @param y String y * @param z String z * @param Dynamic dynamic(true) or static(false) mode */ Zonotope(QString x, QString y, QString z, bool Dynamic); QString getStringX() const{ return x; } QString getStringY() const{ return y; } QString getStringZ() const{ return z; } bool isdynamic() const{ return dynamic; } /** * @brief Update the coefficient (dynamic mode) * @param t time */ void coeff_update(double t); /** * @brief Get number of points * @return number of points, 2^(numberofvariable) */ int getnumberofpoints(); /** * @brief Get number of variable * @return number of variable */ int getnumberofvariable(); /** * @brief Get the coefficients * @return the coefficients */ virtual double** getcoeff(); /** * @brief Get the coefficients at a given time (dynamic mode) * @param time time * @return coefficients of a given time */ virtual double** getcoeff(double time); /** * @brief Get all the points * @return all the points */ double** getpoints(); /** * @brief Get all the faces * @return all the faces */ vector<Face> getAllFace(); /** * @brief Set max time (dynamic mode) * @param tmax max time */ void setmaxtime(double tmax){ if (tmax > 0) this->tmax = tmax; else{ dynamic = false; this->tmax = 0; } } /** * @brief Set time step (dynamic mode) * @param tstep time step */ void settimestep(double tstep){ if (!dynamic) return; if (tstep >= tmax){ dynamic = false; this->tstep = 0; } else this->tstep = tstep; } double getmaxtime() const{ return tmax; } double gettimestep() const{ return tstep; } public slots: bool verification(QString x, QString y, QString z); private: QString x, y, z; /*!< String x, y, z */ /** * @brief Transform the strings * @param x String x * @param y String y * @param z String z */ void transform(QString x, QString y, QString z); /** * @brief Transform the strings (dynamic mode) * @param x String x * @param y String y * @param z String z */ void transform_dynamic(QString x, QString y, QString z); /** * @brief Transform one string * @param x String to be transformed * @return coefficients of the string */ double* trans(QString x);// Transform each equation /** * @brief Transform one string (dynamic mode) * @param x String to be transformed * @return coefficients of the string */ double **trans_dynamic(QString x); /** * @brief vector multiplication * @param a vector a * @param b vector b * @param d length * @return vector multiplication result */ double multi(double* a, double* b, int d);// Vector multiplication double** coeff; /*!< Coefficients */ double*** coeff_dynamic; /*!< Dynamic coefficients */ int numberofvariable; int numberofdynamicvariable; int numberoftotalvariable; double** coor; double tmax, tstep; bool dynamic; }; /** * @brief Generate faces of the convex from points (brutal force) * @param points points * @param n number of points * @return vector of faces that can form a convex */ vector<Face> generateface(double** points, int n); /** * @brief Generate faces of the convex from points (brutal force) * @param points points * @param n number of points * @return vector of faces that can form a convex */ vector<Face> generateface2(double** points, int n); /** * @brief Print all the faces * @param vp vector of faces */ void printface(vector<Face> vp); /** * @brief normalize the points * @param points * @param n number of points * @return points normalized */ double** normalize(double** points, int n); class CheckPoint{ public: CheckPoint(double** points, int n){ this->points = points; this->n = n; } int getnum(){ return n; } double** getpoints(){ return points; } void check(){ } private: double** points; int n; }; #endif // ZONOTOPE_H
true
649b31c5e0d105be452030808b8bb73d4c8b5c5b
C++
Jubayer-Hossain-Abir-404/Problem-Solving-Using-C-C-
/above average.cpp
UTF-8
477
2.90625
3
[]
no_license
#include<stdio.h> #include<math.h> int main() { int i,j,n; int a[100]; float sum=0; int c=0; float average; printf("The value of n:"); scanf("%d",&n); for(i=0; i<n; i++) { printf("The numbers:"); scanf("%d",&a[i]); sum=sum+a[i]; } average=(float)sum/n; printf("The average:%.2f\n",average); if(a[n-1]>average) { printf("This last number is above average:%d",a[n-1]); } return 0; }
true
49450aa00545835eb7adc9269c35729b4c21b974
C++
sunchun1979/gojo
/src/gameEngine.cpp
UTF-8
4,527
2.59375
3
[]
no_license
#include <cstdio> #include <iostream> #include <string> #include <cstring> #include <unistd.h> #include "common.h" #include "gameEngine.h" #include "player.h" using namespace std; GameEngine::GameEngine() : GameEngine(9) { } GameEngine::GameEngine(int size):m_size(size) { startGNUGo(); string cmd("boardsize " + to_string(m_size)); execute(cmd); } string GameEngine::execute(string command) { //cout << "command: " << command << endl; //cout.flush(); if (writeTo(command) == 0) { //string p = readFrom(); //cout << "return: " << p; //cout.flush(); //return p; return readFrom(); } } void GameEngine::game_human(Player* p1, int computer_color) { execute("clear_board"); execute("komi " + std::to_string(KOMI9)); string cmdComputer; string cmdHuman; if (computer_color == BLACK) { cmdComputer = "play black "; cmdHuman = "play white "; execute(cmdComputer + p1->genMove(this,computer_color)); }else { cmdComputer = "play white"; cmdHuman = "play black "; } string vtx = ""; cout << execute("showboard") << endl; cout.flush(); cin >> vtx; while(vtx != "end") { execute(cmdHuman + vtx); execute(cmdComputer + p1->genMove(this,computer_color)); cout << execute("showboard") << endl; cout.flush(); cin >> vtx; } } int GameEngine::game(Player* p1, Player* p2) { execute("clear_board"); execute("komi " + std::to_string(KOMI9)); // first two moves random execute("play black " + p1->genMoveRnd(this,0)); execute("play white " + p1->genMoveRnd(this,0)); for (int i=0;i<m_depth;++i) { string move; move = p1->genMove(this,0); if (!move.empty()) execute("play black " + move); else { break; } move = p2->genMove(this,1); if (!move.empty()) execute("play white " + move); else { break; } } string result = execute("estimate_score"); return (result[2] == 'B'); } int GameEngine::game_gnugo(Player* p1, int computer_color) { execute("clear_board"); execute("komi " + std::to_string(KOMI9)); string cmdComputer; string cmdGnugo; if (computer_color == BLACK) { cmdComputer = "play black "; cmdGnugo = "genmove white"; execute(cmdComputer + p1->genMove(this,computer_color)); }else { cmdComputer = "play white"; cmdGnugo = "genmove black"; } string vtx = ""; while(vtx.substr(0,6) != "= PASS") { vtx = execute(cmdGnugo); execute(cmdComputer + p1->genMove(this,computer_color)); } string result = execute("estimate_score"); return (result[2] == 'B'); } void GameEngine::error(string errmsg) { cerr << errmsg << endl; abort(); } void GameEngine::startGNUGo() { if (pipe(pfd_a) == -1) error("can't open pipe a"); if (pipe(pfd_b) == -1) error("can't open pipe b"); switch (fork()) { case -1: error("fork failed (try chopsticks)"); case 0: /* Attach pipe a to stdin */ if (dup2(pfd_a[0], 0) == -1) error("dup pfd_a[0] failed"); /* attach pipe b to stdout" */ if (dup2(pfd_b[1], 1) == -1) error("dup pfd_b[1] failed"); execlp("gnugo", "gnugo", "--mode", "gtp", "--quiet", NULL); error("execlp failed"); } /* We use stderr to communicate with the client since stdout is needed. */ /* Attach pipe a to to_gnugo_stream */ to_gnugo_stream = fdopen(pfd_a[1], "w"); /* Attach pipe b to from_gnugo_stream */ from_gnugo_stream = fdopen(pfd_b[0], "r"); } void GameEngine::closeGNUGo() { execute("quit"); if (to_gnugo_stream != NULL) fclose(to_gnugo_stream); if (from_gnugo_stream != NULL) fclose(from_gnugo_stream); } int GameEngine::writeTo(string command) { if (fprintf(to_gnugo_stream, "%s\n", command.c_str()) < 0) error("writeTo fails: " + command); fflush(to_gnugo_stream); return 0; } string GameEngine::readFrom() { string ret; int length = 0; while(length!=1) { if (!fgets(gnugo_line,ENGINE_BUF_SIZE,from_gnugo_stream)) error("readFrom fails"); length=strlen(gnugo_line); ret = ret + gnugo_line; } fflush(stderr); return ret; }
true
0052dd25d5b2009b28b4d01f7b3593205b4b4246
C++
cbrghostrider/Hacking
/leetcode/_000317_shortestDistAllBuildings_accepted.cpp
UTF-8
2,235
2.8125
3
[ "MIT" ]
permissive
class Solution { struct Coord { int r=0; int c=0; }; int R, C; int num_houses=0; vector<vector<int>> dist; // total dist to all houses vector<vector<int>> touched; // how many houses could visit me // O(R*C) time. void bfs(vector<vector<int>>& grid, int hr, int hc, int check) { queue<pair<Coord, int>> q; q.push({{hr, hc}, 0}); while (!q.empty()) { auto elem = q.front(); q.pop(); Coord my_crd = elem.first; int my_dist = elem.second; if (grid[my_crd.r][my_crd.c] == check-1) { dist[my_crd.r][my_crd.c] += my_dist; touched[my_crd.r][my_crd.c] += 1; } vector<Coord> neighs = { {my_crd.r-1, my_crd.c}, {my_crd.r, my_crd.c-1}, {my_crd.r+1, my_crd.c}, {my_crd.r, my_crd.c+1} }; for (const Coord& neigh : neighs) { if (neigh.r < 0 || neigh.c < 0 || neigh.r >= R || neigh.c >= C) continue; if (grid[neigh.r][neigh.c] != check) continue; grid[neigh.r][neigh.c] = check-1; q.push({neigh, my_dist+1}); } } } public: // O(R*R*C*C) time, O(R*C) space. // With added pruning of search space, so finally accepted. int shortestDistance(vector<vector<int>>& grid) { R = grid.size(); C = grid[0].size(); dist = touched = vector<vector<int>>(R, vector<int>(C, 0)); for (int r=0; r<R; r++) { for (int c=0; c<C; c++) { if (grid[r][c] == 1) { bfs(grid, r, c, -1*num_houses); num_houses++; } } } int ans = std::numeric_limits<int>::max(); for (int r=0; r<R; r++) { for (int c=0; c<C; c++) { if (grid[r][c] != -1*num_houses || touched[r][c] != num_houses) continue; ans = std::min(ans, dist[r][c]); } } return (ans == std::numeric_limits<int>::max() ? -1 : ans); } };
true
c7f1d23a342d7a1f1dd01f702c5e357740c574be
C++
cristian-szabo-university/2d-graphics-programming-opengl
/MonkeyInvasion/include/game/game.h
UTF-8
3,549
2.578125
3
[ "MIT" ]
permissive
/** * Name : Game * Author : B00233705 * Version : 1.0 * Copyright : (c) 2013 http://videogamelab.co.uk/monkey-invasion * Description : This file presents the variables and functions declarations * of class Game which setup the game objects and how they are * rendered, updated and any mouse or keyboard events. */ #pragma once #include <iostream> #include <string> #include <vector> #include "zeno\core.h" #include "game\player.h" #include "game\enemy.h" // Constants for radians to degrees transformation const float RAD2DEG = 180.0f / 3.141592f; const float DEG2RAD = 3.141592f / 180.0f; // Maximum number of objects in game for each type const int MAX_BACKGROUND_OBJECT = 1; const int MAX_AMMO_OBJECT = 20; const int MAX_CRATE_OBJECT = 144; const int MAX_BUTTON_OBJECT = 6; const int MAX_TITLE_OBJECT = 6; const enum MapType { MAP_UNUSED, MAP_CRATE, MAP_PLAYER, MAP_ENEMY, MAP_MAX_OBJECTS, MAP_USED }; const enum RoomType { ROOM_UNUSED, ROOM_MENU, ROOM_HELP, ROOM_LEVEL, ROOM_END, ROOM_MAX_SPRITES, ROOM_USED }; const enum BackgroundType { BACKGROUND_UNUSED, BACKGROUND_MAIN, BACKGROUND_HELP, BACKGROUND_GAME, BACKGROUND_END, BACKGROUND_SPRITES, BACKGROUND_USED }; const enum CrateType { CRATE_UNUSED, CRATE_DEFAULT, CRATE_MAX_SPRITES, CRATE_USED }; const enum AmmoType { AMMO_UNUSED, AMMO_BLUK, AMMO_JABOCA, AMMO_MAGOST, AMMO_PERSIM, AMMO_PINAP, AMMO_RAWST, AMMO_RAZZ, AMMO_SPRITES, AMMO_USED }; const enum ButtonType { BUTTON_UNUSED, BUTTON_START, BUTTON_BACK, BUTTON_RETURN, BUTTON_EXIT, BUTTON_HELP, BUTTON_SPRITES, BUTTON_USED }; const enum NumberType { NUMBER_UNUSED, NUMBER_ZERO, NUMBER_ONE, NUMBER_TWO, NUMBER_THREE, NUMBER_FOUR, NUMBER_FIVE, NUMBER_SIX, NUMBER_SEVEN, NUMBER_EIGHT, NUMBER_NINE, NUMBER_SPRITES, NUMBER_USED }; const enum TitleType { TITLE_UNUSED, TITLE_TYPE, TITLE_AMMO, TITLE_GAME, TITLE_WIN, TITLE_LOST, TITLE_SPRITES, TITLE_USED }; // Damage delt by each ammo type const float DAMAGE_AMMO[AMMO_SPRITES + 1] = {0, 12, 14, 16, 18, 20, 22, 24}; // Available munition for each ammo type const int AVAILABLE_AMMO[AMMO_SPRITES + 1] = {0, 7, 6, 5, 4, 3, 2, 1}; class Game : public Zeno::Layout { public: Game(); ~Game(); void setup(); void cleanup(); void render(); void update(); void reshape(int nWidth, int nHeight); void specialKeys(int nKey, int nAction); void characterKeys(int nKey, int nAction); void mouseButtons(int nButton, int nAction); void mousePosition(int nX, int nY); protected: Zeno::Timer cTimer; std::vector<Zeno::Sprite> vecBackgroundSpr; Zeno::Object cBackgroundObj; std::vector<Zeno::Sprite> vecButtonSpr; std::vector<Zeno::Object> vecButtonObj; std::vector<Zeno::Sprite> vecAmmoSpr; std::vector<Zeno::Object> vecAmmoObj; Zeno::Sprite cCrateSpr; std::vector<Zeno::Object> vecCrateObj; std::vector<Zeno::Sprite> vecNumberSpr; Zeno::Object cNumberObj; std::vector<Zeno::Sprite> vecTitleSpr; std::vector<Zeno::Object> vecTitleObj; Zeno::Object cIconObj; std::vector<Zeno::Sprite> vecPlayerSpr; Player cPlayerObj; std::vector<Zeno::Sprite> vecEnemySpr; Enemy cEnemyObj; AmmoType eCurrentAmmo; RoomType eCurrentRoom; int** pGameMap; int nTotalAmmo; int nAvailableAmmo[AMMO_SPRITES]; void fireAmmo(AmmoType eAmmoType, float nPower); void readMap(std::string szFileName, int** pGameMap, int nMapColumns, int nMapRows); void setupMap(); void loadMagazine(AmmoType eAmmoType, int nValue); void restartGame(); private: };
true
ff092117d41cade37b08e1b6fc7ef33554c02be5
C++
mviseu/Cpp_primer
/Chapter18/18_8_Query.cc
UTF-8
610
2.546875
3
[]
no_license
#include "18_8_Query.h" #include "18_8_BaseQuery.h" #include "18_8_NotQuery.h" #include "18_8_AndQuery.h" #include "18_8_OrQuery.h" #include <memory> namespace chapter18 { Query operator~(const Query &qr) { return std::shared_ptr<BaseQuery>(new NotQuery(qr)); } Query operator&(const Query &lhs, const Query &rhs) { return std::shared_ptr<BaseQuery>(new AndQuery(lhs, rhs)); } Query operator|(const Query &lhs, const Query &rhs) { return std::shared_ptr<BaseQuery>(new OrQuery(lhs, rhs)); } std::ostream &operator<<(std::ostream &os, const Query &q) { return os << q.rep(); } } // namespace chapter8
true
d5b42edc7e20663dc3fbb7c990dde4478eef1eea
C++
rohit1309d/Operating-Systems-Lab-CS39002
/Asgn5/Ass5_43_18CS10013_18CS10024/Ass5_43_18CS10013_18CS10024_process.cpp
UTF-8
3,957
2.59375
3
[]
no_license
#include <unistd.h> #include <sys/errno.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/ipc.h> #include <sys/shm.h> #include <bits/stdc++.h> #include <chrono> #include <signal.h> #include <pthread.h> using namespace std; using namespace std::chrono; #define max_size 8 struct job{ pid_t process_id; int producer_numb; int priority; int comp_time; int job_id; }; job create_job(int p_numb,pid_t p_id) { job new_job; new_job.process_id=p_id; new_job.producer_numb=p_numb; new_job.priority=rand()%10 + 1; new_job.comp_time=rand()%4 + 1; new_job.job_id = rand()*rand() % 100000; return new_job; } struct share_item{ int tot_jobs; int job_created = 0; int job_completed = 0; pthread_mutex_t m; job buffer[max_size+10]; int count = 0; }; void producer(int i, share_item* share1){ while(true) { int ran = rand()%4; sleep(ran); pthread_mutex_lock(&(share1->m)); if (share1->count < max_size) { pid_t id = getpid(); if(share1->tot_jobs > share1->job_created){ job p_job = create_job(i+1,id); int i = 0; if(share1->count != max_size){ if(share1->count == 0){ share1->buffer[share1->count++] = p_job; }else{ for(i = share1->count - 1; i >= 0; i-- ){ if(p_job.priority < share1->buffer[i].priority){ share1->buffer[i+1] = share1->buffer[i]; }else{ break; } } share1->buffer[i+1] = p_job; share1->count++; } } cout << "producer : " << p_job.producer_numb << ", producer pid : " << p_job.process_id << ", priority : " << p_job.priority << ", compute time : " << p_job.comp_time << endl; share1->job_created++; } } pthread_mutex_unlock(&(share1->m)); } } void consumer(int i, share_item* share1){ while(true) { int ran = rand() % 4; sleep(ran); pthread_mutex_lock(&(share1->m)); if ((share1->count) != 0) { pid_t id = getpid(); if(share1->tot_jobs > share1->job_completed){ job p_job = share1->buffer[--(share1->count)]; cout << "consumer : " << i+1 << " consumer pid : " << id << ", producer : " << p_job.producer_numb << ", producer pid : " << p_job.process_id << ", priority : " << p_job.priority << ", compute time : " << p_job.comp_time << endl; share1->job_completed++; sleep(p_job.comp_time); } else { pthread_mutex_unlock(&(share1->m)); break; } } pthread_mutex_unlock(&(share1->m)); } } int main() { share_item *share; int shmid; key_t key = 341; shmid = shmget(IPC_PRIVATE, sizeof(share_item), 0666|IPC_CREAT); share = (share_item *) shmat(shmid, 0, 0); pthread_mutexattr_t atr; pthread_mutexattr_init(&atr); pthread_mutexattr_setpshared(&atr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&(share->m), &atr); int np,nc; cout << "Enter the number of producers : "; cin >> np; cout << "Enter the number of consumers : "; cin >> nc; cout << "Enter the total number of jobs : "; cin >> share->tot_jobs; pid_t producers[np] = {0}; pid_t consumers[nc] = {0}; int i; auto start = high_resolution_clock::now(); for(i = 0; i < np; i++){ if ((producers[i] = fork()) == 0) { producer(i, share); } } for(i = 0; i < np; i++){ if ((consumers[i] = fork()) == 0) { consumer(i, share); } } while(share->job_created != share->job_completed || share->job_completed != share->tot_jobs); shmdt(share); shmctl(shmid, IPC_RMID, NULL); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << "Time taken : " << duration.count() << " microseconds" << endl; for (int i = 0; i < np; ++i) { kill(producers[i], SIGTERM); } for (int i = 0; i < nc; ++i) { kill(consumers[i], SIGTERM); } return 0; }
true
a730f808b4120e75f3452daf97a06c63911b57de
C++
eglrp/PointCloudPractice
/week3/src/kmeans.cpp
UTF-8
3,039
2.890625
3
[]
no_license
#include "kmeans.h" void Kmeans::fit(const std::vector<Eigen::VectorXd> &data) { // 检查输入有效性 assert(data.size() > 0 && k <= data.size() && "Data not valid\n"); numDimensions = data[0].size(); for (auto &item:data) { if (item.size() != numDimensions) { std::cerr << "Data dimension not match\n"; return; } } this->data = data; // 初始聚类 initialCentroids(); // 迭代计算 bool converge = false; int iter = 0; while (!converge) { computeClusters(); double diff = computeCentroids(); if (diff < tolerance || iter == maxIter) converge = true; ++iter; } } std::vector<int> Kmeans::predict(const std::vector<Eigen::VectorXd> &data) { assert(!centroids.empty() && "Should call fit() first\n"); // 检查输入有效性 if (data.empty()) return std::vector<int>(); for (auto &item:data) { if (item.size() != numDimensions) { std::cerr << "Data dimension not match\n"; return std::vector<int>(); } } // 预测 int size = data.size(); std::vector<int> ret(size, 0); for (int i = 0; i < size; ++i) { int clusterIdx = 0; double minDist = std::numeric_limits<double>::max(); // 寻找最近的聚类中心 for (int j = 0; j < k; ++j) { double dist = (centroids[j] - data[i]).norm(); if (dist < minDist) { minDist = dist; clusterIdx = j; } } ret[i] = clusterIdx; } return ret; } void Kmeans::initialCentroids() { centroids = std::vector<Eigen::VectorXd>(k, Eigen::VectorXd::Zero(numDimensions, 1)); srand(time(NULL)); for (int i = 0; i < k; ++i) { int randomIdx = rand() % data.size(); centroids[i] = data[randomIdx]; } } double Kmeans::computeCentroids() { auto oldCentroids = centroids; centroids = std::vector<Eigen::VectorXd>(k, Eigen::VectorXd::Zero(numDimensions, 1)); for (int i = 0; i < k; ++i) { int count = 0; for (int j = 0; j < clusters[i].size(); ++j) { int idx = clusters[i][j]; centroids[i] += data[idx]; ++count; } centroids[i] /= (count + 1e-5); } // 计算新中心和旧中心的差别 double diff = 0; for (int i = 0; i < k; ++i) diff += (oldCentroids[i] - centroids[i]).norm(); return diff; } void Kmeans::computeClusters() { clusters = std::vector<std::vector<int>>(k, std::vector<int>()); for (int i = 0; i < data.size(); ++i) { int clusterIdx = 0; double minDist = std::numeric_limits<double>::max(); // 寻找最近的聚类中心 for (int j = 0; j < k; ++j) { double dist = (centroids[j] - data[i]).norm(); if (dist < minDist) { minDist = dist; clusterIdx = j; } } clusters[clusterIdx].push_back(i); } }
true
5990f1095d2e3183772ae3f0615cc8b8ec3a57d7
C++
JonMoore75/SDL_GUI
/Source/Font_TTF.cpp
UTF-8
1,080
2.890625
3
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
#include "Font_TTF.h" #include <SDL2\SDL_ttf.h> FontTTF::FontTTF() { } FontTTF::~FontTTF() { Release(); } bool FontTTF::LoadFont(const char* file, int ptsize, Color textColor) { m_pFont = TTF_OpenFont(file, ptsize); if (m_pFont == nullptr) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error!", "Font not loaded", nullptr); m_ptsize = 0; return false; } m_ptsize = ptsize; m_textColor = textColor; m_height = TTF_FontHeight(m_pFont); m_ascent = TTF_FontAscent(m_pFont); m_lineskip = TTF_FontLineSkip(m_pFont); return true; } void FontTTF::Release() { TTF_CloseFont(m_pFont); m_pFont = nullptr; m_ptsize = 0; } int FontTTF::SizeUTF8(const std::string& text, int& w, int& h, Uint32 wrapLength/* = 0*/) const { // Returns: 0 on success with the ints pointed to by w and h set as appropriate, // if they are not NULL. -1 is returned on errors, such as a glyph in the string not being found. if (wrapLength > 0) return TTF_SizeUTF8_Wrapped(m_pFont, text.c_str(), &w, &h, wrapLength); else return TTF_SizeUTF8(m_pFont, text.c_str(), &w, &h); }
true
fe9c17c5c136432775b07f05626d1a6f9096170c
C++
rahulsud48/cpp
/englcon1.cpp
UTF-8
1,407
3.890625
4
[]
no_license
#include<iostream> using namespace std; class Distance{ private: int feet; float inches; public: Distance() : feet(0), inches(0.0){ /* First Constructor */ } Distance(int feet_, float inches_) : feet(feet_), inches(inches_){ /* Second Constructor */ } void get_distance(int feet_, float inches_){ /* Third Constructor */ feet = feet_; inches = inches_; } void display(){ cout << "Feet: " << feet; cout << "\nInches: " << inches; cout << endl; } void add(Distance d){ feet += d.feet; inches += d.inches; } Distance scale(float n){ Distance temp(feet,inches); temp.feet *= n; temp.inches *= n; return temp; } void mul_dist(Distance, Distance); }; void Distance::mul_dist(Distance dd1, Distance dd2){ feet *= dd1.feet * dd2.feet; inches *= dd2.inches * dd2.inches; } int main(){ Distance d1(6,4), d2(10,2); Distance d4, d5; d5.get_distance(20, 30.0); d1.display(); d2.display(); d1.add(d2); d1.display(); Distance d3 = d1.scale(0.5); d3.display(); d1.mul_dist(d2, d3); d1.display(); d5.mul_dist(d1, d4); d5.display(); return 0; }
true
5e1c5a29840a122dfef02fca5997a6c953bc407a
C++
Warboss-rus/concurrencycourse
/src/8_thread_safe_queue.cpp
UTF-8
831
2.84375
3
[]
no_license
#include <benchmark/benchmark.h> #include "OptimizedThreadSafeQueue.h" #include "SimpleThreadSafeQueue.h" #include "JoinableThread.h" #include <thread> // Do not modify template <class T> void bench_body(benchmark::State& state) { srand(0); for (auto _ : state) { T queue; JoinableThread<std::thread> t1([&] { for (int i = 0; i < state.range(); ++i) { queue.push(rand()); } }); JoinableThread<std::thread> t2([&] { for (int i = 0; i < state.range(); ++i) { queue.wait_and_pop(); } }); } } void simple(benchmark::State& state) { bench_body<SimpleThreadSafeQueue<int>>(state); } void optimized(benchmark::State& state) { bench_body<optimized_thread_safe_queue<int>>(state); } BENCHMARK(simple)->Range(8, 8 << 15)->Iterations(25); BENCHMARK(optimized)->Range(8, 8 << 15)->Iterations(25);
true
761ab2e12c9029122f71b38edc6e09793a08a1c4
C++
peeyush11/bag-of-words
/src/clustering/feature_point.ipp
UTF-8
3,146
3.328125
3
[]
no_license
/** * @file feature_point.ipp * * @author Jan Quakernack * @version 1.0 */ #include <numeric> #include "tools/linalg.hpp" namespace igg { template <class T> size_t NearestNeighbor (const FeaturePoint<T>& kQueryPoint, const std::vector<FeaturePoint<T>>& kPointSet) { if (kPointSet.empty()) {throw std::invalid_argument("Empty set of points.");} const auto kNumPoints = kPointSet.size(); T min_distance = std::numeric_limits<T>::max(); size_t nearest_cluster_index = 0; FeaturePoint<T> difference; // Initialized inside loop T squared_distance; // Initialized inside loop for (size_t point_index = 0; point_index<kNumPoints; point_index++) { difference = Difference<FeaturePoint<T>>(kQueryPoint, kPointSet[point_index]); squared_distance = SquaredL2Norm<FeaturePoint<T>>(difference); if (squared_distance<=min_distance) { min_distance = squared_distance; nearest_cluster_index = point_index; } } return nearest_cluster_index; } template <class T> std::vector<T> Flatten (std::vector<std::vector<T>>&& vector_of_vectors) { // Use lambda expression to get total number of elements auto add_size = [](size_t num_elements, std::vector<T> vector_in_vector) -> size_t {return std::move(num_elements)+vector_in_vector.size();}; const auto kNumElements = std::accumulate (vector_of_vectors.begin(), vector_of_vectors.end(), 0, add_size); // Reference: https://stackoverflow.com/questions/201718/concatenating-two-stdvectors std::vector<T> flattened_vector; flattened_vector.reserve(kNumElements); for(auto vector_in_vector: vector_of_vectors) { flattened_vector.insert (flattened_vector.end(), std::make_move_iterator(vector_in_vector.begin()), std::make_move_iterator(vector_in_vector.end())); } return flattened_vector; } template <class T> std::vector<FeaturePoint<T>> FromMat(cv::Mat&& mat) { std::vector<FeaturePoint<T>> point_set; point_set.reserve(mat.rows); for(int index = 0; index<mat.rows; index++) { cv::Mat row_mat = mat.row(index); FeaturePoint<T> point(row_mat.begin<T>(), row_mat.end<T>()); point_set.emplace_back(point); } return point_set; } template <class T> cv::Mat ToMat(std::vector<FeaturePoint<T>>&& point_set) { if (point_set.empty()) {throw std::invalid_argument("Empty set of points.");} const auto kNumRows = point_set.size(); const auto kFlattened = Flatten(std::move(point_set)); // Arguments of cv::Mat::reshape: channels, rows return cv::Mat(kFlattened, true).reshape(0, static_cast<int>(kNumRows)); } template <class T> cv::Mat ToMat(const std::vector<FeaturePoint<T>>& kPointSet) { return ToMat(std::vector<FeaturePoint<T>>(kPointSet)); } template <class T> std::vector<FeaturePoint<T> const *> GetPointers (const std::vector<FeaturePoint<T>>& kPointSet) { std::vector<FeaturePoint<T> const *> pointers(kPointSet.size()); // Use lambda expression to get address of each element std::transform (kPointSet.begin(), kPointSet.end(), pointers.begin(), [](const auto& kPoint){return &kPoint;}); return pointers; } } // namespace igg
true
1e3c3e14ac1d03de11270ab0590eb5e545ffb633
C++
Sadeeb96/Genetic-Algorithm
/GeneticAlgorithm.cpp
UTF-8
11,995
2.734375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct chromosome { string a; string b; } pop[5],ch1,ch2; bool complete(int visA[],int visB[]) { for(int i=0; i<8; i++) { if(visA[i]==0 || visB[i]==0) { return false; } } return true; } void populate() { string str="12345678"; string str2="qqqqqrrr"; string g[41000]; string g2[100]; int i=0; do { // //cout << str << endl; g[i]=str; i++; } while (next_permutation(str.begin(), str.end())); i=0; do { // //cout << str << endl; g2[i]=str2; i++; } while (next_permutation(str2.begin(), str2.end())); int d=0; for(int i=0; i<5; i++) { int x=d+rand()%8064; int y=rand()%56; pop[i].a=g[x]; pop[i].b=g2[y]; //cout<<pop[i].a<<" "<<pop[i].b<<endl; d+=8064; } } string pmx(string pa1,string pa2) { srand(time(NULL)); string p1=pa1; string p2=pa2; int a=rand()%8; int b=rand()%8; while(a==b){ b=rand()%10; } if(b<a)swap(a,b); string c="********"; for(int i=a;i<=b;i++){ c[i]=p1[i]; } //cout<<c<<endl; for(int i=a;i<=b;i++){ int f=0; for(int j=a;j<=b;j++){ if(c[j]==p2[i])f=1; } if(f==0){ char c=p2[i]; } else{ continue; } bool found=false; char e=p2[i]; // cout<<"Next:"<<e<<endl; int x=i; while(!found) { char n=p1[x]; for(int k=0;k<8;k++){ if(p2[k]==n){ x=k; } } if(x<a || x>b)found=true; } c[x]=e; } for(int i=0;i<8;i++){ if(c[i]=='*'){ c[i]=p2[i]; } } return c; } void pmx_crossover(chromosome p1,chromosome p2,struct chromosome *child1,struct chromosome *child2) { child1->a=pmx(p1.a,p2.a); child2->a=pmx(p2.a,p1.a); random_shuffle(p1.b.begin(), p1.b.end()); child1->b=p1.b; random_shuffle(p2.b.begin(), p2.b.end()); child2->b=p2.b; } int fitness(chromosome c) { int fitness = 28; for(int i=0; i<7; i++) { for (int j=i+1; j<8; j++) { int x=c.a[i]-'0'; int y=c.a[j]-'0'; //(c.a[i]-'0')- (c.a[j]-'0') if (abs(i-j) == abs(x-y)) { if (c.b[i]=='q' or c.b[j]=='q') { //cout<<fitness<<endl; fitness--; // cout<<i<<" "<<j<<endl; } } } } return fitness; } void cycleCrossover(chromosome parent1,chromosome parent2,struct chromosome *child1,struct chromosome *child2) { //srand(time(NULL)); random_shuffle(parent1.b.begin(), parent1.b.end()); child1->b=parent1.b; random_shuffle(parent2.b.begin(), parent2.b.end()); child2->b=parent2.b; if(parent1.a==parent2.a) { child1->a=parent1.a; child2->a=parent2.a; return; } child1->a="00000000"; child2->a="00000000"; string a=parent1.a; string b=parent2.a; int visA[]= {0,0,0,0,0,0,0,0}; int visB[]= {0,0,0,0,0,0,0,0}; string ac[100]; string bc[100]; for(int i=0; i<8; i++) { ac[i]=""; bc[i]=""; } int nu=1; while(!complete(visA,visB)) { int x; char h; for(int i=0; i<8; i++) { if(visA[i]==0) { visA[i]=nu; h=a[i]; x=i; ////cout<<h<<" "<<b[x]<<endl; visB[x]=nu; break; } } int cycle=0; while(cycle==0) { for (int i=0; i<8; i++) { if (a[i]==b[x]) { visB[x]=nu; visA[i]=nu; x=i; ////cout<<x<<" "<<a[i]<<" "<<b[x]<<endl; //int t; //cin>>t; break; } } if (b[x]==h) { visB[x]=nu; cycle=1; nu++; } } } nu--; for(int i=0; i<8; i++) //cout<<visA[i]<<" "; //cout<<endl; for(int i=1; i<=4; i++) { if(i%2==1) { for(int k=0; k<8; k++) { if(visA[k]==i) { child1->a[k]=parent1.a[k]; } } } else { for(int k=0; k<8; k++) { if(visA[k]==i) { child1->a[k]=parent2.a[k]; } } } } for(int i=1; i<=nu; i++) { if(i%2==1) { for(int k=0; k<8; k++) { if(visA[k]==i) { child2->a[k]=parent2.a[k]; } } } else { for(int k=0; k<8; k++) { if(visA[k]==i) { child2->a[k]=parent1.a[k]; } } } } ////cout<<child1->a<<" "<<child2->a<<endl; ////cout<<endl; //for(int i=0; i<8; i++) // //cout<<child1->a[i]<<" "; ////cout<<endl; //for(int i=0; i<8; i++) // //cout<<child2->a[i]<<" "; ////cout<<child1.b<<" "<<child2.b<<endl; ////cout<<child1->a<<" "<<child2->a<<endl; } void rank_selection(chromosome s[],struct chromosome *p1,struct chromosome *p2) { //srand(time(NULL)); for(int i=0; i<4; i++) { for(int j=i+1; j<5; j++) { if(fitness(s[i])>=fitness(s[j])) { string tempa =s[i].a; string tempb =s[i].b; s[i].a=s[j].a; s[i].b=s[j].b; s[j].a=tempa; s[j].b=tempb; } } } int t=10; int r=rand()%10; int sum=0; //cout<<r<<endl; int pdx; for(int i=0; i<5; i++) { sum+=i; if(sum>=r) { pdx=i; p1->a=s[i].a; p1->b=s[i].b; break; } } int t1=10; int r1=rand()%10; if(r1==r) { while(r1-r==0) { r1=rand()%10; } } int sum1=0; int pdx2; for(int i=0; i<5; i++) { sum1+=i; if(sum1>=r1) { pdx2=i; p2->a=s[i].a; p2->b=s[i].b; break; } } if(pdx==pdx2) { p1->a=p2->a; p1->b=p2->b; } ////cout<<p1->a<<" "<<p2->a; } chromosome scramble_mutation(chromosome so) { string s=so.a+so.b; int i1=rand()%16; int i2=rand()%16; if(i1>i2)swap(i1,i2); string x=""; for(int i=i1;i<=i2;i++){ x+=s[i]; } random_shuffle(x.begin(), x.end()); //cout<<s<<endl; int j=0; for(int i=i1;i<=i2;i++){ s[i]=x[j++]; } //cout<<s<<endl; chromosome ms; ms.a=""; ms.b=""; for(int i=0; i<16; i++) { if(s[i]=='q' || s[i]=='r') { ms.b+=s[i]; } else { ms.a+=s[i]; } } //cout<<ms.a<<" "<<ms.b; return ms; } chromosome swap_mutation(chromosome so) { string s=so.a+so.b; int i1=rand()%16; int i2=rand()%16; swap(s[i1],s[i2]); chromosome ms; ms.a=""; ms.b=""; for(int i=0; i<16; i++) { if(s[i]=='q' || s[i]=='r') { ms.b+=s[i]; } else { ms.a+=s[i]; } } //cout<<ms.a; return ms; } int main() { srand(time(NULL)); //populate(); //chromosome p1,p2; //rank_selection(pop,p1,p2); ////cout<<p1.a<<" "<<p2.a; //float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); ////cout<<r; //chromosome n=swap_mutation(pop[1]); ////cout<<n.a<<endl; populate(); chromosome p1,p2,c1,c2,best; best.a=pop[0].a; best.b=pop[0].b; for(int i=0; i<5; i++) { //cout<<fitness(pop[i])<<endl; if(fitness(pop[i])>fitness(best)) { best.a=pop[i].a; best.b=pop[i].b; } } chromosome Q[5]; int idx=0; for(int i=0; i<2; i++) { rank_selection(pop,&p1,&p2); pmx_crossover(p1,p2,&c1,&c2); Q[idx].a=c1.a; Q[idx+1].a=c2.a; Q[idx].b=c1.b; Q[idx+1].b=c2.b; idx+=2; } ////cout<<endl; //for(int i=0; i<4; i++) //{ ////cout<<Q[i].a<<" "<<fitness(Q[i])<<endl; //} for(int k=0; k<100; k++) { for(int j=0; j<5; j++) { ////cout<<fitness(pop[j])<<endl; if(fitness(Q[j])>=fitness(best)) { best.a=Q[j].a; best.b=Q[j].b; } } idx=0; for(int i=0; i<2; i++) { rank_selection(pop,&p1,&p2); pmx_crossover(p1,p2,&c1,&c2); //pmx_crossover(p1,p2,&c1,&c2); float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); if(r<=0.01) { c1=swap_mutation(c1); } r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); if(r<=0.01) { c2=swap_mutation(c2); } Q[idx].a=c1.a; Q[idx+1].a=c2.a; Q[idx].b=c1.b; Q[idx+1].b=c2.b; idx+=2; } } //cout<<best.a<<" "<<best.b<<endl; cout<<"\nSolution:"; //cout<<fitness(best)<<endl; if(!(best.a[0]>='1' && best.a[0]<='8')){ int A[]={0,0,0,0,0,0,0,0,0}; for(int i=1;i<8;i++){ int x=best.a[i]-'0'; // cout<<x<<"h"<<endl; A[x]=1; } for(int i=1;i<=8;i++){ if(A[i]==0){best.a[0]=i+'0';} } int q=0; int r=0; for(int i=1;i<8;i++){ if(best.b[i]=='q')q++; if(best.b[i]=='r')r++; } if(q<5)best.b[0]='q'; else if(r<3)best.b[0]='r'; } chromosome solution; solution.a=""; solution.b=""; for(int i=0;i<8;i++){ solution.a+=best.a[i]; solution.b+=best.b[i]; } cout<<fitness(solution)<<endl; for(int i=0; i<8; i++) { cout<<best.a[i]; } cout<<endl; for(int i=0; i<8; i++) { cout<<best.b[i]; } cout<<endl; string board[8]; for(int i=0; i<8; i++) { board[i]=""; for(int j=0; j<8; j++) { board[i]+="*"; } } for(int i=0; i<8; i++) { board[i][(best.a[i]-'0')-1]=best.b[i]; } for(int i=0; i<8; i++) { for(int j=0;j<8;j++){ cout<<board[i][j]<<" "; } cout<<endl<<endl; } chromosome x; x.a="12345678"; x.b="rrrqqqqq"; x=swap_mutation(x); cout<<x.a<<" "<<x.b<<endl; } //71863425 71863425 //43587162 //qqrqrqrq
true
947c4a9bb653de3c53c3db11636a94db2e0588fd
C++
quzery/Leetcode2019
/118.杨辉三角.cpp
UTF-8
1,124
3.328125
3
[]
no_license
/* * @lc app=leetcode.cn id=118 lang=cpp * * [118] 杨辉三角 * * https://leetcode-cn.com/problems/pascals-triangle/description/ * * algorithms * Easy (63.13%) * Likes: 174 * Dislikes: 0 * Total Accepted: 32K * Total Submissions: 50.5K * Testcase Example: '5' * * 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 * * * * 在杨辉三角中,每个数是它左上方和右上方的数的和。 * * 示例: * * 输入: 5 * 输出: * [ * ⁠ [1], * ⁠ [1,1], * ⁠ [1,2,1], * ⁠ [1,3,3,1], * ⁠[1,4,6,4,1] * ] * */ class Solution { public: vector<vector<int>> generate(int numRows) { if(numRows == 0) return {}; vector<vector<int>> res; for(int i=0;i<numRows;i++){ if(i==0) {res.push_back({1});continue;} vector<int> vv; for(int j=0;j<res[i-1].size()+1;j++){ if(j==0 || j==res[i-1].size()) {vv.push_back(1);continue;} vv.push_back(res[i-1][j-1]+res[i-1][j]); } res.push_back(vv); } return res; } };
true
6cbd906ab0c2ea40fb74ee2035fbc538870d332b
C++
fconrotte/android_astronomy
/cepheids.ino
UTF-8
2,241
3.75
4
[ "LicenseRef-scancode-public-domain" ]
permissive
/* Cepheids pulsing period & brightness This example shows how to fade 2 LEDs on pins 3 and 5 using the analogWrite() function, to simulate Cepheids stars. This is to illustrate the relation between period & brightness in Cepheid stars, as discovered by Henrietta Swan Leavitt in 1908. Read https://en.wikipedia.org/wiki/Cepheid_variable The analogWrite() function uses PWM, so if you want to change the pin you're using, be sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11. This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Fade */ int shortPeriodCepheid = 3; // the PWM pin the LED is attached to int shortPeriodCepheidFadeAmount = 5; // how many points to fade the LED by int shortPeriodCepheidBrightness = 0; // how bright the LED is int longPeriodCepheid = 5; // the PWM pin the LED is attached to int longPeriodCepheidFadeAmount = 2; // how bright the LED is int longPeriodCepheidBrightness = 0; // how bright the LED is // the setup routine runs once when you press reset: void setup() { // declare pin 3 and 5 to be an output: pinMode(shortPeriodCepheid, OUTPUT); pinMode(longPeriodCepheid, OUTPUT); } // the loop routine runs over and over again forever: void loop() { // set the shortPeriodCepheidBrightness of shortPeriodCepheid: analogWrite(shortPeriodCepheid, shortPeriodCepheidBrightness); analogWrite(longPeriodCepheid, longPeriodCepheidBrightness); // change the shortPeriodCepheidBrightness for next time through the loop: shortPeriodCepheidBrightness = shortPeriodCepheidBrightness + shortPeriodCepheidFadeAmount; longPeriodCepheidBrightness = longPeriodCepheidBrightness + longPeriodCepheidFadeAmount; // reverse the direction of the fading at the ends of the fade: if (shortPeriodCepheidBrightness <= 0 || shortPeriodCepheidBrightness >= 100) { shortPeriodCepheidFadeAmount = -shortPeriodCepheidFadeAmount; } if (longPeriodCepheidBrightness <= 0 || longPeriodCepheidBrightness >= 254) { longPeriodCepheidFadeAmount = -longPeriodCepheidFadeAmount; } // wait for 30 milliseconds to see the dimming effect delay(30); }
true
239ff16c9f1dff02d22e0c7848a8f56b4f9937c7
C++
Bloodclot24/clown1
/Trabajo Practico 2/BloqueDeRegistros.h
UTF-8
738
2.65625
3
[]
no_license
#ifndef BLOQUEDEREGISTROS_H_ #define BLOQUEDEREGISTROS_H_ #include <iostream> #include <string.h> #include "Registro.h" #include "LockFile.h" #define MAX_REG_MEM 100 class BloqueDeRegistros { private: int numeroBloque; Registro registros[MAX_REG_MEM]; int cantidadDeRegistros; void acomodarBloque(int posicion); bool buscarRegistro(Registro registro); public: BloqueDeRegistros(); virtual ~BloqueDeRegistros(); bool agregarRegistro(Registro registro); bool eliminarRegistro(Registro registro); bool modificarRegistro(Registro registro); bool consultarRegistro(Registro& registro); void setNumeroBloque(int numero); int getCantidadDeRegistros(); void persistir(); void recuperar(); }; #endif /* BLOQUEDEREGISTROS_H_ */
true
b06b837e0bdcca9ef6de32ea7f58106a59af4a8a
C++
asdlei99/p81z
/sources/FMOperator.cpp
UTF-8
1,125
2.53125
3
[]
no_license
#include "FMOperator.h" void FMOperator::setup(float sampleRate) { eg_.setup(sampleRate); osc_.setup(sampleRate); } void FMOperator::clear() { eg_.clear(); osc_.clear(); } void FMOperator::adjustBuffer(unsigned size) { buffer_.reset(new float[size]); } void FMOperator::noteOn(int note, float velocity) { eg_.noteOn(note, velocity); osc_.noteOn(note); } void FMOperator::noteOff() { eg_.noteOff(); osc_.noteOff(); } void FMOperator::pitchBend(float bendSemitones) { osc_.pitchBend(bendSemitones); } void FMOperator::run(const float *audioIn, float *audioOut, unsigned numFrames) { float *egTemp = buffer_.get(); eg_.run(egTemp, numFrames); osc_.run(egTemp, audioIn, audioOut, numFrames); } void FMOperator::runAdding(const float *audioIn, float *audioOut, unsigned numFrames) { float *egTemp = buffer_.get(); eg_.run(egTemp, numFrames); osc_.runAdding(egTemp, audioIn, audioOut, numFrames); } void FMOperator::useSettings(const Settings *s) { settings_ = s; eg_.useSettings(s ? &s->eg : nullptr); osc_.useSettings(s ? &s->osc : nullptr); }
true
3e9c7f222ba628b1418aa4bd2c37f0621d8cb55f
C++
coveleski/jawsome
/dispatcher.h
UTF-8
1,198
3.15625
3
[]
no_license
/** * Authored by David Vriezen * 27 October, 2013 * Com S 352 Project 1 */ #include <queue> #include <vector> #include <time.h> /** A container class to hold the thread context, priority, and ready_time, while in the queue */ class Task{ public: //Constructor Task(int pri, ucontext_t *con); //The task's priority int priority; //The time the task became ready time_t ready_time; //pointer to the thread's context ucontext_t *context; }; //A comparator, to determine which Task has higher priority class TaskCompare{ public: //A constructor TaskCompare(const bool& revparam=false); //Overloaded compare operator bool operator() (const Task& lhs, const Task& rhs); private: //signals which order to sort in bool reverse; }; //Typedef a Priority Queue of tasks, compared using TaskCompare typedef std::priority_queue<Task,std::vector<Task>,TaskCompare> TaskPQ; //A class containing necessary items to schedule user threads class Dispatcher { public: //Dispatcher constructor Dispatcher(int max); //A priority Queue of tasks TaskPQ pq; //the current number of spawned kernel threads int cur_klt; //the number of max kernel threads int max_klt; };
true
cd24436ea308b0ed8751a5bab08e6cbbe648d370
C++
dawnarc/high_level_container
/multi_type_list/unreal_version/VarObject.h
UTF-8
815
2.59375
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" enum EValueType { Integer, Float, String, Object, None, }; /** * */ class TOWERDEFENSE_API VarObject { public: VarObject(); VarObject(int Val); VarObject(float Val); VarObject(const FString& Val); VarObject(const UObject* Val); ~VarObject(); EValueType ValueType() { return ValType_; }; int IntVal() { return IntVal_; }; float FloatVal() { return FloatVal_; }; FString& StrVal() { return StrVal_; }; UObject* ObjVal() { return ObjVal_; } /*void SetValue(int Val); void SetValue(float Val); void SetValue(const FString& Val); void SetValue(UObject* Val);*/ private: EValueType ValType_; int IntVal_; float FloatVal_; FString StrVal_; UObject* ObjVal_; };
true
22de40521944b2881553aad32d7855ce884c7222
C++
Siapran/dunkleheld
/DunkleHeld/src/Collidable.h
UTF-8
1,092
2.71875
3
[]
no_license
/* * File: Collidable.h * Author: siapran * * Created on February 5, 2015, 9:17 AM */ #ifndef COLLIDABLE_H #define COLLIDABLE_H #include <SFML/Graphics.hpp> class Actor; //enum CollideReaction { // RESOLVE, DAMAGE, ACTION, NONE //}; class Collidable { public: Collidable(sf::Vector2f m_position = sf::Vector2f()) : m_position(m_position) { } virtual bool collidesWithCircle(sf::Vector2f pos, float radius); virtual sf::Vector2f resoleCollision(sf::Vector2f pos, float radius); virtual void onCollide(Actor *target) = 0; sf::Vector2f m_position; static float distance(sf::Vector2f a, sf::Vector2f b); static float squareDistance(sf::Vector2f a, sf::Vector2f b = sf::Vector2f()); static bool collidesBoxVSCircle(sf::FloatRect box, sf::Vector2f pos, float radius); static sf::Vector2f resolveBoxVSCircle(sf::FloatRect box, sf::Vector2f pos, float radius); static sf::Vector2f getCentre(sf::FloatRect box); static inline float clamp(float left, float right, float z); }; #endif /* COLLIDABLE_H */
true
930610d319c10d423f4ca2680c5ddeeb9b8bc514
C++
bdajeje/SDLEngine
/graphics/animation.hpp
UTF-8
594
2.625
3
[]
no_license
#ifndef ANIMATION_HPP #define ANIMATION_HPP #include <string> #include <vector> #include "graphics/drawable.hpp" namespace graphics { namespace info { static const std::string Framerate {"framerate"}; static const std::string NbrClips {"nbr_clips"}; } class Animation : public Drawable { public: Animation(const utils::Configuration& info, const SDL_Rect& parent); void newFrame(); private: void setFramerate(uint framerate); private: uint m_framerate; uint m_current_frame {0}; std::vector<SDL_Rect> m_texture_clips; }; } #endif // ANIMATION_HPP
true
b339c71c6d20e4d922f07c4a41fe801a1efee6d1
C++
twbikeman/advance
/deepcopying.cpp
UTF-8
821
3.40625
3
[]
no_license
#include <cstring> #include <cassert> #include <iostream> class MyString { private: char *m_data; int m_length; public: MyString(const char *source="") { assert(source); m_length = std::strlen(source) + 1; m_data = new char[m_length]; for (int i = 0; i < m_length; ++i) m_data[i] = source[i]; m_data[m_length -1] = '\0'; } MyString(const MyString &source) : m_length{source.m_length}, m_data{source.m_data} {} ~MyString() { delete[] m_data; } char* getString() {return m_data;} int getLine() {return m_length;} void deepCopy(const MyString& source); }; void MyString::deepCopy(const MyString& source) { delete[] m_data; } int main() { MyString hello("Hello, world"); MyString copy{hello}; std::cout << hello.getString() << '\n'; return 0; }
true
90c7a0d54a195128dd5d6e0947748f09d0b69846
C++
abarankab/competitive-programming
/zachetik/zachetik/zachetik.cpp
UTF-8
4,529
3.046875
3
[]
no_license
// Munin.cpp : Defines the entry point for the console application. // #include <iostream> #include <string> #include <vector> #include <set> #include <algorithm> #include <bitset> #include <cmath> #include <fstream> using namespace std; typedef long double ld; const ld EPS = (ld)1e-9; const ld Pi = 3.14159265359; const ld INF = (ld)1e9; struct point { ld x, y; point() {} point(ld _x, ld _y) { x = _x; y = _y; } point operator+(point b) { return point(x + b.x, y + b.y); } point operator-(point b) { return point(x - b.x, y - b.y); } bool operator==(point b) { return abs(x - b.x) < EPS && abs(y - b.y) < EPS; } ld operator%(point b) { return x * b.y - y * b.x; } ld operator*(point b) { return x * b.x + y * b.y; } point median() { return point(x / 2, y / 2); } ld dist() { return sqrt(x * x + y * y); } point normal() { ld d = dist(); return point(x / d, y / d); } point operator-() { return point(-x, -y); } point operator*(ld mod) { return point(x * mod, y * mod); } }; struct line { ld a, b, c; line(ld _a, ld _b, ld _c) { a = _a; b = _b; c = _c; } line(point p, point q) { a = p.y - q.y; b = q.x - p.x; c = -a * p.x - b * p.y; } line() {} ld point_dist(point p) { return abs((p.x * a + p.y * b + c) / sqrt(a * a + b * b)); } ld point_dist_2(point p) { return abs((p.x * a + p.y * b + c) / (a * a + b * b)); } point normal_vector() { return point(a, b); } bool on_line(point p) { return abs(a * p.x + b * p.y + c) < EPS; } }; istream &operator >> (istream &is, point &p) { ld _x, _y; is >> _x >> _y; p = point(_x, _y); is.clear(); return is; } ostream &operator << (ostream &os, point &p) { os << p.x << " " << p.y; os.clear(); return os; } istream &operator >> (istream &is, line &ln) { ld _a, _b, _c; is >> _a >> _b >> _c; ln = line(_a, _b, _c); is.clear(); return is; } point lower; ld get_dist(point a, point b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } ld crossprod(point l, point m, point r) { point v1 = r - m; point v2 = l - m; return v1 % v2; } ld dotprod(point l, point m, point r) { point v1 = r - m; point v2 = l - m; return v1 * v2; } bool polar_deg_cmp(point a, point b) { if (abs(crossprod(a, lower, b)) < EPS) { return get_dist(a, lower) < get_dist(b, lower); } return crossprod(a, lower, b) < 0; } vector<point> convex_hull(vector<point> arr) { vector<int> preprocess; ld min_x = INF; ld min_y = INF; int min_ind = 0; for (int i = 0; i < arr.size(); ++i) { if (arr[i].x < min_x) { min_x = arr[i].x; min_ind = i; } if (arr[i].x == min_x) { if (arr[i].y < min_y) { min_y = arr[i].y; min_ind = i; } } } lower = arr[min_ind]; sort(arr.begin(), arr.end(), polar_deg_cmp); vector<point> res; res.push_back(arr[0]); int ind = 1; while (ind < arr.size()) { if (polar_deg_cmp(res[res.size() - 1], arr[ind])) { res.push_back(arr[ind]); ++ind; } else { res.pop_back(); } } return res; } bool linear_intersection(point x, point a, point b) { if (a.x > b.x) swap(a, b); return (x.x >= a.x && x.x <= b.x) && (x.y >= min(a.y, b.y) && x.y <= max(b.y, a.y)); } ld a, b, c; line ln; point s, f; point get_by_y(ld y) { ld x = -ln.c / ln.a - ln.b / ln.a * y; return point(x, y); } point get_by_x(ld x) { ld y = -ln.c / ln.b - ln.a / ln.b * x; return point(x, y); } ld get(point a, point b) { return abs(a.x - b.x) + abs(a.y - b.y); } signed main() { cout.precision(30); cin >> a >> b >> c; ln = line(a, b, c); cin >> s >> f; if (b == 0 || a == 0) { cout << get(s, f) << endl; } else { ld res = get(s, f); point v = point(a, b); v = v.normal(); if (ln.point_dist(s + v * (ld)1e15) - ln.point_dist(s - v * (ld)1e15) > EPS) { v = -v; } v = v * ln.point_dist(s); vector<point> p1; for (int d = -100; d <= 100; ++d) { p1.push_back(get_by_x((long long)v.x + d)); p1.push_back(get_by_y((long long)v.y + d)); } v = point(a, b); v = v.normal(); if (ln.point_dist(f + v * (ld)1e15) - ln.point_dist(f - v * (ld)1e15) > EPS) { v = -v; } v = v * ln.point_dist(f); vector<point> p2; for (int d = -100; d <= 100; ++d) { p2.push_back(get_by_x((long long)v.x + d)); p2.push_back(get_by_y((long long)v.y + d)); } for (point r : p1) { for (point g : p2) { res = min(res, get(s, r) + get(f, g) + (r - g).dist()); } } cout.precision(20); cout << res << endl; } return 0; }
true
c29645d369e83c35547dc89697ebbdd2e85b765f
C++
rlj1202/problemsolving
/baekjoon/1342/main.cpp
UTF-8
734
2.953125
3
[]
no_license
#include <cstdio> #include <cstring> using namespace std; char str[12]; bool check(char* s) { for (int i = 1; s[i] != 0; i++) if (s[i - 1] == s[i]) return false; return true; } void swap(char* a, char* b) { char temp = *a; *a = *b; *b = temp; } int perm(char* s) { if (*s == 0) { return check(str); } int result = 0; bool used[26]; memset(used, 0, sizeof(used)); for (int i = 0; s[i] != 0; i++) { if (used[s[i] - 'a']) continue; used[s[i] - 'a'] = true; swap(s, s + i); result += perm(s + 1); swap(s, s + i); } return result; } int main() { scanf("%s", str); printf("%d\n", perm(str)); return 0; }
true
837c7c09531cc5b0c7817f36194091ff8ec55894
C++
david20571015/Introduction-to-Computers-and-Programming
/hw4/2.cpp
UTF-8
181
2.703125
3
[]
no_license
#include<stdio.h> int main(void){ int n=1,sign=1; double ans=0; while(1.0/n>=1E-06){ ans+=(1.0/n)*sign; sign=-sign; n+=2; } printf("PI/4 = %lf",ans); return 0; }
true
c63f8dd6eda57ef2b96f385cd86c4aa944804386
C++
ChengSashankh/SudokuSolver
/Header.cpp
UTF-8
5,032
3.25
3
[]
no_license
#include<iomanip.h> #include<math.h> #include<stdio.h> void getpuzzle(int s[9][9],char *A) //gets the given values for the grid and set all other cells to 99 { for(int i=0;i<9;i++) //set all cells to 99. { for(int j=0;j<9;j++) { s[i][j]=99; } } int r,c,value,number; freopen(A,"r",stdin); //cout<<"How many cells do you want to fill?"; cin>>number; int count=0; while(count<number) { //cout<<"Enter from 1 to 9, in order the row, coloumn and value of the cell you want to fill."; cin>>r>>c>>value; s[r-1][c-1]=value; count++; } } void setu(int s[9][9][2]) //sets u to 9 { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(s[i][j][0]==99) s[i][j][1]=9; else s[i][j][1]=0; } } } int checkfill(int s[9][9][2]) //check if all are filled. return 1 if filled, else return zero. { int k=1; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(s[i][j][1]==1) //THis was u[i][j]==1 for some reason O.o. corrected. { k=0; break; } } } return k; } int chrowcol(int s[9][9][2],int r,int c,int val) { int flag=1; for(int i=0;i<9;i++) { if( ( (s[i][c][0]==val)&&(i!=r) )||( (s[r][i][0]==val)&&(i!=c) ) ) flag=0; } return flag; } int check3(int s[9][9][2],int r,int c,int val) { int i=r/3; int j=c/3; int lc1,lc2,lr1,lr2; int flag=1; /* if((s[r][c][0]!=99)&&(s[r][c][0]==val)) return(1); else if((s[r][c][0]!=99)&&(s[r][c][0]!=val)) return(0); */ if(i==0) { lc1=0; lc2=2; } if(i==1) { lc1=3; lc2=5; } if(i==2) { lc1=6; lc2=8; } if(j==0) { lr1=0; lr2=2; } if(j==1) { lr1=3; lr2=5; } if(j==2) { lr1=6; lr2=8; } for(int col=lc1;col<=lc2;col++) //not a mistake. Just goes coloumnwise. { for(int row=lr1;row<=lr2;row++) { if( (s[col][row][0]==val)&&( !( (col==r)&&(row==c) ) ) ) { flag=0; break; } } } return flag; } void unc(int s[9][9][2],int r,int c) //gets indices { //Why?? Starts here for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(s[i][j][0]!=99) { s[i][j][1]=0; } } } //Why?? Ends here if(s[r][c][0]==99) // filled boxes left untouched { s[r][c][1]=9; for(int value=1;value<=9;value++) { if((check3(s,r,c,value)==0)||(chrowcol(s,r,c,value)==0)) { s[r][c][1]--; } } } } int fillgrid(int s[9][9][2]) { int value=1,filled=0; for(int i=0;i<=8;i++) { for(int j=0;j<=8;j++) { if(s[i][j][1]==1) { for(value=1;value<=9;value++) { if((check3(s,i,j,value)==1)&&(chrowcol(s,i,j,value)==1)) { filled++; s[i][j][0]=value; s[i][j][1]=0; } } } } } return filled; } void printpuz(int s[9][9]) { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) if(s[i][j]==99) cout<<"-"<<" "; else cout<<s[i][j]<<" "; cout<<endl; } cout<<endl; } int detsolve(int su[9][9]) { int s[9][9][2]; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { s[i][j][0]=su[i][j]; } } setu(s); int r=0,c=0; int flags=1; //This is func. while(flags>0) { for(r=0;r<9;r++) //maps uncertainity for all cells. for(c=0;c<9;c++) unc(s,r,c); flags=fillgrid(s); /* for(r=0;r<9;r++) { for(c=0;c<9;c++) { if(s[r][c][0]==99) s[r][c][1]=9; else s[r][c][1]=0; } } */ // cout<<"I have filled "<<flags<<" points"<<endl; } for(i=0;i<9;i++) { for(int j=0;j<9;j++) { su[i][j]=s[i][j][0]; } } //I am the danger. int solution=1; for(r=0;r<9;r++) //maps uncertainity for all cells. for(c=0;c<9;c++) { unc(s,r,c); if(s[r][c][1]==0) solution=0; } return solution; } int checkifsol(int su[9][9]) { int s[9][9][2]; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { s[i][j][0]=su[i][j]; } } for(i=0;i<9;i++) { for(int j=0;j<9;j++) { if( (chrowcol(s,i,j,s[i][j][0])==0)||(check3(s,i,j,s[i][j][0])==0) ) return(0); } } return(1); } int mappos_first(int su[9][9],int r,int c,int pos[9]) { int s[9][9][2],count=0; int shazam=0; for(int i=0;i<9;i++) { pos[i]=-1; for(int j=0;j<9;j++) { s[i][j][0]=su[i][j]; } } for(int value=1;value<10;value++) { //sets from 1 only. Does not include the first plane. Notice that count++ comes before the set command. if((check3(s,r,c,value)==1)&&(chrowcol(s,r,c,value)==1)) { pos[count]=value; count++; shazam=1; } } return(shazam); } int isfilled(int s[9][9]) { int flag=1; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(s[i][j]==99) flag=0; } } return flag; } /* void main() { int s[9][9]; int poss[9]; getpuzzle(s); mappos_first(s,0,2,poss); for(int i=0;i<9;i++) { cout<<poss[i]<<endl; } printpuz(s); cout<<"The puzzle has been solved? :"<<checkifsol(s)<<endl; detsolve(s); printpuz(s); cout<<"The puzzle has been solved? :"<<checkifsol(s)<<endl; } */
true
2ebfe9d6cfbc6d6f7d1871d87d7880928e46a672
C++
drlongle/leetcode
/algorithms/problem_0469/solution.cpp
UTF-8
2,312
3
3
[]
no_license
/* 469. Convex Polygon Medium You are given an array of points on the X-Y plane points where points[i] = [xi, yi]. The points form a polygon when joined sequentially. Return true if this polygon is convex and false otherwise. You may assume the polygon formed by given points is always a simple polygon. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other. Example 1: Input: points = [[0,0],[0,5],[5,5],[5,0]] Output: true Example 2: Input: points = [[0,0],[0,10],[10,10],[10,0],[5,5]] Output: false Constraints: 3 <= points.length <= 10^4 points[i].length == 2 -10^4 <= xi, yi <= 10^4 All the given points are unique. */ #include <algorithm> #include <atomic> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <condition_variable> #include <functional> #include <future> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <memory> #include <numeric> #include <queue> #include <random> #include <regex> #include <set> #include <sstream> #include <stack> #include <string_view> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include "common/ListNode.h" #include "common/Node.h" #include "common/TreeNode.h" using namespace std; using ll = long long; using pi = pair<int, int>; using vi = vector<int>; using vii = vector<vector<int>>; using vl = vector<ll>; using vll = vector<vector<ll>>; class Solution { public: using ll = long long; ll product(vector<ll>& v1, vector<ll>& v2) { return v1[0] * v2[1] - v1[1] * v2[0]; } bool isConvex(vector<vector<int>>& points) { vector<vector<ll>> vect; int sz = points.size(); for (int i = 0; i < sz - 1; ++i) { vector<ll> v{points[i+1][0] - points[i][0], points[i+1][1] - points[i][1]}; vect.push_back(v); } vector<ll> v{points[0][0] - points[sz-1][0], points[0][1] - points[sz-1][1]}; vect.push_back(v); ll p = product(vect[sz-1], vect[0]); for (int i = 0; i < sz - 1; ++i) { if (product (vect[i], vect[i+1]) * p < 0) return false; } return true; } }; int main() { Solution sol; return 0; }
true
c77aff09002403f2fbce65684e13966dcd21dcc5
C++
ashleygwinnell/firecube
/Tools/SceneEditor/CollisionShapeWindow.cpp
UTF-8
5,263
2.546875
3
[ "MIT" ]
permissive
#include "CollisionShapeWindow.h" #include "Descriptors/CollisionShapeDescriptor.h" #include "Commands/CustomCommand.h" #include "EditorState.h" using namespace FireCube; CollisionShapeWindow::CollisionShapeWindow(FireCube::Engine *engine) : Object(engine) { } void CollisionShapeWindow::Render(EditorState *editorState, CollisionShapeDescriptor *descriptor) { const CollisionShapeType shapeTypes[] = { CollisionShapeType::BOX, CollisionShapeType::PLANE, CollisionShapeType::TRIANGLE_MESH, CollisionShapeType::SPHERE }; const char *shapeTypesStr[] = { "Box", "Plane", "Mesh", "Sphere" }; const char *selectedType; CollisionShapeType oldShapeType = descriptor->GetShapeType(); if (oldShapeType == CollisionShapeType::BOX) { selectedType = shapeTypesStr[0]; } else if (oldShapeType == CollisionShapeType::PLANE) { selectedType = shapeTypesStr[1]; } else if (oldShapeType == CollisionShapeType::TRIANGLE_MESH) { selectedType = shapeTypesStr[2]; } else if (oldShapeType == CollisionShapeType::SPHERE) { selectedType = shapeTypesStr[3]; } if (ImGui::BeginCombo("Type", selectedType)) { std::string oldMesh = descriptor->GetMeshFilename(); Plane oldPlane = descriptor->GetPlane(); BoundingBox oldBoundingBox = descriptor->GetBox(); float oldRadius = descriptor->GetRadius(); for (int i = 0; i < IM_ARRAYSIZE(shapeTypesStr); i++) { bool isSelected = (descriptor->GetShapeType() == shapeTypes[i]); if (ImGui::Selectable(shapeTypesStr[i], isSelected)) { CollisionShapeType newShapeType = shapeTypes[i]; auto command = new CustomCommand(editorState, "Change Shape Type", [descriptor, newShapeType, oldPlane, oldBoundingBox, oldMesh, oldRadius, this]() { switch (newShapeType) { case CollisionShapeType::TRIANGLE_MESH: descriptor->SetMesh(oldMesh, engine); break; case CollisionShapeType::PLANE: descriptor->SetPlane(oldPlane); break; case CollisionShapeType::BOX: descriptor->SetBox(oldBoundingBox); break; case CollisionShapeType::SPHERE: descriptor->SetSphere(oldRadius); break; default: break; } descriptor->componentChanged(nullptr); }, [descriptor, oldShapeType, oldPlane, oldBoundingBox, oldMesh, oldRadius, this]() { switch (oldShapeType) { case CollisionShapeType::TRIANGLE_MESH: descriptor->SetMesh(oldMesh, engine); break; case CollisionShapeType::PLANE: descriptor->SetPlane(oldPlane); break; case CollisionShapeType::BOX: descriptor->SetBox(oldBoundingBox); break; case CollisionShapeType::SPHERE: descriptor->SetSphere(oldRadius); break; default: break; } descriptor->componentChanged(nullptr); }); editorState->ExecuteCommand(command); } if (isSelected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } triggerCheckBox.Render("Trigger", editorState, "Change Trigger", [descriptor]() { return descriptor->IsTrigger(); }, [descriptor](bool newValue) { descriptor->SetIsTrigger(newValue); }); if (descriptor->GetShapeType() == CollisionShapeType::BOX) { boxMinInput.Render("Min", editorState, "Change Box", [descriptor]() { return descriptor->GetBox().GetMin(); }, [descriptor](vec3 newValue) { descriptor->SetBox(BoundingBox(newValue, descriptor->GetBox().GetMax())); }); boxMaxInput.Render("Max", editorState, "Change Box", [descriptor]() { return descriptor->GetBox().GetMax(); }, [descriptor](vec3 newValue) { descriptor->SetBox(BoundingBox(descriptor->GetBox().GetMin(), newValue)); }); } else if (descriptor->GetShapeType() == CollisionShapeType::PLANE) { planeInput.Render("Plane", editorState, "Change Plane", [descriptor]() { return vec4(descriptor->GetPlane().GetNormal(), descriptor->GetPlane().GetDistance()); }, [descriptor](vec4 newValue) { Plane plane(vec3(newValue.x, newValue.y, newValue.z), newValue.w); descriptor->SetPlane(plane); }); } else if (descriptor->GetShapeType() == CollisionShapeType::TRIANGLE_MESH) { std::string selectedPath; std::string meshFileName = descriptor->GetMeshFilename(); ImGui::InputText("", &meshFileName[0], meshFileName.size() + 1, ImGuiInputTextFlags_ReadOnly); ImGui::SameLine(); if (ImGui::Button("...")) { ImGuiHelpers::ShowAssetSelectionPopup("Select Mesh"); } ImGui::SameLine(); ImGui::Text("Mesh"); if (ImGuiHelpers::AssetSelectionPopup("Select Mesh", AssetType::MESH, selectedPath)) { std::string oldMeshFileName = descriptor->GetMeshFilename(); auto command = new CustomCommand(editorState, "Change Mesh", [descriptor, selectedPath, this]() { descriptor->SetMesh(selectedPath, engine); descriptor->componentChanged(nullptr); }, [descriptor, oldMeshFileName, this]() { descriptor->SetMesh(oldMeshFileName, engine); descriptor->componentChanged(nullptr); }); editorState->ExecuteCommand(command); } } else if (descriptor->GetShapeType() == CollisionShapeType::SPHERE) { sphereRadiusInput.Render("Radius", editorState, "Change Radius", [descriptor]() { return descriptor->GetRadius(); }, [descriptor](float newValue) { descriptor->SetSphere(newValue); }); } }
true
169e942461c53116c18d4b55698a12304e0dc069
C++
dennyown/CrazyTanks.v.1
/CrazyTanks.v.1/Tank.h
UTF-8
294
2.609375
3
[]
no_license
#ifndef TANK_H #define TANK_H #include "Point.h" #include "Bullet.h" #include "Player.h" class Tank: public Player { public: Tank(); Tank( Point position, char sign, int health ); ~Tank(); void action( Tank& tank, Bullet& bullet ); private: void move( Tank& tank ); }; #endif // TANK_H
true
8f0be48d8c9b3d22b1dac48ae59a87885f12c93f
C++
543877815/algorithm
/leetcode周赛/2351. First Letter to Appear Twice.cpp
GB18030
344
3.03125
3
[]
no_license
// ϣ // ʱ临ӶȣO(n) // ռ临ӶȣO(n) class Solution { public: char repeatedCharacter(string s) { int n = s.size(); unordered_map<char, int> mymap; for (int i = 0; i < n; i++) { mymap[s[i]]++; if (mymap[s[i]] == 2) return s[i]; } return -1; } };
true
7cf48db38c53ac32dbf3eb7e15f7ce261496b97b
C++
chenminhua/math
/matrix/multiply/matmul_eigen/main.cpp
UTF-8
713
2.734375
3
[]
no_license
/** * @ Author: Minhua Chen * @ Create Time: 2019-08-24 11:00:32 * @ Modified by: Minhua Chen * @ Modified time: 2019-08-24 15:00:57 * @ Description: g++ -I eigen -O3 main.cpp */ #include <iostream> #include <Eigen/Dense> using namespace::Eigen; #define DEFAULT_SIZE_M 5 typedef Eigen::Matrix<int, Dynamic, Dynamic> IntMatrix; int main(int argc, char* argv[]) { int m_size; if (argc > 1) { m_size = atoi(argv[1]); } else { m_size = DEFAULT_SIZE_M; } IntMatrix mat1(m_size,m_size); IntMatrix mat2(m_size,m_size); IntMatrix result(m_size,m_size); mat1.setRandom(); mat2.setRandom(); result = mat1 * mat2; std::cout << "finished" << std::endl; }
true
e223f6c249adb83bbd0c9ffeaf543a372446fffb
C++
HaiZeizhouyuan/HZOJ
/596.cpp
UTF-8
805
2.953125
3
[]
no_license
/************************************************************************* > File Name: 596.cpp > Author: > Mail: > Created Time: Fri Jul 24 21:31:33 2020 ************************************************************************/ #include<iostream> #include <algorithm> using namespace std; #define max_n 5000 string a[max_n + 5]; bool cmp(string a, string b) { int size_a = a.size(); int size_b = b.size(); if (size_a < size_b) return 1; if (size_a > size_b) return 0; for (int i = 0; i < size_a; i++) { if (a[i] > b[i]) return 0; if (a[i] < b[i]) return 1; } return 1; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n, cmp ); for (int i = 0; i < n; i++) cout << a[i] << endl; return 0; }
true
ad313b0e170f89e9a8d3908a65cac35e0d055d0b
C++
xSeanliux/CompetitiveProgramming
/AtCoder/ARC_087/pC.cpp
UTF-8
249
2.6875
3
[]
no_license
#include <iostream> #include <map> using namespace std; int N, x; map<int, int> frq; int main(){ cin >> N; while(N--){ cin >> x; frq[x]++; } int ans = 0; for(auto [a, b] : frq){ ans += (a <= b ? b - a : b); } cout << ans << endl; }
true
b126389c46cb9ae6712330f29afee35162906573
C++
ygagneja/CS335-Compiler
/src/3ac.cpp
UTF-8
10,325
2.625
3
[]
no_license
#include "3ac.h" #include "type_check.h" long long counter = 0; vector<quad> code_arr; string new_symbol(){ counter++; string new_sym = "_tmp_" + to_string(counter); return new_sym; } qid newtmp(string type, unsigned long long level, unsigned long long* level_id){ string sym = new_symbol(); return (qid)insert_entry(sym, type, get_size(type, level, level_id), 0, 1, level, level_id[level]); } qid newstring(string type, unsigned long long size, unsigned long long level, unsigned long long* level_id){ string sym = new_symbol(); return (qid)insert_entry(sym, type, size, 0, 1, level, level_id[level]); } int emit(string op, qid arg1, qid arg2, qid res){ quad tmp; tmp.op = op; tmp.arg1 = arg1; tmp.arg2 = arg2; tmp.res = res; code_arr.push_back(tmp); return code_arr.size()-1; } int nextinstr(){ return code_arr.size(); } char* merge(char* l1, char* l2){ if (!l1 && !l2) return NULL; else if (l1 && !l2){ return l1; } else if (!l1 && l2){ return l2; } else { string ret = string(l1) + "," + string(l2); char* str = new char[ret.size()+1]; strcpy(str, ret.c_str()); return str; } } char* insert(char* li, int tmp){ if (li == NULL){ string str = to_string(tmp); li = new char[str.size()+1]; strcpy(li, str.c_str()); return li; } else { string str(li); str += "," + to_string(tmp); free(li); li = new char[str.size()+1]; strcpy(li, str.c_str()); return li; } } char* copy(char* li){ if (li == NULL) return NULL; string str(li); char* ret = new char[str.size()+1]; strcpy(ret, str.c_str()); return ret; } void backpatch(char* li, int tmp){ if (li == NULL) return; string str(li); string delim = ","; size_t f = 1; while (f != string::npos){ f = str.find_first_of(delim); string t = str.substr(0, f); code_arr[stoi(t)].goto_label = tmp; if (f == string::npos) break; else str = str.substr(f+1); } } void patch_constant(string constant, int addr){ code_arr[addr].constant = string(constant); } void patch_caselist(char* li, qid arg2){ if (li == NULL) return; string str(li); string delim = ","; size_t f = 1; while (f != string::npos){ f = str.find_first_of(delim); string t = str.substr(0, f); code_arr[stoi(t)].arg2 = arg2; if (f == string::npos) break; else str = str.substr(f+1); } } qid emit_assignment(string str1, string str2, qid place2, unsigned long long level, unsigned long long* level_id, int line){ if (str1 == str2){ return place2; } if ((is_type_int(str1) || is_type_float(str1) || is_type_char(str1) || is_type_bool(str1)) && (is_type_int(str2) || is_type_float(str2) || is_type_char(str2) || is_type_bool(str2))){ // inttofloat inttobool inttochar, floattoint floattochar floattobool, chartofloat chartoint chartobool, booltofloat booltoint booltochar if (is_type_int(str2)){ if (is_type_float(str1)){ qid tmp = newtmp(str1, level, level_id); emit("inttofloat", NULL, place2, tmp); return tmp; } else if (is_type_bool(str1)){ qid tmp = newtmp(str1, level, level_id); emit("inttobool", NULL, place2, tmp); return tmp; } else if (is_type_char(str1)){ qid tmp = newtmp(str1, level, level_id); emit("inttochar", NULL, place2, tmp); return tmp; } } else if (is_type_float(str2)){ if (is_type_int(str1)){ qid tmp = newtmp(str1, level, level_id); emit("floattoint", NULL, place2, tmp); return tmp; } else if (is_type_bool(str1)){ qid tmp = newtmp(str1, level, level_id); emit("floattobool", NULL, place2, tmp); return tmp; } else if (is_type_char(str1)){ qid tmp = newtmp(str1, level, level_id); emit("floattochar", NULL, place2, tmp); fprintf(stderr, "%d |\t Warning : Converting float to char\n", line); return tmp; } } else if (is_type_bool(str2)){ if (is_type_float(str1)){ qid tmp = newtmp(str1, level, level_id); emit("booltofloat", NULL, place2, tmp); fprintf(stderr, "%d |\t Warning : Converting bool to float\n", line); return tmp; } else if (is_type_int(str1)){ qid tmp = newtmp(str1, level, level_id); emit("booltoint", NULL, place2, tmp); return tmp; } else if (is_type_char(str1)){ qid tmp = newtmp(str1, level, level_id); emit("booltochar", NULL, place2, tmp); fprintf(stderr, "%d |\t Warning : Converting bool to char\n", line); return tmp; } } else if (is_type_char(str2)){ if (is_type_float(str1)){ qid tmp = newtmp(str1, level, level_id); emit("chartofloat", NULL, place2, tmp); fprintf(stderr, "%d |\t Warning : Converting char to float\n", line); return tmp; } else if (is_type_bool(str1)){ qid tmp = newtmp(str1, level, level_id); emit("chartobool", NULL, place2, tmp); fprintf(stderr, "%d |\t Warning : Converting char to bool\n", line); return tmp; } else if (is_type_int(str1)){ qid tmp = newtmp(str1, level, level_id); emit("chartoint", NULL, place2, tmp); return tmp; } } } else if ((is_type_ptr(str1) && is_type_int(str2)) || (is_type_ptr(str2) && is_type_int(str1)) || is_type_ptr(str1) && is_type_ptr(str2)){ qid tmp = newtmp(str1, level, level_id); emit("=", NULL, place2, tmp); return tmp; } } void emit_assignment_multi(string op, string str1, string str2, qid place1, qid place2, qid address1, unsigned long long level, unsigned long long* level_id, int line){ if (op == "*=" || op == "/=" || op == "%="){ op = op.substr(0, 1); string type = mul_type(str1, str2, op[0]); qid p1 = emit_assignment(type, str1, place1, level, level_id, line); qid p2 = emit_assignment(type, str2, place2, level, level_id, line); qid t = newtmp(type, level, level_id); emit(op+type, p1, p2, t); qid f = emit_assignment(str1, type, t, level, level_id, line); if (address1) emit("* =", NULL, f, address1); else emit("=", NULL, f, place1); } else if (op == "+=" || op == "-="){ op = op.substr(0, 1); string type = add_type(str1, str2); if (type == "int" || type == "float"){ qid p1 = emit_assignment(type, str1, place1, level, level_id, line); qid p2 = emit_assignment(type, str2, place2, level, level_id, line); qid t = newtmp(type, level, level_id); emit(op+type, p1, p2, t); qid f = emit_assignment(str1, type, t, level, level_id, line); if (address1) emit("* =", NULL, f, address1); else emit("=", NULL, f, place1); } else { if (is_type_int(str1)){ qid res = newtmp(str1, level, level_id); qid tmp = newtmp(str1, level, level_id); string tp(str2); tp.pop_back(); int k = emit("*int", place1, NULL, tmp); patch_constant(to_string(get_size(tp, level, level_id)), k); emit(op+"ptr", tmp, place2, res); if (address1) emit("* =", NULL, res, address1); else emit("=", NULL, res, place1); } else { qid res = newtmp(str1, level, level_id); qid tmp = newtmp(str2, level, level_id); string tp(str1); tp.pop_back(); int k = emit("*int", place2, NULL, tmp); patch_constant(to_string(get_size(tp, level, level_id)), k); emit(op+"ptr", place1, tmp, res); if (address1) emit("* =", NULL, res, address1); else emit("=", NULL, res, place1); } } } else if (op == ">>=" || op == "<<="){ op = op.substr(0, 2); string type = shift_type(str1, str2); qid p1 = emit_assignment(type, str1, place1, level, level_id, line); qid p2 = emit_assignment(type, str2, place2, level, level_id, line); qid t = newtmp(type, level, level_id); emit(op, p1, p2, t); qid f = emit_assignment(str1, type, t, level, level_id, line); if (address1) emit("* =", NULL, f, address1); else emit("=", NULL, f, place1); } else if (op == "&=" || op == "^=" || op == "|="){ op = op.substr(0, 1); string type = bit_type(str1, str2); qid p1 = emit_assignment(type, str1, place1, level, level_id, line); qid p2 = emit_assignment(type, str2, place2, level, level_id, line); qid t = newtmp(type, level, level_id); emit(op, p1, p2, t); qid f = emit_assignment(str1, type, t, level, level_id, line); if (address1) emit("* =", NULL, f, address1); else emit("=", NULL, f, place1); } } void dump_3ac(){ ofstream out_file("./out/out.3ac"); int i = 0; for (quad q : code_arr){ out_file << i << ".\t"; if (q.res){ out_file << q.res->sym_name; } else if (q.op == "GOTO" || q.op == "GOTO IF"){ out_file << q.goto_label; } out_file << " <- "; if (q.arg1){ out_file << q.arg1->sym_name; } out_file << " " << q.op << " "; if (q.arg2){ out_file << q.arg2->sym_name; } else { out_file << q.constant; } out_file << endl; i++; } }
true
0984f5fd9700d4b9a1b8152c7f9b9e32dcd426a8
C++
Rulygl/C
/pag_124/Bucles_ej_2_pag_124_.cpp
UTF-8
238
3
3
[]
no_license
#include <iostream> using namespace std; int main(){ int n = 26; cout<<" Estos son los numeros pares menores de 26 "<< endl ; while((n <= 26)&&(n >=10)&&(n%2==0 )){ cout << n << endl; n = n-2; } return 0; }
true
53c3581bf11c5f103d0c2586e5b6881782c8ad3d
C++
hungntth/T2004E_C
/assignment5/4.cpp
UTF-8
287
2.5625
3
[]
no_license
#include <stdio.h> int main(){ int a,b,c,d; printf("Nhap so a: "); scanf("%d",&a); printf("Nhap so b: "); scanf("%d",&b); if(a*b==0){ printf("Sai so"); }else{ for(c = 1; c <= a || c <= b; c++) { if( a%c == 0 && b%c == 0 ) d = c; } printf("USCLN = %d", d); } }
true
e0f74ce643726739c061637dc15707bf6ae65709
C++
Robin-P/indie-studio
/include/Socket.hpp
UTF-8
1,431
2.59375
3
[]
no_license
// // EPITECH PROJECT, 2018 // cpp_indie_studio // File description: // Socket // #pragma once #include <unistd.h> #include <netdb.h> #include <arpa/inet.h> #include <cstring> #include <iostream> #include <vector> namespace Indie { enum PowerUpType { FIRST_UP = 3, SPEED_UP = 4, BOMB_UP = 5, FIRE_UP = 6, WALLPASS_UP = 7, LAST_UP = 8//don't use it }; enum ObjectsType { PLAYER, GAMEINFOS, MAP, BOMB }; enum ObjectsEvents { APPEAR, DEAD, MOVE, START, MESSAGE, CREATEBOMB, DESTROYBOMB, DESTROYBLOCK, CREATEBLOCK, TAKEBONUS, EV_READY, EV_UNREADY, SUICIDE, STAND, LEAVE, INFO, EXIT, NICK }; class Socket { public: enum TypeSocket { SERVER, CLIENT }; Socket() {} ~Socket() {} Socket(const int, const std::string &, TypeSocket); Socket(const int, const in_addr_t &, TypeSocket); int getPort() const { return _port; } std::string getAddr() const { return _addr; } in_addr_t getInetAddr() const { return _inetAddr; } TypeSocket getType() const { return _type; } int getFd() const { return _fd; } void sendInfos(ObjectsType, ObjectsEvents, const std::string &); bool isSocketWritten(); std::vector<std::string> readSocket(); void closeSocket() { close(_fd); } private: int _port; std::string _addr; in_addr_t _inetAddr; TypeSocket _type; int _fd; struct sockaddr_in _sIn; fd_set _fdRead; }; }
true
f502e31389241d04475e035e3a9a834e27ae138f
C++
zhiqianglife/Leetcode-Practice
/DP/303. Range Sum Query - Immutable.cpp
UTF-8
1,136
4.09375
4
[]
no_license
/* 给定一个整数数组  nums,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。 示例: 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 说明: 你可以假设数组不可变。 会多次调用 sumRange 方法。 */ /*class NumArray { public: vector<int> m_nums; NumArray(vector<int>& nums) { m_nums = nums; } int sumRange(int i, int j) { int res = 0; for (int k = i; k <= j; ++k) { res += m_nums[k]; } return res; } };*/ class NumArray { public: vector<int> sum; NumArray(vector<int>& nums) { sum.resize(nums.size() + 1); sum[0] = 0; for (int i = 0; i < nums.size(); ++i) { sum[i + 1] = sum[i] + nums[i]; } } int sumRange(int i, int j) { int res = 0; return sum[j + 1] - sum[i]; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(i,j); */
true
cf0d0ccbbe8841093f0b44e5a1bd36290faf0a5a
C++
dandanjoseph/Regular-Pentagon
/RegularPentagon.cpp
UTF-8
861
3.546875
4
[]
no_license
/* * File: RegularPentagon.cpp * Author: Joseph Dandan * * This program calculates the area and perimeter of a regular pentagon */ #include "RegularPentagon.h" #include <cmath> RegularPentagon::RegularPentagon(double sideArg, string name) : GeometricObject (name) //this method takes in a side argument and can take in a string name as well { side = sideArg; } /*This is a getter for the area*/ double RegularPentagon::getArea(){ return (0.25) * sqrt (5* ( 5 + 2* sqrt (5) ))*side*side; //we calculate the area with the formula that is being returned for the area } /*This is a getter for the perimeter*/ double RegularPentagon::getPerimeter() { return 5 * side; //we calculate the perimeter with the side } /*This is a getter for the side*/ double RegularPentagon::getSide() { return side; //we get the side and return the side }
true
bcd8f36a71e106fa24ff76e1e7a8a02797856fb4
C++
rajaniket/Data-Structures-and-algorithms
/coding blocks/Arrays 2.0/solving a string challenge.cpp
UTF-8
2,078
3.84375
4
[]
no_license
//order string //question link => https://www.hackerrank.com/contests/morgan-stanley-codeathon-2017/challenges/shell-sort-command #include<iostream> #include<string> #include<cstring> #include"algorithm" using namespace std; //extract string will give Kth number using string tokenizer string extract(string a,int k) { char *p=strtok((char *)a.c_str()," "); while(k>1){ p=strtok(NULL," "); k--; } return (string)p; } // for numeric type comperater => 13<23 bool numeric(pair<string,string>s1,pair<string,string>s2){ int key1=stoi(s1.second); int key2=stoi(s2.second); return key1<key2; } // for lexicographic type comperator => 13>23 ,1 comes before 2 bool lexicographic(pair<string,string>s1,pair<string,string>s2){ return s1.second<s2.second; } int main(){ int n; cin>>n; cin.ignore(); string a[n]; for(int i=0;i<n;i++){ getline(cin,a[i]); } int key; string reversal,ordering; cin>>key; cin.ignore(); cin>>reversal>>ordering; pair<string,string>strpair[n]; // The pair container is a simple container defined in <utility> header consisting of two data elements or objects. for(int i=0;i<n;i++){ strpair[i].first=a[i]; //The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second). strpair[i].second=extract(a[i],key); } //ordering if(ordering=="numeric"){ sort(strpair,strpair+n,numeric); //sorting in numeric order 11<22 } else sort(strpair,strpair+n,lexicographic); // sorting in lexicographic order 11>22 ,1 comes before 2 //reversing the strpair if(reversal=="true"){ for(int i=0;i<n/2;i++) swap(strpair[i],strpair[n-i-1]); //here we can't use sort because we are reversing result and it may be lexicographical or numerical so it's easy to swap } for(int i=0;i<n;i++){ cout<<strpair[i].first<<endl; // it will print first element which is containing sorted string a[i] } }
true
2815f394820da260756d10f59cb594d7ef9b7fd2
C++
seifgamal/Social_ConsoleApp
/DateTime.h
UTF-8
1,045
3.03125
3
[]
no_license
#ifndef SOCIAL_DATETIME_H #define SOCIAL_DATETIME_H #include <bits/stdc++.h> using namespace std; class DateTime { private: int day, month, year; int second, minute, hour; string dayName, monthName; bool validDate(int day, int month, int year); bool validDate(string &DDMMYY); void setCurrent(); public: DateTime(); static string whatDay(int Y, int M, int D); // formula string timePassed(); string getDate(); // dayName DD/MM/YY void setDate(int day, int month, int year); void setDate(string DDMMYY); // DD/MM/YYYY format string getTime(); void setTime(int second, int minute, int hour); string getDayName(); void setDayName(string); int getDayNumber(); void setDayNumber(int); int getMonth(); void setMonth(int); int getYear(); void setYear(int); int getSecond(); void setSecond(int); int getMinute(); void setMinute(int); int getHour(); void setHour(int); friend ostream &operator<<(ostream &out, const DateTime &date); }; #endif //SOCIAL_DATETIME_H
true
8d6692a1dc843152edb87c018902cdabd3796829
C++
ryecao/MiniSQL
/index_info.h
UTF-8
1,155
2.59375
3
[]
no_license
// @copyright (c) 2014 sodabeta, ryecao // @license: MIT // @author(s): sodabeta/rxzxx0723@gmail.com, ryecao/ryecao@gmail.com // created by sodabeta , Oct. , 2014 // // MiniSQL // A course project for Database System Design, Fall 2014 @Zhejiang Univ. // // @file:index_info.h // @brief: used to store index information. // // please compile with -std=c++11 #ifndef INDEX_INFO_ #define INDEX_INFO_ #include <string> class IndexInfo { public: IndexInfo(){}; IndexInfo(const std::string &index_name, const std::string &table_name, const std::string &attribute_name) { name_ = index_name; table_name_ = table_name; attribute_name_ = attribute_name; }; std::string name() const{ return name_; }; std::string table_name() const{ return table_name_; }; std::string attribute_name() const{ return attribute_name_; }; void set_name(const std::string &name){ name_ = name; }; void set_table_name(const std::string &table_name){ table_name_ = table_name; }; void set_attribute_name(const std::string &attribute_name){ attribute_name_ = attribute_name; }; private: std::string name_; std::string table_name_; std::string attribute_name_; }; #endif
true
38aa6f7bfad25046f27075d70748c6f8868ddf89
C++
cantina-lib/cantina_common
/inline/cant/physics/PhysicalShape.inl
UTF-8
3,123
2.78125
3
[]
no_license
#ifndef CANTINA_PHYSICS_PHYSICALSHAPE_INL #define CANTINA_PHYSICS_PHYSICALSHAPE_INL #pragma once #include <c3ga/Mvec.hpp> #include <c3ga/c3gaTools.hpp> #include <cant/common/macro.hpp> CANTINA_PHYSICS_NAMESPACE_BEGIN template <size_u dim, typename T> PhysicalShape<dim, T>::PhysicalShape(DistanceFunctor func, T radius) : m_func(std::move(func)), m_radius(radius) { } template <size_u dim, typename T> PhysicalShape<dim, T>::~PhysicalShape() = default; template <size_u dim, typename T> CANT_INLINE T PhysicalShape<dim, T>::getRadius() const { return m_radius; } template <size_u dim, typename T> Optional<typename PhysicalShape<dim, T>::Intersection> PhysicalShape<dim, T>::getIntersection(ShPtr<PhysicalShape> const & other, Position const & thisCentre, Position const & otherCentre) const { static_assert(dim == 3, "Not so generic now, are we?"); typedef c3ga::Mvec<T> MultiVector; // In 3D. static auto const conformMultiVectorToVector = [](MultiVector const & mv) -> Vector { return { mv[c3ga::E1], mv[c3ga::E2], mv[c3ga::E3] }; }; // make conform spheres from the centres and the radius of the shape. // we can easily do that by first making dual spheres: // S* = u_c - (r ** 2)/2 * e_infinity // Actually, we need to intersect after that, // so we'll keep the dual spheres. MultiVector const thisDualSphere = c3ga::dualSphere<T>( thisCentre.template get<0>(), thisCentre.template get<1>(), thisCentre.template get<2>(), this->m_radius); MultiVector const otherDualSphere = c3ga::dualSphere<T>( otherCentre.template get<0>(), otherCentre.template get<1>(), otherCentre.template get<2>(), other->m_radius); // compute the intersection multi-vector. // could be a sphere MultiVector const contact = thisDualSphere ^ otherDualSphere; // check whether the two spheres are intersecting, // That is, whether the contact point is 'real'. // It should be a circle, tangent bivector or an imaginary circle. // In any case, it can be checked by computing: // (contact / R . e_infinity) ** 2. // if it's strictly positive, the two spheres are strictly in each other, // if it's null, the spheres are touching, // if it's negative, they are not intersecting. T contactRadius; MultiVector contactCentre; MultiVector contactDirection; c3ga::extractDualCircle(contact, contactRadius, contactCentre, contactDirection); if (contactRadius < static_cast<T>(0.0)) { // no intersection! return Optional<Intersection>(); } Intersection intersection; // The direction of the dual surface gives us the opposite of the normal! intersection.normal = - conformMultiVectorToVector(contactDirection); intersection.centre = conformMultiVectorToVector(contactCentre); intersection.radius = contactRadius; return intersection; } CANTINA_PHYSICS_NAMESPACE_END #include <cant/common/undef_macro.hpp> #endif // CANTINA_PHYSICS_PHYSICALSHAPE_INL
true
8494aa7e4c027e1c42f4d8bbd77ba5670ce12634
C++
Polynominal/Lucy3D
/include/Lucia/Collider/Manager.h
UTF-8
3,490
2.546875
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
#ifndef MIKUS_LUCIA_COLLIDER_MANAGER_H #define MIKUS_LUCIA_COLLIDER_MANAGER_H #include <Lucia/Collider/Collider.h> #include <Lucia/Collider/Tools.h> // matrix<uint> and inf vector; #include <Lucia/Collider/Algorithm/Octtree.h> namespace Lucia { class Collider::Manager { public: friend class Shape; Manager(); //set void setPrecision(float Precision){precision = Precision;}; void setChanged(bool c); //get float getPrecision(){return precision;}; // when new shape is added it does not cause a collision response, only if its moved! void addShape(std::shared_ptr<Shape>); void removeShape(std::shared_ptr<Shape>); void moveShape(std::shared_ptr<Shape>); void update(); void addGhost(std::shared_ptr<Shape> A,Vertex dim); void scanCollisions(std::vector<std::shared_ptr<Shape>> Shapes); Vertex incrementPos(float x,float y,float z); // std::shared_ptr<Shape> addBox(float x,float y,float z,float w,float h,float d); std::shared_ptr<Shape> addBox(Vertex Center,Vertex Dimensions){return addBox(Center.x,Center.y,Center.z, Dimensions.x,Dimensions.y,Dimensions.z);}; std::shared_ptr<Polygon> addPolygon(std::vector<Vertex>Points); std::shared_ptr<Point> addPoint(Vertex Center); std::shared_ptr<Sphere> addSphere(Vertex Center, float radius); std::shared_ptr<Ray> addRay(Vertex A,Vertex B); std::pair<float,float> getDepthLimits(){return Broadphase.getDepthLimits();}; void cast(Vertex A,Vertex B,std::function <void(Shape *B)> collide,bool infinite_depth=false) {Broadphase.rayCast(A,B,collide,infinite_depth);}; virtual ~Manager(); // use basic construction buffers eg box and pass a model matrix for [position rotation and scale] // DATA = 1: Position 2: Rotation 3: Scale // functions for drawing stuff, eg wrappers, should be enough to provide drawing capabilities. std::function <int(std::vector<Vertex>)> CreatePolygon = [](std::vector<Vertex>Points){return -1;}; // returns id of the specific shape std::function <void(int)>DeletePolygon = [](int){}; std::function <void()>PreDraw = [](){}; std::function <void(Matrix<4>,Vertex)> DrawBox = [](Matrix<4> Data,Vertex Color=Vertex(1.0,0.0,0.0)){}; std::function <void(Matrix<4>,Vertex)> DrawPoint = [](Matrix<4> Data,Vertex Color=Vertex(1.0,0.0,0.0)){}; std::function <void(Matrix<4>,Vertex)> DrawSphere = [](Matrix<4> Data,Vertex Color=Vertex(1.0,0.0,0.0)){}; std::function <void(Vertex,Vertex,Vertex)> DrawRay = [](Vertex A,Vertex B,Vertex Color=Vertex(1.0,0.0,0.0)){}; // id is the id returned from Create Polygon std::function <void(Matrix<4>,int id,Vertex)> DrawPolygon = [](Matrix<4> Data,int id,Vertex Color=Vertex(1.0,0.0,0.0)){}; // fn after draw. std::function <void()>PostDraw = [](){}; void drawChunks(bool blocks); // collision functions: std::function <void(Shape*,Shape*)> OnCollision = [](Shape *A,Shape *B){}; std::function <void(Shape*,Shape*)> OnRelease = [](Shape *A,Shape *B){}; Algorithm::Octtree Broadphase = Algorithm::Octtree(); private: float precision = 0.01f; }; } #endif // COLLIDER_MANAGER_H
true
6927b508440c5115934d299dcd39b48107b7f965
C++
gengyouchen/atcoder
/beginner-contest-141/e-who-says-a-pun/binary-search-solution.cpp
UTF-8
1,468
3.28125
3
[]
no_license
#include <iostream> #include <string> #include <unordered_map> using namespace std; using LL = long long; #define MOD 1000000007 class RollingHash { private: LL mod(LL x) { return (x % MOD + MOD) % MOD; } LL h = 0, w = 0; public: template <class I> RollingHash(I first, I last) { for (auto it = first; it != last; ++it) h = mod(h * 256 + *it), w = w ? mod(w * 256) : 1; } void roll(char L, char R) { h = mod((h - w * L) * 256 + R); } operator int() const { return h; } }; class Solution { private: template <class F> int lowestTrue(int low, int high, F cond) { while (low < high) { const int mid = low + (high - low) / 2; if (cond(mid)) high = mid; else low = mid + 1; } return low; } public: /* time: O(n*log(n)), space: O(n), where n = |S| */ int whoSaysAPun(const string& S) { const int n = S.size(); auto cond = [&](int len) { unordered_map<int, int> h; RollingHash curr(S.begin(), S.begin() + len); for (int L = 0, R = len - 1; R < n; ++L, ++R) { const auto it = h.find(curr); if (it == h.end()) h[curr] = L; else if (L - it->second >= len && !S.compare(it->second, len, S, L, len)) return false; /* found */ if (R != n - 1) curr.roll(S[L], S[R + 1]); } return true; /* not found */ }; return lowestTrue(1, n, cond) - 1; } }; int main() { int n; cin >> n; string S; cin >> S; Solution sol; int ans = sol.whoSaysAPun(S); cout << ans << endl; return 0; }
true
07c6fc51849298797791c61738ee081d9cf6abd1
C++
LeFou-k/RTRenderer
/include/hittable_pdf.h
UTF-8
621
2.578125
3
[]
no_license
// // Created by VRLAB on 2020/12/6. // #ifndef HITTABLE_PDF_H #define HITTABLE_PDF_H #include "pdf.h" #include "hittable.h" class hittable_pdf : public pdf{ public: //origin is the not the hittable point, but the Ray origin point hittable_pdf(shared_ptr<hittable> p, const point3& origin): ptr(p), o(origin){} virtual double value(const vec3 &direction) const override{ return ptr->pdf_value(o, direction); } virtual vec3 generate() const override{ return ptr->random(o); } private: point3 o; shared_ptr<hittable> ptr; }; #endif //RAYTRACINGTHENEXTWEEK_HITTABLE_PDF_H
true
3eeceb457d20695e0a5b8af9f05f2c98bbb9a732
C++
remerson/uva
/solutions/10205-StackEmUp/generator.cpp
UTF-8
945
2.6875
3
[]
no_license
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <vector> #include <iostream> #ifndef ONLINE_JUDGE #define DEBUG(X) { X; } #else #define DEBUG(X) #endif using namespace std; const int MAX_N = 100; const int MAX_C = 52; int main(int argc, char **argv) { srand(unsigned(time(0))); const int t = atoi(argv[1]); cout << t << endl << endl; for(int i = 0; i < t; ++i) { const int n = rand() % 100; cout << n << endl; for(int j = 0; j < n; ++j) { vector<int> v; for(int k = 1; k <= MAX_C; ++k) v.push_back(k); random_shuffle(v.begin(), v.end()); for(int k = 0; k < MAX_C; ++k) { if(k > 0) cout << " "; cout << v[k]; } cout << endl; } const int m = rand() % 100; for(int j = 0; j < m; ++j) { cout << (rand() % n) + 1 << endl; } cout << endl; } return 0; }
true
82ef6431a479899ef16106421b02e9af5dbdc00d
C++
PhilCK/vortex
/Code/Caffeine/Tests/AnyDataTest.cpp
UTF-8
2,670
3.484375
3
[]
no_license
#include <UnitTest.hpp> #include <Caffeine/Utilities/AnyData.hpp> TEST(SimpleUse) { // Ints and String { const Caffeine::Utilities::AnyData data(123); ASSERT_IS_EQUAL(123, data.asInt8()) ASSERT_IS_EQUAL(123, data.asUInt8()) ASSERT_IS_EQUAL(123, data.asInt16()) ASSERT_IS_EQUAL(123, data.asUInt16()) ASSERT_IS_EQUAL(123, data.asInt32()) ASSERT_IS_EQUAL(123, data.asUInt32()) ASSERT_IS_EQUAL("123", data.asStdString()) ASSERT_IS_TRUE(false) // you need to test extreams of ints etc. } // Floating Point { const Caffeine::Utilities::AnyData data1(123.32f); ASSERT_IS_EQUAL(123.32f, data1.asFloat()) ASSERT_IS_EQUAL(123.32, data1.asDouble()) const Caffeine::Utilities::AnyData data2(-123.32); ASSERT_IS_EQUAL(-123.32f, data2.asFloat()) ASSERT_IS_EQUAL(-123.32, data2.asDouble()) } // Signed Ints { const Caffeine::Utilities::AnyData data("-32"); ASSERT_IS_EQUAL(-32, data.asInt8()) ASSERT_IS_EQUAL(-32, data.asInt16()) ASSERT_IS_EQUAL(-32, data.asInt32()) } } TEST(Tokens) { const Caffeine::Utilities::AnyData data("9 8 7 6 5"); // Int Tokens { const std::vector<int> tokens = data.asIntTokens(); ASSERT_IS_EQUAL(5, tokens.size()) ASSERT_IS_EQUAL(tokens.at(0), 9) ASSERT_IS_EQUAL(tokens.at(1), 8) ASSERT_IS_EQUAL(tokens.at(2), 7) ASSERT_IS_EQUAL(tokens.at(3), 6) ASSERT_IS_EQUAL(tokens.at(4), 5) } // Float Tokens { const Caffeine::Utilities::AnyData fdata("9.1 8.2 7.3 6.4 5.5"); const std::vector<float> tokens = fdata.asFloatTokens(); ASSERT_IS_EQUAL(tokens.at(0), 9.1f) ASSERT_IS_EQUAL(tokens.at(1), 8.2f) ASSERT_IS_EQUAL(tokens.at(2), 7.3f) ASSERT_IS_EQUAL(tokens.at(3), 6.4f) ASSERT_IS_EQUAL(tokens.at(4), 5.5f) } // String Tokens { const std::vector<std::string> tokens = data.asStringTokens(); ASSERT_IS_EQUAL(tokens.at(0), "9") ASSERT_IS_EQUAL(tokens.at(1), "8") ASSERT_IS_EQUAL(tokens.at(2), "7") ASSERT_IS_EQUAL(tokens.at(3), "6") ASSERT_IS_EQUAL(tokens.at(4), "5") } } TEST(Asignments) { Caffeine::Utilities::AnyData data; data = 3; ASSERT_IS_EQUAL(3, data.asUInt8()) data = -4; ASSERT_IS_EQUAL(-4, data.asInt16()) data = 65535; ASSERT_IS_EQUAL(65535, data.asUInt16()) data = 3.2f; ASSERT_IS_EQUAL(3.2f, data.asFloat()) ASSERT_IS_EQUAL(3.2, data.asDouble()) data = std::string("foo"); ASSERT_IS_EQUAL("foo", data.asStdString()) data = "bar"; ASSERT_IS_EQUAL("bar", data.asStdString()) } TEST(Pointer) { //float a = 1.23f; //float b = 3.23f; //Caffeine::Utilities::AnyData data(&a); //ASSERT_IS_EQUAL("0", data.asStdString()) //ASSERT_IS_EQUAL(8, sizeof(long*)) } int main() { Test::RunTests(); return 0; }
true
e3ac025b6776e502aa49330c5fdb084e4d216170
C++
xeppaka/ganids
/common.cpp
UTF-8
909
3
3
[]
no_license
#include <iomanip> #include "common.h" using std::hex; //std::ostream& print_sequence_val32(std::ostream &stream, const sequence_val32 &val) { // int cur_node_type = val & NODE_TYPE_PATTERN; // switch (cur_node_type) { // case NODE_NORMAL: // stream << static_cast<int>(val & NODE_VALUE_PATTERN); // break; // case NODE_ANY: // stream << '*'; // break; // case NODE_RANGE: // int from = (val & NODE_VALUE_PATTERN) >> 8; // int to = val & NODE_VALUE_PATTERN & 0x00FF; // stream << from << '-' << to; // break; // } // return stream; //} std::ostream& operator<<(std::ostream &stream, const sequence32 &sequence) { for (sequence32::const_iterator it = sequence.begin(); it != sequence.end(); ++it) { stream << hex << *it; if (it != sequence.end() - 1) stream << ' '; } return stream; }
true
7e9050c61ea40b55c6ba99cc1cf6df2d3265209b
C++
happydhKim/MyDataStructureAlgorithm
/newMyDataStructureAlgorithm/algorithm/permutation.cpp
UTF-8
403
2.546875
3
[]
no_license
// https://www.acmicpc.net/problem/15649 #include <stdio.h> int n, m, i, c[9]; char d[20]; void dfs(int depth) { if (depth == m) { printf("%s\n",d); return; } for (int i = 1; i <= n; i++) { if (c[i]) { continue; } d[depth * 2] = i + '0'; c[i] = 1; dfs(depth + 1); c[i] = 0; } } int main() { scanf("%d%d", &n,&m); for (i = 0; i < 2 * m; i++) { d[i] = ' '; } dfs(0); return 0; }
true
6e07eff93f96071acaf322bce748b53fe097435c
C++
xliu45/Job-Fun
/LeetCode/C++/94_Binary_Tree_Inorder_Traversal.cpp
UTF-8
1,548
3.9375
4
[]
no_license
//94. Binary Tree Inorder Traversal /* Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,3,2]. Tag: Tree, Hash Table, Stack Author: Xinyu Liu */ #include <iostream> #include <vector> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; //class Solution { //public: // vector<int> inorderTraversal(TreeNode* root) { // vector<int> vec; // subinorder(root, vec); // return vec; // } // void subinorder(TreeNode* root, vector<int> &vec){ // if(!root){ // return; // } // subinorder(root->left, vec); // vec.push_back(root->val); // subinorder(root->right, vec); // } //}; class Solution { public: vector<int> inorderTraversal(TreeNode* root) { if(!root) return vector<int>(); stack<TreeNode*> s; vector<int> vec; while(!s.empty() || root){ if(root){ s.push(root); root = root->left; } else{ root = s.top(); vec.push_back(root->val); s.pop(); root = root->right; } } return vec; } }; void main(){ TreeNode n1(1),n2(2),n3(3); n1.right = &n2; n2.left = &n3; Solution sol; vector<int> vec = sol.inorderTraversal(&n1); }
true
443f1f8c6ddb026eb98298b975fe681891a9bbc1
C++
barajasr/Snake
/include/Definitions.hpp
UTF-8
1,311
3
3
[]
no_license
#ifndef __DEFINITIONS_HPP__ #define __DEFINITIONS_HPP__ #include <SFML/Graphics.hpp> enum Direction{UP, DOWN, LEFT, RIGHT}; enum TileType{EMPTY, FOOD, HAZARD}; // Constants for 2D gameboard, max indices const unsigned BOARD_X = 61; const unsigned BOARD_Y = 61; const unsigned IMAGESIZE = 8; // Total margin between gameboard and window, in pixels // MARGIN/2 to be exact for left, top, right const unsigned MARGIN = 10; const unsigned SCORE_MARGIN = 30; // specific to bottom const unsigned WINDOW_X = BOARD_X * IMAGESIZE + BOARD_X + MARGIN - 1; const unsigned WINDOW_Y = BOARD_Y * IMAGESIZE + BOARD_Y + MARGIN + SCORE_MARGIN - 1; struct Tile{ TileType type; sf::RectangleShape tile; Tile(sf::Vector2f pos, unsigned imageSize=IMAGESIZE, TileType tType=EMPTY){ sf::Color color = getNewTileFill(tType); tile.setSize(sf::Vector2f(imageSize,imageSize)); tile.setPosition(pos); tile.setFillColor(color); } sf::Color getNewTileFill(TileType tType){ sf::Color color; switch(tType){ default: case EMPTY: color = sf::Color(211, 211, 211); break; case FOOD: color = sf::Color::Red; break; case HAZARD: color = sf::Color::Magenta; break; } return color; } void setTileType(TileType tType){ type = tType; tile.setFillColor(getNewTileFill(tType)); } }; #endif
true
1e16e840bb35585d8d60fa3f24cea0afcb6c5494
C++
julianbeek/openFrameworksHKU
/les3BounceKeys/src/ofApp.cpp
UTF-8
1,146
2.890625
3
[]
no_license
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { amount = 1; addOne = 0; for (int i = 0; i < amount; i++) { Triangle newTriangleA; newTriangleA.setup(); TriangleA.push_back(newTriangleA); } } //-------------------------------------------------------------- void ofApp::update() { for (int i = 0; i < TriangleA.size(); i++) { TriangleA[i].bounce(); } } //-------------------------------------------------------------- void ofApp::draw() { for (int i = 0; i < TriangleA.size(); i++) { TriangleA[i].display(); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { if (key == 'c') // create { addOne += 1; for (int i = 0; i < addOne; i++) { Triangle newTriangleA; newTriangleA.setup(); TriangleA.push_back(newTriangleA); addOne = 0; } } else if (key == 'd') { // delete if (TriangleA.size() > 0) { TriangleA.erase(TriangleA.begin()); } } }
true
6aedc575f423df44db6838df94209bec674177be
C++
monircse061/Lab-Problems-Solution-Codes
/Others/binary search std.cpp
UTF-8
845
3.171875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ vector<int> v ; v.push_back(2); v.push_back(3); v.push_back(5); v.push_back(9); v.push_back(10); v.push_back(13); /*bool ans= binary_search(v.begin(),v.end(),9); if(ans) cout<<" Found "; else cout<<" Not Found ";*/ /// for lower bound ; 1st element which is same or greater than the input value vector<int>::iterator it=lower_bound(v.begin(),v.end(),5); cout<<*it<<endl; cout<<distance(v.begin(),it)<<endl; ///if(it==v.end()) ///cout<<"not found" ; /// for upper bound 1st element which is only greater than the input value vector<int>::iterator itt = upper_bound(v.begin(),v.end(),9); cout<<*itt<<endl; cout<<distance(v.begin(),itt); return 0; }
true
6e7ecb900c28274dcaeb776db7501b10b0f25666
C++
MeLikeyCode/QtGameEngine
/example projects/example9/main.cpp
UTF-8
2,368
3.28125
3
[]
no_license
// Basic GUI // Hello again and welcome back to another QGE tutorial! // // Today, I will show you how to create a basic GUI. // // All Gui objects inherit from qge::Gui. They can be added to a Game (via Game::addGui()) or to a Map (via Map::addGui()). // If they are added to a Game, they will be positioned relative to the top left of the screen. // If they are added to a Map, they will be positioned relative to the top left of the Map. // All Guis that you add to a Game, will always show on the screen, regardless of what Map you are currently seeing. // For Guis that you placed to a Map, they are only seen when you are seeing that map (i.e. when that map is the current map). // // Enjoy! // - Abdullah #include <QApplication> #include <QDebug> #include "qge/MapGrid.h" #include "qge/Map.h" #include "qge/Game.h" #include "qge/Label.h" #include "qge/Button.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); // create MapGrid, Map, and Game qge::MapGrid* mapGrid = new qge::MapGrid(1,1); qge::Map* map = new qge::Map(); mapGrid->setMapAtPos(map,0,0); qge::Game* game = new qge::Game(mapGrid,0,0); game->launch(); // create some Guis // create a Label qge::Label* label = new qge::Label("Hello! I'm a label!"); label->setGuiPos(QPointF(50,50)); game->addGui(label); // add the Label to the *Game* // create a Button qge::Button* button = new qge::Button(); button->setText("Hello, I'm a button! Click me!"); button->setGuiPos(QPointF(100,100)); map->addGui(button); // add the Button to the *Map* // Button has a "clicked" signal that is emitted whenever it is clicked. // But for convenience, you can also have it execute a function each time it is clicked. // Here we have it execute a lambda function each time it is clicked. auto cb = [](qge::Button* btn){ qDebug() << "Ouch! You clicked me!"; }; button->setOnClickCB(cb); return a.exec(); } // So let's recap! // - we added a Label Gui to the Game (thus it is positioned relative to the top left of the *screen* (and it will be visible no matter what Map we are currently seeing). // - we added a Button Gui to the Map (thus it is positioned relative to the top left of the *map* // - we had a function be called each time the Button is clicked // // That is all for today!
true
ecbf18ada503fc140b7981283bf1fb952ae3a864
C++
Syhawk/LeetCode
/divide_two_integers.cpp
UTF-8
2,287
3.578125
4
[]
no_license
//uri: https://leetcode.com/problems/divide-two-integers/ /* * 由于不允许使用乘、除以及取余运算,所以可以采用加、减以及位运算来实现除法。 * 首先考虑特殊情况,主要是int整数越界情况。然后将被除数与除数转化为正整数, * 对正整数进行操作。由于所有的int整数都可以转化成二进制来表示,那么一个 * 十进制整数x可以由另一个十进制整数y以及余数z来表示。 * x = (2 ^ a1 + 2 ^ a2 + 2 ^ a3 + ... 2 ^ an) * y + z。其中ai均为非负整数, * 且ai < 32, ai < ai+1 * 那么,我们可以先找出最大的an,循环从an到a1,然后将2 ^ ai叠加起来就是商。 * 最大an就是被除数与除数转化为二进制之后的位数之差,也就是代码中cnt1与cnt2之差。 * 空间复杂度:O(1). * 时间复杂度:O(1). * */ class Solution { public: int divide(int dividend, int divisor) { int MAX_INF = 0x7fffffff; int MIN_INF = 0x80000000; if(divisor == 0) return MAX_INF; if(dividend == 0) return 0; if(divisor == 1) return dividend; if(divisor == -1) { if(dividend == MIN_INF) return MAX_INF; else return -dividend; } if(dividend == divisor) return 1; if(divisor == MIN_INF) return 0; bool flg = 0; if((dividend ^ divisor) < 0) flg = 1; int x = dividend, y = 0, z = abs(divisor); if(dividend == MIN_INF) { x = MAX_INF; y = 1; } else if(dividend < 0) x = -dividend; int t1 = x, t2 = z; int cnt1 = 0, cnt2 = 0; while(t1) { t1 >>= 1; ++ cnt1; } while(t2) { t2 >>= 1; ++ cnt2; } if(cnt1 < cnt2) return 0; int cnt = 0; if(x - (z - y) >= 0) { x -= (z - y); ++ cnt; y = 0; } else return 0; cnt1 -= cnt2; while(cnt1 >= 0) { int t = z << cnt1; if(x - t >= 0) { x -= t; cnt += (1 << cnt1); } -- cnt1; } if(flg) cnt = -cnt; return cnt; } };
true
78a6471fe9a07a59487cb40fd5c8a071cbfe826e
C++
miviwi/Hamil
/Hamil/include/py/object.h
UTF-8
2,387
2.859375
3
[]
no_license
#pragma once #include <py/python.h> #include <string> #include <utility> #include <type_traits> namespace py { class TypeObject; class List; class Dict; class Tuple; // RAII wrapper around PyObject (does Py_DECREF automatically) // - nullptr can be passed to the constructor as the 'object' // and will be handled correctly, though no checking is done // when attempting to run methods on such an Object // - NEVER put Object's or any other derived types in global scope // they are initialized before the interpreter and will cause // undefined behaviour. // To overcome this limitation do: // Object obj = nullptr; // void init_obj() // { // obj = ...; // init 'obj' however you like // } class Object { public: Object(PyObject *object); Object(const Object& other); Object(Object&& other); ~Object(); Object& operator=(const Object& other); // Steals reference Object& operator=(PyObject *object); static Object ref(PyObject *object); Object& ref(); bool deref(); PyObject *move(); void dispose(); PyObject *py() const; PyObject *operator *() const; operator bool() const; template <typename T> bool typeCheck() const { static_assert(std::is_base_of_v<Object, T>, "invalid T passed to Object::typeCheck()!"); return py() ? T::py_type_check(py()) : false; } template <typename T> T as() const& { return typeCheck<T>() ? ref(py()) : nullptr; } template <typename T> T as() && { return typeCheck<T>() ? move() : nullptr; } std::string str() const; std::string repr() const; Object attr(const Object& name) const; Object attr(const char *name) const; void attr(const Object& name, const Object& value); void attr(const char *name, const Object& value); bool callable() const; Object call(Tuple args, Dict kwds); Object call(Tuple args); Object call(); template <typename... Args> Object call(Args&&... args) { auto tuple = PyTuple_Pack(sizeof...(args), args.py()...); return doCall(tuple); // cleans up 'tuple' } template <typename... Args> Object operator()(Args&&... args) { return call(std::forward<Args>(args)...); } List dir() const; private: Object doCall(PyObject *args); PyObject *m; }; Object py(int i); Object py(size_t sz); Object py(const char *str); Object py(const std::string& str); }
true
5df896689d6e73b9175df63b2f0d817b7212987c
C++
Anonymous-V/Principles-and-Practice-Using-CPP-2nd-edition
/chapter_08/task_10/main.cpp
UTF-8
4,602
3.5
4
[]
no_license
/* * Описание задачи: * ================ * Напишите функцию, которая находит наименьший и наибольший элементы вектора, * являющегося ее аргументом, а также вычисляющую их среднее и медиану. Не * используйте глобальные переменные. Результаты можно вернуть либо в виде структуры * struct, либо с помощью механизма передачи аргументов по ссылке. Какой из этих * двух способов следует предпочесть и почему? * * Идея реализации: * ================ * Т.к. поиск медианы предусматривает использование отсортированного вектора, то * лучше всего отсортировать вектор до начала вычислений. Таким образом можно * получить сразу минимальный и максимальный элементы. Медианой же, является * середина вектора, а среднее значение находится суммируя весь вектор и деля его * на количество элементов в нем. * * Считаю, что в данной задаче лучше использовать структуру, т.к. элементы не будут * "отделены" друг от друга и будут храниться в одном месте. Конечно, всё зависит от * конкретной задачи и каждый из способов будет более предпочтительнее. * */ #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::cin; using std::endl; using std::vector; struct Values { double maxv; // Максимальное значение double minv; // Минимальное значение double avgv; // Среднее значение double medv; // Медиана }; // Поиск максимального числа (вектор изначально отсортирован) double maxv(const vector <double> &elems) { if (elems.empty()) throw std::runtime_error("Vector is empty"); return elems[elems.size() - 1]; } // Поиск минимального числа (вектор изначально отсортирован) double minv(const vector <double> &elems) { if (elems.empty()) throw std::runtime_error("Vector is empty"); return elems[0]; } // Вычисление среднего значения double avgv(const vector <double> &elems) { if (elems.empty()) throw std::runtime_error("Vector is empty"); double avg_val = 0; for (double elem : elems) avg_val += elem; return avg_val / elems.size(); } // Вычисление медианы double medv(const vector <double> &elems) { if (elems.empty()) throw std::runtime_error("Vector is empty"); int mid = elems.size() / 2; if (elems.size() % 2 != 0) return elems[mid]; return (elems[mid - 1] + elems[mid]) / 2; } // Ввод вектора вещественных чисел void inp_elems(vector <double> &elems) { double val; cout << "Enter nums (any symbol to exit):" << endl; while (cin) { cin >> val; if (!cin) break; elems.push_back(val); } } Values calculate(vector <double> &nums) { try { Values val {}; // Сортировка вектора; необходимо для поиска медианы // Также упрощает поиск минимального и максимального значения std::sort(nums.begin(), nums.end()); val.maxv = maxv(nums); val.minv = minv(nums); val.avgv = avgv(nums); val.medv = medv(nums); return val; } catch (std::runtime_error &e) { std::cerr << e.what() << endl; return {}; } } int main() { try { vector <double> nums; inp_elems(nums); Values val = calculate(nums); cout << "Max: " << val.maxv << '\n' << "Min: " << val.minv << '\n' << "Avg: " << val.avgv << '\n' << "Med: " << val.medv << '\n'; return 0; } catch (...) { std::cerr << "Unknown exception" << endl; return 1; } }
true
330ac0dc8feb2fe132108a0d5e0c25f51bf5015f
C++
shantanudwvd/Coding_Problems_in_C-
/Queue_operations.cpp
UTF-8
943
2.875
3
[]
no_license
// // Created by Shantanu on 2/14/2020. // #include <iostream> #include <deque> using namespace std; int main() { deque<int> array; deque<int>::iterator itr; int s1, s2; cin >> s1; for (int i = 0, val; i < s1; ++i) { cin >> val; array.push_back(val); } cin >> s2; int freq[s2 + 1]; for (int j = 0; j < s2; ++j) { cin >> freq[j]; } int count; for (int k = 0; k < s2; ++k) { auto val = freq[k]; itr = array.begin(); count = 0; for (int i = 0; i < s1 - count; ++i) { if (array[i] == val) { count++; array.erase(itr); itr++; i -= 1; } else itr++; } s1 = s1 - count; if (count == 0) cout << "-1" << " "; else cout << count << " "; } }
true
31cad6e72c64b057d70aa821e73d70013cd2aa27
C++
lynli/radiomicfeatures
/Extraction/Collage/Code/MEX_ComputeHaralick/ComputeHaralick.cpp
UTF-8
8,979
2.53125
3
[]
no_license
#include "mex.h" #include <algorithm> #include <iostream> using namespace std; inline double logb(double x, double b) { return std::log(x) / std::log(b); } void graycomtx(const double *image, double *comtx, int ws, int dist, int graylevels, const int background, int rows, int cols, int row, int col) { int i, j, k, l, centerind, pixind, center_value, hws; int d_start_row, d_start_col, d_end_row, d_end_col; int block_start_row, block_start_col, block_end_row, block_end_col; for (i = 0; i < graylevels*graylevels; i++) comtx[i] = 0.0; hws = (int)std::floor((float)ws / 2); block_start_row = std::max(0, row - hws); block_start_col = std::max(0, col - hws); block_end_row = std::min(rows - 1, row + hws); block_end_col = std::min(cols - 1, col + hws); for (j = block_start_col; j < block_end_col; j++) for (i = block_start_row; i < block_end_row; i++) { centerind = i + j*rows; center_value = (int)image[centerind]; if (center_value == background) continue; d_start_row = std::max((int)0, i - dist); d_start_col = std::max((int)0, j - dist); d_end_row = std::min((int)rows - 1, i + dist); d_end_col = std::min((int)cols - 1, j + dist); for (l = d_start_col; l <= d_end_col; l++) for (k = d_start_row; k <= d_end_row; k++) { pixind = k + l*rows; if (image[pixind] != background && pixind != centerind) comtx[center_value + (int)(image[pixind] + 0.5)*graylevels] += 1; } } } /* haralick2mex -- Haralick for 2D images. Syntax: * haralickims = haralick2mex(double image, double graylevels, double window_size, double dist, double background [optional]) */ void haralick2(double *image, double *haralicks, int ws, int dist, int graylevels, int background, int rows, int cols, int nharalicks) { int i, j, k, ii, jj, nbins, nnonzeros; int *hi, *hj, *himhj, *hiphj; double *comtx, *p, *pnz, *nzcomtx, *px, *py, *pxplusy, *pxminusy; double entropyval, energyval, inertiaval, idmval, correlationval, info1val, info2val, H1, H2, sigma_x, sigma_y, mu_x, mu_y, h_x, h_y, h_max, saval, svval, seval, daval, dvval, deval, cosum; nbins = graylevels*graylevels; comtx = (double *)malloc(nbins*sizeof(double)); nzcomtx = (double *)malloc(nbins*sizeof(double)); p = (double *)malloc(nbins*sizeof(double)); pnz = (double *)malloc(nbins*sizeof(double)); px = (double *)malloc(graylevels*sizeof(double)); py = (double *)malloc(graylevels*sizeof(double)); pxplusy = (double *)malloc(2 * graylevels*sizeof(double)); pxminusy = (double *)malloc(graylevels*sizeof(double)); hi = (int *)malloc(nbins*sizeof(int)); hj = (int *)malloc(nbins*sizeof(int)); himhj = (int *)malloc(nbins*sizeof(int)); hiphj = (int *)malloc(nbins*sizeof(int)); for (j = 0; j < cols; j++) for (i = 0; i < rows; i++) if (image[i + j*rows] >= graylevels && image[i + j*rows] != background) std::cerr << "Graylevels of image fall outside acceptable range."; for (j = 0; j < cols; j++) { for (i = 0; i < rows; i++) { if (image[i + j*rows] != background) { /* Get co-occurrence matrix */ graycomtx(image, comtx, ws, dist, graylevels, background, rows, cols, i, j); /* Initialize feature values */ entropyval = 0; energyval = 0; inertiaval = 0; idmval = 0; correlationval = 0; info1val = 0; info2val = 0; saval = 0; svval = 0; seval = 0; daval = 0; dvval = 0; deval = 0; H1 = 0; H2 = 0; h_x = 0; h_y = 0; h_max = 0; mu_x = 0; mu_y = 0; sigma_x = 0; sigma_y = 0; cosum = 0; /* Non-zero elements & locations in comtx and distribution */ for (k = 0; k < nbins; k++) cosum += comtx[k]; if (cosum < 2) continue; for (k = 0, ii = 0; k < nbins; k++) { if (comtx[k] > 0) { p[k] = comtx[k] / cosum; pnz[ii] = p[k]; nzcomtx[ii] = comtx[k]; hi[ii] = k % graylevels; hj[ii] = (int)floor((float)k / (float)graylevels); himhj[ii] = hi[ii] - hj[ii]; hiphj[ii] = hi[ii] + hj[ii]; ii++; } else { p[k] = 0; } } nnonzeros = ii; /* Entropy, Energy, Inertial, Inv. Diff. Moment */ for (k = 0; k < nnonzeros; k++) { //pnz[k]=nzcomtx[k]/nbins; entropyval -= pnz[k] * logb(pnz[k], 2.0); energyval += pnz[k] * pnz[k]; inertiaval += himhj[k] * himhj[k] * pnz[k]; idmval += pnz[k] / (1.0 + himhj[k] * himhj[k]); } /* Marginal distributions */ for (ii = 0; ii < graylevels; ii++) { px[ii] = 0; py[ii] = 0; } for (k = 0, ii = 0; ii < graylevels; ii++) for (jj = 0; jj < graylevels; jj++, k++) { py[ii] += p[k]; px[jj] += p[k]; } /* Correlation */ for (ii = 0; ii < graylevels; ii++) { h_x -= (px[ii] > 0 ? px[ii] * logb(px[ii], 2.0) : 0); h_y -= (py[ii] > 0 ? py[ii] * logb(py[ii], 2.0) : 0); mu_x += ii*px[ii]; mu_y += ii*py[ii]; } for (ii = 0; ii < graylevels; ii++) { sigma_x += pow(ii - mu_x, 2) * px[ii]; sigma_y += pow(ii - mu_y, 2) * py[ii]; } if (sigma_x > (1e-4) && sigma_y > (1e-4)) { for (k = 0; k < nnonzeros; k++) correlationval += (hi[k] - mu_x)*(hj[k] - mu_y)*pnz[k]; correlationval /= sqrt(sigma_x*sigma_y); } else correlationval = 0; /* Information measures of correlation */ for (k = 0, ii = 0; ii < graylevels; ii++) for (jj = 0; jj < graylevels; jj++, k++) { H1 -= (p[k] > 0 && px[jj]>0 && py[ii]>0 ? p[k] * logb(px[jj] * py[ii], 2.0) : 0); H2 -= (px[jj] > 0 && py[ii] > 0 ? px[jj] * py[ii] * logb(px[jj] * py[ii], 2.0) : 0); } h_max = std::max(h_x, h_y); info1val = (h_max != 0 ? (entropyval - H1) / h_max : 0); info2val = sqrt(abs(1 - exp(-2 * (H2 - entropyval)))); /* Sum average, variance and entropy */ for (k = 0; k < (2 * graylevels); k++) pxplusy[k] = 0; for (k = 0; k < nnonzeros; k++) pxplusy[hiphj[k]] += pnz[k]; for (k = 0; k < (2 * graylevels); k++) { saval += k*pxplusy[k]; seval -= (pxplusy[k] > 0 ? pxplusy[k] * logb(pxplusy[k], 2.0) : 0); } for (k = 0; k < (2 * graylevels); k++) svval += pow(k - saval, 2) * pxplusy[k]; /* Difference average, variance and entropy */ for (k = 0; k < graylevels; k++) pxminusy[k] = 0; for (k = 0; k < nnonzeros; k++) pxminusy[abs(himhj[k])] += pnz[k]; for (k = 0; k < graylevels; k++) { daval += k*pxminusy[k]; deval -= (pxminusy[k] > 0 ? pxminusy[k] * logb(pxminusy[k], 2.0) : 0); } for (k = 0; k < graylevels; k++) dvval += pow(k - daval, 2) * pxminusy[k]; /* Put feature values in output volume */ haralicks[i + j*rows + 0 * rows*cols] = entropyval; haralicks[i + j*rows + 1 * rows*cols] = energyval; haralicks[i + j*rows + 2 * rows*cols] = inertiaval; haralicks[i + j*rows + 3 * rows*cols] = idmval; haralicks[i + j*rows + 4 * rows*cols] = correlationval; haralicks[i + j*rows + 5 * rows*cols] = info1val; haralicks[i + j*rows + 6 * rows*cols] = info2val; haralicks[i + j*rows + 7 * rows*cols] = saval; haralicks[i + j*rows + 8 * rows*cols] = svval; haralicks[i + j*rows + 9 * rows*cols] = seval; haralicks[i + j*rows + 10 * rows*cols] = daval; haralicks[i + j*rows + 11 * rows*cols] = dvval; haralicks[i + j*rows + 12 * rows*cols] = deval; } else { for (k = 0; k < nharalicks; k++) haralicks[i + j*rows + k*rows*cols] = 0; } } } delete[] comtx; delete[] p; delete[] pnz; delete[] nzcomtx; delete[] px; delete[] py; delete[] pxplusy; delete[] pxminusy; delete[] hi; delete[] hj; delete[] himhj; delete[] hiphj; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *haralicks, *image; int dist, rows, cols; int graylevels, background, ws; mwSize dims[3]; int nharalicks=13; //unsigned short int *X; if(nrhs > 5 || nrhs < 4) mexErrMsgTxt("haralick2mex(image,graylevels,ws,dist,background)"); if(!mxIsDouble(prhs[0])) mexErrMsgTxt("Input image must be DOUBLE."); image = mxGetPr(prhs[0]); rows = (int) mxGetM(prhs[0]); cols = (int) mxGetN(prhs[0]); graylevels=(int) mxGetScalar(prhs[1]); ws = (int) mxGetScalar(prhs[2]); dist = (int) mxGetScalar(prhs[3]); if (nrhs==4) background = -1; else background = (int) mxGetScalar(prhs[4]); if(graylevels < 0 || graylevels > 65535) mexErrMsgTxt("GRAYLEVELS must be between 0 and 2^16-1."); dims[0] = rows; dims[1] = cols; dims[2] = nharalicks; plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL); haralicks = mxGetPr(plhs[0]); haralick2(image,haralicks,ws,dist,graylevels,background,rows,cols,nharalicks); }
true
cc1d75b493ecf617012fc9d53daf886ef9dc15c8
C++
raghuit/DSA-REVISION
/FAANG IMP. INTERVIEW QUE3/LCS.cpp
UTF-8
804
3.546875
4
[]
no_license
PROBLEM STATEMENT: Longest Common Subsequence Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase. LANGUAGE USED:C++ CODE SOLUTION: class Solution { public: //Function to find the length of longest common subsequence in two strings. int lcs(int x, int y, string s1, string s2) { int dp[2][y+1]; for(int i=0;i<=x;i++){ for(int j=0;j<=y;j++){ if(i==0 or j==0) dp[i%2][j] =0; else if(s1[i-1]==s2[j-1]){ dp[i%2][j] = 1 + dp[(i+1)%2][j-1]; } else{ dp[i%2][j] = max(dp[i%2][j-1],dp[(i+1)%2][j]); } } } return dp[x%2][y]; } };
true
88fb331c37e729eac283d5a32043ea94419fc01c
C++
carlosaffrc/HackerRank-CPP
/30DaysOfCode/day8-Maps-PhoneBook.cpp
UTF-8
937
3.515625
4
[]
no_license
#include <vector> #include <iostream> #include <algorithm> #include <map> #include <string> int main() { int entries; int value; std::string key; //map std::map<std::string, int> phoneBook; //iterator std::map<std::string, int>::iterator it; //pair for return value of map std::pair <std::map<std::string,int>::iterator, bool> ptr; std::cin >> entries; //To fill the phonebook for(int i = 0; i < entries; i++) { std::cin >> key; std::cin >> value; ptr = phoneBook.insert(std::pair<std::string,int>(key,value)); } //To get unlimited queries while(std::cin >> key) { if (phoneBook.find(key) != phoneBook.end()) { std::cout << key << "=" << phoneBook.find(key)->second << std::endl; } else { std::cout << "Not found" << std::endl; } } return 0; }
true
9e5c545eabba618130e23352e31513bd1b3070ac
C++
wdeng7714/Minesweeper
/src/Number.h
UTF-8
310
2.53125
3
[]
no_license
/* * Numbers.h * * Created on: Apr 22, 2016 * Author: Wendy */ #ifndef NUMBER_H_ #define NUMBER_H_ #include "Tile.h" class Number :public Tile { private: int m_number; public: Number(); virtual ~Number(); void setNumber(int n); int getNumber(); }; #endif /* NUMBER_H_ */
true
076e1175605dd8f7255f23d4e45b042824194763
C++
timkpaine/aat
/aat/cpp/include/aat/config/enums.hpp
UTF-8
5,754
2.515625
3
[ "Apache-2.0" ]
permissive
#pragma once #include <iostream> #include <unordered_map> #include <vector> #include <aat/common.hpp> using namespace aat::common; namespace aat { namespace config { enum class TradingType { LIVE = 0, SIMULATION = 1, SANDBOX = 2, BACKTEST = 3, }; enum class Side { NONE = 0, BUY = 1, SELL = 2, }; enum class OptionType { CALL = 0, PUT = 0, }; enum class EventType { // Heartbeat events HEARTBEAT = 0, // Trade events TRADE = 1, // Order events OPEN = 2, CANCEL = 3, CHANGE = 4, FILL = 5, // Other data events DATA = 6, // System events HALT = 7, CONTINUE = 8, // Engine events ERROR = 9, START = 10, EXIT = 11, // Order Events BOUGHT = 12, SOLD = 13, RECEIVED = 14, REJECTED = 15, CANCELED = 16 }; enum class DataType { DATA = 0, ERROR = 1, ORDER = 2, TRADE = 3, }; enum class InstrumentType { OTHER = 0, EQUITY = 1, BOND = 2, OPTION = 3, FUTURE = 4, PAIR = 6, SPREAD = 7, FUTURESOPTION = 8, MUTUALFUND = 9, COMMODITY = 10, CURRENCY = 11, INDEX = 12, }; enum class OrderType { LIMIT = 0, MARKET = 1, STOP = 2, }; enum class OrderFlag { NONE = 0, FILL_OR_KILL = 1, ALL_OR_NONE = 2, IMMEDIATE_OR_CANCEL = 3, }; enum class ExitRoutine { NONE = 0, CLOSE_ALL = 1, }; static const std::vector<str_t> TradingType_names = { "LIVE", "SIMULATION", "SANDBOX", "BACKTEST", }; static const std::vector<str_t> Side_names = { "NONE", "BUY", "SELL", }; static const std::vector<str_t> OptionType_names = { "CALL", "PUT", }; static const std::vector<str_t> EventType_names = { "HEARTBEAT", "TRADE", "OPEN", "CANCEL", "CHANGE", "FILL", "DATA", "HALT", "CONTINUE", "ERROR", "START", "EXIT", "BOUGHT", "SOLD", "RECEIVED", "REJECTED", "CANCELED", }; static const std::vector<str_t> DataType_names = { "DATA", "ERROR", "ORDER", "TRADE", }; static const std::vector<str_t> InstrumentType_names = { "OTHER", "EQUITY", "BOND", "OPTION", "FUTURE", "PAIR", "SPREAD", "FUTURESOPTION", "MUTUALFUND", "COMMODITY", "CURRENCY", "INDEX", }; static const std::vector<str_t> OrderType_names = { "LIMIT", "MARKET", "STOP", }; static const std::vector<str_t> OrderFlag_names = { "NONE", "FILL_OR_KILL", "ALL_OR_NONE", "IMMEDIATE_OR_CANCEL", }; static const std::vector<str_t> ExitRoutine_names = { "NONE", "CLOSE_ALL", }; static std::unordered_map<str_t, TradingType> _TradingType_mapping = { {"LIVE", TradingType::LIVE}, {"SIMULATION", TradingType::SIMULATION}, {"SANDBOX", TradingType::SANDBOX}, {"BACKTEST", TradingType::BACKTEST}, }; static std::unordered_map<str_t, Side> _Side_mapping = { {"NONE", Side::NONE}, {"BUY", Side::BUY}, {"SELL", Side::SELL}, }; static std::unordered_map<str_t, OptionType> _OptionType_mapping = { {"CALL", OptionType::CALL}, {"PUT", OptionType::PUT}, }; static std::unordered_map<str_t, EventType> _EventType_mapping = { {"HEARTBEAT", EventType::HEARTBEAT}, {"TRADE", EventType::TRADE}, {"OPEN", EventType::OPEN}, {"CANCEL", EventType::CANCEL}, {"CHANGE", EventType::CHANGE}, {"FILL", EventType::FILL}, {"DATA", EventType::DATA}, {"HALT", EventType::HALT}, {"CONTINUE", EventType::CONTINUE}, {"ERROR", EventType::ERROR}, {"START", EventType::START}, {"EXIT", EventType::EXIT}, {"BOUGHT", EventType::BOUGHT}, {"SOLD", EventType::SOLD}, {"RECEIVED", EventType::RECEIVED}, {"REJECTED", EventType::REJECTED}, {"CANCELED", EventType::CANCELED}, }; static std::unordered_map<str_t, DataType> _DataType_mapping = { {"DATA", DataType::DATA}, {"ERROR", DataType::ERROR}, {"ORDER", DataType::ORDER}, {"TRADE", DataType::TRADE}, }; static std::unordered_map<str_t, InstrumentType> _InstrumentType_mapping = { {"OTHER", InstrumentType::OTHER}, {"EQUITY", InstrumentType::EQUITY}, {"BOND", InstrumentType::BOND}, {"OPTION", InstrumentType::OPTION}, {"FUTURE", InstrumentType::FUTURE}, {"PAIR", InstrumentType::PAIR}, {"SPREAD", InstrumentType::SPREAD}, {"FUTURESOPTION", InstrumentType::FUTURESOPTION}, {"MUTUALFUND", InstrumentType::MUTUALFUND}, {"COMMODITY", InstrumentType::COMMODITY}, {"CURRENCY", InstrumentType::CURRENCY}, {"INDEX", InstrumentType::INDEX}, }; static std::unordered_map<str_t, OrderType> _OrderType_mapping = { {"LIMIT", OrderType::LIMIT}, {"MARKET", OrderType::MARKET}, {"STOP", OrderType::STOP}, }; static std::unordered_map<str_t, OrderFlag> _OrderFlag_mapping = { {"NONE", OrderFlag::NONE}, {"FILL_OR_KILL", OrderFlag::FILL_OR_KILL}, {"ALL_OR_NONE", OrderFlag::ALL_OR_NONE}, {"IMMEDIATE_OR_CANCEL", OrderFlag::IMMEDIATE_OR_CANCEL}, }; static std::unordered_map<str_t, ExitRoutine> _ExitRoutine_mapping = { {"NONE", ExitRoutine::NONE}, {"CLOSE_ALL", ExitRoutine::CLOSE_ALL}, }; ENUM_TO_STRING(TradingType) ENUM_TO_STRING(Side) ENUM_TO_STRING(OptionType) ENUM_TO_STRING(EventType) ENUM_TO_STRING(DataType) ENUM_TO_STRING(InstrumentType) ENUM_TO_STRING(OrderType) ENUM_TO_STRING(OrderFlag) ENUM_FROM_STRING(Side) ENUM_FROM_STRING(EventType) ENUM_FROM_STRING(DataType) ENUM_FROM_STRING(InstrumentType) ENUM_FROM_STRING(OrderType) ENUM_FROM_STRING(OrderFlag) ENUM_FROM_STRING(ExitRoutine) } // namespace config } // namespace aat
true
f621b326e5f422dd44343449b6f8970a2a8d8c6b
C++
mt-revolution/Competition
/Atcoder/ABC168D.cpp
UTF-8
1,208
3.40625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; // 幅優先探索(最短距離の計算) struct bfs { vector<vector<int>> G; vector<int> mark; bfs(int N) { G.assign(N, vector<int>{}); mark.assign(N, -1); }; void make_edge(int u, int v) { G[u].push_back(v); } void make_twoedge(int u, int v) { G[u].push_back(v); G[v].push_back(u); } void do_bfs(int s) { queue<int> node; int u; mark[s] = 0; node.push(s); while (node.empty() == false) { u = node.front(); node.pop(); // u から行ける各頂点 v について再帰的に探索 for (auto v : G[u]) { if (mark[v] == -1) { mark[v] = u; node.push(v); } } } } }; int main() { int N,M; cin >> N >> M; int A,B; bfs Graph(N+1); for (int i = 0; i < M; i++) { cin >> A >> B; Graph.make_twoedge(A, B); } Graph.do_bfs(1); cout << "Yes" << endl; for (int i = 2; i <= N; i++) { cout << Graph.mark[i] << endl; } return 0; }
true
91a523ecf13afcc3c5ecbdc707b872ab8e9c3073
C++
marwababelly/OOP
/car/distanse.cpp
UTF-8
517
3.03125
3
[]
no_license
#include "distanse.h" #include <iostream> using namespace std; void distanse::setdistsnse(int f, float n) { feet = f; inches = n; } void distanse::print() { cout << "Feet = " << feet << "\t" << "Inches = " << inches << endl; } distanse :: distanse() :feet(0), inches(0.0) { } distanse :: distanse(int f, float n) : feet(f), inches(n) { } distanse distanse::add(distanse d2) { distanse result; result.feet = feet + d2.feet; result.inches = inches + d2.inches; return result; } distanse::~distanse() { }
true
0c4556b72959a7d806365ed7da0a5ebffb1d0f37
C++
OmkarSsawant/Programming-Battle-
/LeetCode/easy/common_prefix.cpp
UTF-8
1,693
3.375
3
[]
no_license
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { string prefix = ""; int j = 0; public: string longestCommonPrefix(vector<string> &strs) { if (strs.capacity() == 0) return ""; bool is_prefix = false; string tocom = minlength_str(strs); for (int i = 0; i < tocom.length(); i++) { for (string str : strs) { if (str.substr(0, i) == tocom.substr(0, i)) { is_prefix = true; } else { is_prefix = false; break; } } if (is_prefix) { prefix = tocom.substr(0, i); is_prefix = false; } } return prefix; } string minlength_str(vector<string> &vs) { string smstr = ""; string firststr = vs.at(0); int min = firststr.length(); // cout<<min; for (string str : vs) { if (min > str.length()) min = str.length(); } for (string str : vs) { if (min == str.length()) smstr= str; } return smstr; } }; int main() { Solution s; string str = "1234567"; cout << str.length() << "\n"; vector<string> strs = {"flower", "flow", "floght","flog","flgged"}; str = s.minlength_str(strs); //s.longestCommonPrefix(strs); cout << "PREFIX STRING :" << str; return 0; }
true
dd0cb7b89c8bde270c31009a38206e7555b9420c
C++
roomyroomy/algorithm
/algospot/DRAWRECT.cpp
UTF-8
688
3.21875
3
[]
no_license
#include <iostream> #include <set> using namespace std; int T; set<int> pointX; set<int> pointY; int main() { cin >> T; for(int idxTest = 0; idxTest < T; idxTest++) { set<int>::iterator it; pointX.clear(); pointY.clear(); for(int idxPoint = 0; idxPoint < 3; idxPoint++) { int x, y; cin >> x >> y; it = pointX.find(x); if(it != pointX.end()) pointX.erase(*it); else pointX.insert(x); it = pointY.find(y); if(it != pointY.end()) pointY.erase(*it); else pointY.insert(y); } set<int>::iterator valueX = pointX.begin(); set<int>::iterator valueY = pointY.begin(); cout << *valueX << " " << *valueY << endl; } return 0; }
true
853f42e85bbfdbfc07337d96527406225c7125df
C++
Davian99/Acepta_El_Reto
/AR_237.cpp
UTF-8
523
3.015625
3
[]
no_license
#include <iostream> #include <string> using namespace std; string polidiv(string num) { string ret = "POLIDIVISIBLE"; int n = num.length(); long double d = stoll(num); unsigned long long ll = stoll(num); while (n > 1) { if (d / n != ll / n) { ret = "NO POLIDIVISIBLE"; n = 0; } else { num.pop_back(); d = stoll(num); ll = stoll(num); --n; } } return ret; } int main() { //freopen("in.txt", "r", stdin); string num; while (cin >> num) { cout << polidiv(num) << "\n"; } return 0; }
true
5d3d6aa558aff3b12b56bd47b97e8241c3851f93
C++
ChristianSchweichler/EasyTimer
/EasyTimer.h
UTF-8
906
2.984375
3
[]
no_license
/* EasyTimer.h - Timer Library for Arduino. Created by Christian Schweichler, 2016 */ #ifndef EasyTimer_h #define EasyTimer_h #include "Arduino.h" class EasyTimer { typedef void (*callback_function)(); public: EasyTimer(int maxTimers); ~EasyTimer(); int setInterval(unsigned long milliseconds, callback_function callback); int setTimeout(unsigned long milliseconds, callback_function callback); void removeTimer(int id); void update(); private: enum TimerType {INTERVAL, TIMEOUT}; struct timer { int alive = 0; unsigned long milliseconds; unsigned long elapsedMilliseconds; callback_function callback; TimerType type; }; int maxTimers; timer* timers; unsigned long elapsedMilliseconds; int findFreeSlot(); int addTimer(unsigned long milliseconds, callback_function callback, TimerType type); }; #endif
true
0138159f9fd91c673f8dbdc1fdc9f00ecba53670
C++
CyJay96/Lab-cpp
/lab_7/lab_7.6/lab_7.6.cpp
UTF-8
1,249
3.03125
3
[]
no_license
/* Дата сдачи: 01.03.2021 Выполнить задания, используя двусвязные динамические структуры данных в виде связных компонент. Оценить асимптотическую сложность алгоритма. Даны натуральное число n, действительные числа x1, x2, ..., xn. Разработать программу вычисления значения выражения следующего вида: (x[1] + x[n]) * (x[2] + x[n-1]) * ... * (x[n] + x[1]). */ #include "functions.h" int main() { cout << "Enter the number of real numbers:" << endl; cout << "N = "; int n = 0; enter(n); cout << endl; Node* top = nullptr; Node* end = nullptr; cout << "Enter real numbers:" << endl; input(top, end, n); cout << "Real numbers in ascending order:" << endl; outputStart(top); cout << "Real numbers in descending order:" << endl; outputEnd(end); double res = solve(top, end); cout << endl << "Result of the expression:" << endl; cout << "(x[1] + x[n]) * (x[2] + x[n-1]) * ... * (x[n] + x[1]) = " << res << endl; cout << endl << "Press any key to continue..." << endl; _getch(); return 0; }
true
f1175796054dca055118e4f7e16588db7b6c3233
C++
adambloniarz/CAGe
/cage_src/cost.cpp
UTF-8
3,387
2.53125
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 Adam Bloniarz, Jonathan Terhorst, Ameet Talwalkar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <sstream> #include <cmath> #include <limits> #include "cost.h" #define PI 3.1415926535 using namespace std; namespace cage { inline double binom_loglik(int N, int K, double p) { if (p <= 0.0 || p >= 1.0) { return 0; } else { return(K * log(p) + (N - K) * log(1.0 - p)); } } double cost(const SuffStats& stats) { if (stats.L == 0) { return 0; } long L = stats.L; /* ------------------------- 1) Read starts - lambda ------------------------- */ double llik_starts; // Deal with the case where there are no read starts at all if (stats.N == 0) { llik_starts = 0; } else { llik_starts = -(double)stats.N + stats.N * log((double)stats.N / L); } /* ------------------------- 2) Mutations - gamma 3) Errors - epsilon ------------------------- */ // Mutations double gamma = (double)stats.N_SNPs / L; double llik_SNPs = binom_loglik(L, stats.N_SNPs, gamma); // Errors double epsilon = (stats.tot_bases == 0) ? 0.0 : (double)stats.tot_errors / stats.tot_bases; double llik_errors = binom_loglik(stats.tot_bases, stats.tot_errors, epsilon); // Indels double iota = (stats.tot_bases == 0) ? 0.0 : (double)stats.indels / stats.tot_bases; double llik_indels = binom_loglik(stats.tot_bases, stats.indels, iota); // Zero mapq double zeta = (stats.N == 0) ? 0.0 : (double)stats.zero_mapq / stats.N; double llik_zero_mapq = binom_loglik(stats.N, stats.zero_mapq, zeta); /* ------------------------- 4) Insert size calcs ------------------------- */ // loglik is (without constants which don't matter): // // -0.5 * (pow(x - mu, 2) / sigmasq + log(sigmasq)); // // loglik for all points when mu, sigmasq are set to MLE // // sum_x [ -0.5 * (pow(x - mu, 2) / sigmasq + log(sigmasq)) ] // // = -0.5 * ( sum_x [ pow(x - mu, 2) / sigmasq ] + n * log(sigmasq) ) // // = -0.5 * ( n - 1 + n * log(sigmasq) ) // // = -0.5 * n * (1 + log(sigmasq)), again dropping constants. double llik_inserts; if (stats.n_inserts > 1) { double mu = (double)stats.inserts_sum / stats.n_inserts; // cout << stats.inserts_sumsq << " " << stats.inserts_sum << " " << stats.n_inserts << endl; double sigmasq = ((double)stats.inserts_sumsq - pow(mu, 2)) / (stats.n_inserts - 1); llik_inserts = -0.5 * stats.n_inserts * (1.0 + log(sigmasq)); } else { llik_inserts = 0; } // Note: llik_inserts is not used return -1.0*(llik_starts + llik_SNPs + llik_indels + llik_errors + llik_zero_mapq); } }
true
fee8384484cdc87cb215a1028b4f860e9fa50c31
C++
facundososagonzales/pa-2021-lab6
/class/Usuario.cpp
UTF-8
797
3.09375
3
[]
no_license
#include "../class/Usuario.h" Usuario::Usuario(){} Usuario::Usuario(string nombre, string imagenUrl, string email, string password){ this->nombre=nombre; this->imagenUrl=imagenUrl; this->email=email; this->password=password; } string Usuario::getnombre() { return this->nombre; } void Usuario::setnombre(string nombre) { this->nombre=nombre; } string Usuario::getimagenUrl() { return this->imagenUrl; } void Usuario::setimagenUrl(string id) { this->imagenUrl=imagenUrl; } string Usuario::getemail() { return this->email; } void Usuario::setemail(string email) { this->email=email; } string Usuario::getpassword() { return this->password; } void Usuario::setpassword(string password) { this->password=password; } Usuario::~Usuario(){}
true
f5e8dfba63efba4c467ed0a7cae22ac7366622bb
C++
AlloSphere-Research-Group/AlloSystem
/allocore/examples/math/vector.cpp
UTF-8
6,132
4.03125
4
[ "BSD-3-Clause" ]
permissive
/* AlloCore Example: Vectors Description: This shows basic usage of the Vec class which represents an n-dimensional vector or n-vector. Author: Lance Putnam, 10/2012, putnam.lance@gmail.com */ #include "allocore/math/al_Vec.hpp" using namespace al; int main(){ // Lesson 1: Declarations // ========================================================================= { /* Vec is a template class with two template parameters: 1) N, the number of dimensions and 2) T, the element type. Here are some example declarations: */ Vec<3,float> vec3f; // 3-vector of floats Vec<2,int> vec2i; // 2-vector of ints Vec<11,double> vec11d; // 11-vector of doubles (!) Vec<1,float> vec1f; // 1-vector (scalar) with a float Vec<0,float> vec0f; // even 0-vectors are allowed, for completeness /* For convience, some common types are predefined: */ // 2-vector 3-vector 4-vector { Vec2f v; } { Vec3f v; } { Vec4f v; } // float { Vec2d v; } { Vec3d v; } { Vec4d v; } // double { Vec2i v; } { Vec3i v; } { Vec4i v; } // int } // Lesson 2: Constructors // ========================================================================= /* Vec has many different kinds of constructors. Here are some examples: */ { Vec3f x; // Initialize to {0, 0, 0} Vec3f a(1); // Initialize to {1, 1, 1} Vec3f b(1,2,3); // Initialize to {1, 2, 3} Vec2f c(4,5); // Initialize to {4, 5} Vec4f d(6,7,8,9); // Init'ing with scalars works up to 4-vectors Vec2d e(c); // Initialize from vector to {4, 5} Vec3f f(c, 6); // Initialize from vector and scalar to {4,5,6} /* Vec can be initialized from C-arrays: */ float arr2[] = {1,2}; Vec2f g(arr2); // Initialize from C-array, sizes match Vec2i h(arr2); // The C-array and vector can be different types /* Sizes can be different, but the C-array must be longer. Only the first n elements are copied. */ float arr3[] = {3,4,5}; Vec2f i(arr3); /* It is also possible to specify a stride amount through the C-array */ float arr8[] = {0,1,2,3,4,5,6,7}; Vec3f l(arr8, 2); // Initialize to {0, 2, 4} Vec3f m(arr8, 3); // Initialize to {0, 3, 6} } // Lesson 3: Acccessing Elements // ========================================================================= /* All vectors know their size (number of elements): */ { Vec3f a; a.size(); // Returns '3' } /* Access is accomplished using the normal array access operator: */ { Vec3f a(7,2,5); a[0]; // Access element 0 a[2]; // Access element 2 } /* For 1-, 2-, 3-, and 4-vectors, it is possible to use symbolic names. The symbols 'x', 'y', 'z', and 'w' are used to access elements 0, 1, 2, and 3, respectively. E.g.: */ { Vec2f b(1,2); b.x = b.y; // Results in {2, 2} Vec3f c(1,2,3); c.x = c.y = c.z; // Results in {3, 3, 3} Vec4f d(1,2,3,4); d.x = d.y = d.z = d.w; // Results in {4, 4, 4, 4} } /* The 'set' family of methods make it easy to set multiple elements at once: */ { Vec3f a, b; a.set(1,2,3); // Sets 'a' to {1, 2, 3} b = 1; // Sets 'b' to {1, 1, 1} a = b; // Sets 'a' to {1, 1, 1} Vec2f c(9,1); a.set(c, 3); // Sets 'a' to {9, 1, 3} float arr[] = {1,7,2,8,3,9}; a.set(arr); // Sets 'a' to {1, 7, 2} a.set(arr,2); // Sets 'a' to {1, 2, 3} by using a stride of 2 } /* It is easy to obtain subvectors, contiguous parts of a larger vector: */ { Vec4f a(7,5,0,2); a.sub<2>(0); // Returns 2-vector {7, 5} a.sub<2>(2); // Returns 2-vector {0, 2} a.sub<3>(1); // Returns 3-vector {5, 0, 2} } /* It is also possible to "swizzle", that is, obtain a new vector comprised of arbitrary elements from a particular vector: */ { Vec3f a(9,3,7); a.get(0,0,0); // Returns {9, 9, 9} a.get(2,1,0); // Returns {7, 3, 9} a.get(1,0); // Returns {3, 9} } // Lesson 4: Arithmetic // ========================================================================= /* Like expected of any good vector, Vec has many arithemtic operators defined: */ { Vec3f a(2,6,4); -a; // Returns {-2, -6, -4} a + 1; // Returns {3, 7, 5} a - 1; // Returns {1, 5, 3} a * 3; // Returns {6, 18, 12} a / 4; // Returns {0.5, 1.5, 1} a += 1; // Sets 'a' to {3, 7, 5} a -= 1; // Sets 'a' to {2, 6, 4} a *= 2; // Sets 'a' to {4,12, 8} a /= 2; // Sets 'a' to {2, 6, 4} } /* Operations between vectors are element-wise: */ { Vec3f a(2,6,4); Vec3f b(4,1,2); a + b; // Returns {6, 7, 6} a - b; // Returns {-2, 5, 2} a * b; // Returns {8, 6, 8} a / b; // Returns {0.5, 6, 2} a += b; // Sets 'a' to {6, 7, 6} a -= b; // Sets 'a' to {2, 6, 4} a *= b; // Sets 'a' to {8, 6, 8} a /= b; // Sets 'a' to {2, 6, 4} } /* Some comparison operators are provided: */ { Vec3f a(2,6,4); Vec3f b(2,2,2); Vec3f c(2,6,4); a == b; // Returns 'false' a == c; // Returns 'true' a != b; // Returns 'true' a != c; // Returns 'false' } // Lesson 5: Vector Functions // ========================================================================= /**/ { Vec2f v(3,4); v.mag(); // Returns 5, the magnitude of the vector v.magSqr(); // Returns 25, the magnitude squared v.normalize(); // Sets magnitude to 1 without changing the // vector's direction; the map a <- a / a.mag(). v.normalize(0.5); // Sets magnitude to 0.5 without changing the // direction v.normalized(); // Returns closest vector on unit sphere Vec3f A( 1, 2, 3); Vec3f B( 3,-2, 0); A.dot(B); // Returns -1 (=1*3 + 2*-2 + 3*0); // the dot product of A and B A.product(); // Returns 6 (= 1*2*3), the product of all elems B.sum(); // Returns 1 (= 3+-2+0), the sum of all elems cross(A, B); // Returns cross product A x B (3-vectors only) angle(A, B); // Returns angle, in radians, between A and B dist(A, B); // Returns Euclidean distance between A and B; // same as (A-B).mag() min(A, B); // Returns {1,-2, 0}; minimum values between A and B max(A, B); // Returns {3, 2, 3}; maximum values between A and B } }
true
cacfb7c91b73fa420106057ec980609eb74ba4f5
C++
sculg/TestOne
/TestOne/TestOne/main.cpp
UTF-8
13,186
3.390625
3
[ "MIT" ]
permissive
// // main.cpp // // Created by lg on 2019/7/27. // Copyright © 2019 sculg. All rights reserved. // #include <iostream> #include <vector> #include <map> #include <string> #include <stack> #include <queue> #include <list> using namespace std; struct ListNode { ListNode* next; int val; }; struct BinaryTreeNode { int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int searchBin(int array[],int low,int high,int target) { if (array == nullptr || low > high) { return -1; } while (low <= high) { int middle = low + (high-low)/2; if (array[middle] == target) { std::cout<<low<<endl; std::cout<<high<<endl; return middle; } else if (array[middle] > target) { high = middle-1; } else { low = middle+1; } } return -1; } int StrToInt(char *string) { int num = 0; if (string == NULL || *string == '\0') { return -1; } char *temp = string; int flag = 1; if (*temp == '+') { flag = 1; temp++; } else if (*temp == '-') { flag = -1; temp++; } while (*temp !='\0') { if(*temp >='0' && *temp <= '9' ) { num = num*10 + *temp - '0'; } else { return -1; } temp++; } return num*flag; } void InsertBST(TreeNode* &t, int key) { TreeNode* temp = NULL; //先判断节点是否存在,如果不存在,则新建节点 if (t == NULL) { temp = new TreeNode(0); temp->left = temp->right = NULL; temp->val = key; t = temp; return; } //新插入的点总是叶子节点,不能插在中间 if (key < t->val) { InsertBST(t->left, key);//key小,则插入左子树 } else if(key > t->val) { InsertBST(t->right, key);//key大,则插入右子树,key等于根节点则不插入 } } //创建二叉排序树,data是数组名,n是数组长度 TreeNode* CreateBiTree(TreeNode* tree,int data[],int n) { for (int i = 0; i < n; i++) { InsertBST(tree, data[i]); } return tree; } //删除二叉树,tree为根节点 void DelBiTree(TreeNode* tree) { if (tree) { DelBiTree(tree->left); DelBiTree(tree->right); delete tree; } } //先序遍历 void PreOrder(TreeNode* tree) { if (tree) { cout << tree->val << " "; PreOrder(tree->left); PreOrder(tree->right); } } //中序遍历 void InOrder(TreeNode* tree) { if (tree) { InOrder(tree->left); cout << tree->val << " "; InOrder(tree->right); } } //后续遍历 void PostOrder(TreeNode* tree) { if (tree) { PostOrder(tree->left); PostOrder(tree->right); cout << tree->val << " "; } } TreeNode* insertIntoBST(TreeNode* root, int val) { if(!root) return new TreeNode(val); if(val > root -> val) root -> right = insertIntoBST(root -> right, val); else root -> left = insertIntoBST(root -> left, val); return root; } //B是否是A的子集 bool isSub(vector<int> arrA, vector<int> arrB) { int lengthA = arrA.size(); int lengthB = arrB.size(); if(lengthA < lengthB || arrA[lengthA - 1] < arrB[lengthB - 1]) { return false; } int i = 0,j = 0; while (i < lengthA && j < lengthB) { if(arrA[i] == arrB[j]) { i++; j++; } else if (arrA[i] < arrB[j]) { i++; } else { return false; } } return true; } void reverseStr(string &str, int start, int end) { if(str.size() == 0) { return; } char temp = str[start]; str[0] = str[end]; str[end] = temp; reverseStr(str,++start,--end); } vector<int> findMaxAndMin(vector<int> &arr) { vector<int> result; if(arr.size() == 0) { return result; } if(arr.size() == 1) { result.push_back(arr[0]); result.push_back(arr[0]); return result; } for(int i = 0;i<arr.size();i = i + 2) { if(arr[i] < arr[i+1]) { int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } int max = 0; for (int i = 0; i < arr.size(); i = i+2) { if(max < arr[i]) { max = arr[i]; } } int min = 0; for (int i = 1; i < arr.size(); i = i+2) { if(min > arr[i]) { min = arr[i]; } } result.push_back(max); result.push_back(min); return result; } int minNumber(vector<int> arr,int target) { if(arr.size() == 0) { return 0; } vector<int> dp(target + 1,-1); for (int i = 0; i<arr.size(); i++) { if(arr[i] == target) { return 1; } dp[arr[i]] = 1; } for (int i = 1; i<=target; i++) { for (int j = 0; j < arr.size(); j++) { if(i-arr[j] >= 0 && dp[i-arr[j]] != -1) { if(dp[i] == -1 || dp[i] > dp[i-arr[j]] + 1) { dp[i] = dp[i-arr[j]] + 1; } } } } return dp[target]; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { double result; vector<int> temp; int nums1Length = nums1.size(); int nums2Length = nums2.size(); int leftIndex = 0; for (int i = 0; i < nums2Length; i++) { while(leftIndex < nums1Length && nums1[leftIndex] <= nums2[i]) { temp.push_back(nums1[leftIndex]); leftIndex++; } temp.push_back(nums2[i]); } while(leftIndex < nums1Length) { temp.push_back(nums1[leftIndex]); leftIndex++; } if(temp.size() & 0x01) { result = temp[temp.size()/2]; } else { result = (double)(temp[(temp.size() + 1)/2] + temp[(temp.size() - 1)/2])/(double)2.0; } return result; } bool isValid(string s) { if(s.empty()) { return true; } stack<char> stack; for (int i = 0; i < s.size(); i++) { if(s[i] == '(' || s[i] == '{' || s[i] =='[') { stack.push(s[i]); } else { if(stack.empty()){ return false; } char tem = stack.top(); if((s[i] == ')' && tem == '(')|| (s[i] == ']' && tem == '[')||(s[i] == '}' && tem == '{')) { stack.pop(); } else { return false; } } } if (stack.size() == 0) { return true; } else { return false; } } int strStr(string haystack, string needle) { if(haystack.size() < needle.size()) { return -1; } if(needle.size() == 0) { return 0; } int needleIndex = 0; int firstIndex = -1; for (int i = 0;i < haystack.size();i++) { if(needleIndex < needle.size()) { if(haystack[i] == needle[needleIndex]) { if(firstIndex == -1) { firstIndex = i; } needleIndex++; } else { if(firstIndex != -1) { i = firstIndex; firstIndex = -1; needleIndex = 0; } } } } return needleIndex == needle.size()? firstIndex : -1;; } void quickSort(vector<int>& nums, int start, int end) { if(nums.size() == 0 || start >= end) { return; } int i = start; int j = end; int temp = nums[start]; while(i < j) { while(i<j && nums[j] >= temp) { j--; } while(i<j && nums[i] <= temp) { i++; } swap(nums[i],nums[j]); } swap(nums[i],temp); quickSort(nums,start,i-1); quickSort(nums,i+1,end); } void nextPermutation(vector<int>& nums) { int rightIndex = nums.size()-1; while(rightIndex > 0) { if(nums[rightIndex] <= nums[rightIndex-1]) { rightIndex--; } else { break; } } if(rightIndex == 0) { int p = 0; int q = nums.size()-1; while(p<=q) { swap(nums[p++],nums[q--]); } return; } int j = rightIndex; int slected = nums[rightIndex - 1]; while(nums[j] >= slected) { j++; if(j == nums.size()) break; } while(nums[j-1] == slected) { j--; } swap(nums[rightIndex-1],nums[j-1]); quickSort(nums,rightIndex,nums.size()-1); } string countAndSay(int n) { vector<string> dp(n+1); dp[0] = "1"; for(int i = 1; i < n ; i++) { string str = dp[i-1]; string tem = ""; int count = 1; char temchar = str[0]; for(int j = 1;j <=str.size();j++) { if(str[j] != temchar) { tem.append(to_string(count)); tem.push_back(temchar); temchar = str[j]; count = 1; } else { count++; } } dp[i] = tem; } return dp[n-1]; } int firstMissingPositive(vector<int>& nums) { sort(nums.begin(),nums.end()); int startOf1 = -1; for(int i = 0;i < nums.size(); i++) { if(nums[i] <= 0) { continue; } else if(startOf1 == -1) { startOf1 = i; } else { if(nums[i] != nums[startOf1] + 1) { return nums[startOf1] + 1; } else { startOf1 = i; } } } return nums[startOf1] + 1; } }; // 如:[1, [2, [ [3, 4], 5], 6], 7] => [1, 2, 3, 4, 5, 6, 7] //[1, [2, [ [3, 4], 5], 6], 7] => [1, 2, 3, 4, 5, 6, 7] // //} int minEditCost(string str1, string str2, int ic, int dc, int rc) { // write code here int m = str1.size(); int n = str2.size(); int dp[m+1][n+1]; dp[0][0] = 0; for(int i = 1;i <= m; i++) { dp[i][0] = dp[i-1][0] + dc; } for(int j = 1;j <= n; j++) { dp[0][j] = dp[0][j-1] + ic; } for(int i = 1;i <= m; i++) { for(int j = 1;j <= n; j++) { if(str1[i-1] == str2[j-1]) { dp[i][j] = dp[i-1][j-1]; } else { int ins = dp[i][j-1] + ic; int del = dp[i-1][j] + dc; int rep = dp[i-1][j-1] + rc; dp[i][j] = min(ins,min(del,rep)); } } } return dp[m][n]; } int main(int argc, const char * argv[]) { int array[] = {1,2,0}; // int array2[] = {2}; // int len = sizeof(array)/sizeof(int); // cout<<"The orginal array are:"<<endl; // for(int i=0; i<len; ++i) // { // cout<< array[i] << " "; // } // cout<<endl; vector<int> vect1(array,array+sizeof(array)/sizeof(int)); // vector<int> vect2(array2,array2+sizeof(array2)/sizeof(int)); int result = Solution().firstMissingPositive(vect1); // int result = Solution().GetUglyNumber_Solution(20);"mississippi""pi" // cout<<result<<endl; // int arr[] = {1,3,4,5,16,17,29}; // int index = Solution().searchBin(arr, 0, 6, 4); // std::cout<<index<<endl; // struct student { // char a; // int b; //// int c; // }; // char str[] = "12p4"; // int intAfterConvert = Solution().StrToInt(str); // std::cout<<sizeof(student)<<endl; // insert code here... // - return 0; }
true
33ca8c153669593ff921f8f42521b7942e654dbd
C++
jeffersonfr/jhanoi
/hanoi-v01.cpp
UTF-8
1,585
3.578125
4
[]
no_license
#include <iostream> #include <vector> #include <cmath> #include <string> std::vector<int> tower1, tower2, tower3; void move(int from, int to) { int value; if (from == 1) { value = tower1.back(); tower1.pop_back(); } else if (from == 2) { value = tower2.back(); tower2.pop_back(); } else if (from == 3) { value = tower3.back(); tower3.pop_back(); } if (to == 1) { tower1.push_back(value); } else if (to == 2) { tower2.push_back(value); } else if (to == 3) { tower3.push_back(value); } // std::cout << ": " << "ABC"[from - 1] << " to " << "ABC"[to - 1] << std::endl; } int main(int argc, char **argv) { if (argc < 2) { std::cout << "usage: " << argv[0] << " <number of disks>" << std::endl; return 0; } size_t disks = std::stoi(argv[1]), // number of disks steps = std::pow(2, disks) - 1; // define the bigest value to platform tower1.push_back(999); tower2.push_back(999); tower3.push_back(999); // stack the initial disks for (size_t i=0; i<disks; i++) { tower1.push_back(disks - i); } for (size_t i=0; i<steps; i++) { if ((i % 3) == 0) { // 101 if (tower1.back() < tower3.back()) { move(1, 3); } else { move(3, 1); } } else if ((i % 3) == 1) { // 110 if (tower1.back() < tower2.back()) { move(1, 2); } else { move(2, 1); } } else if ((i % 3) == 2) { // 011 if (tower2.back() < tower3.back()) { move(2, 3); } else { move(3, 2); } } } return 0; }
true
d4d7ce414227107df4af7461bb5428fda6cdf082
C++
7thsanctum/Intro_to_Graphics_Coursework
/GFX_Submission/GFX_Submission/texture.h
UTF-8
320
2.578125
3
[]
no_license
#pragma once #include <string> #include <GL\glew.h> #include <glm\glm.hpp> class texture { private: GLuint _image; std::string _filename; public: texture(const std::string& filename); ~texture(); GLuint getImageID() const { return _image; } bool create(); bool create(int width, int height, glm::vec4* data); };
true
9741e340f900f96b81beeceb78efc539f873d3b2
C++
xwudennis/Algorithms
/QuickSort/QuickSort.cpp
UTF-8
4,459
3.375
3
[]
no_license
#include <iostream> #include <vector> #include <fstream> #include <sstream> #include <string> #include <stdlib.h> #include <stdio.h> #include <time.h> using namespace std; void readFile(char * fileName, int ** nArray, int * nArraySize) { ifstream infile(fileName); string line; vector<int> nVector; int i = 0; while (getline(infile, line)) { istringstream iss(line); int n; iss >> n; nVector.push_back(n); i++; } *nArray = new int [nVector.size()]; *nArraySize = nVector.size(); copy(nVector.begin(), nVector.end(), *nArray); } // Using the first (left) element as the pivot element for quick sort void partionLP(int * A, int l, int r, unsigned long long * comparisonLP) { // A is the input array. l is the left boundary; r is the right boundary. if(r - l >= 1) { int p = A[l]; // Let p be the first element in the array int i = l + 1; for(int j = l + 1; j <= r; j++) { if (A[j] < p) { int a = A[j]; A[j] = A[i]; A[i] = a; i++; } } int b = A[l]; A[l] = A[i-1]; A[i-1] = b; *comparisonLP += r - l; partionLP(A, l, i-2, comparisonLP); partionLP(A, i, r, comparisonLP); } } // Using the last (right) element as the pivot element for quick sort void partionRP(int * A, int l, int r, unsigned long long * comparisonRP) { // A is the input array. l is the left boundary; r is the right boundary. if(r - l >= 1) { int p = A[r]; // Let p be the last element in the array. Exchange A[r] and A[l] A[r] = A[l]; A[l] = p; int i = l + 1; for(int j = l + 1; j <= r; j++) { if (A[j] < p) { int a = A[j]; A[j] = A[i]; A[i] = a; i++; } } int b = A[l]; A[l] = A[i-1]; A[i-1] = b; *comparisonRP += r - l; partionRP(A, l, i-2, comparisonRP); partionRP(A, i, r, comparisonRP); } } void moveMedianToFirst(int * A, int l, int r) { int *first = A + l; int *last = A + r; int *middle = A + (l + r)/2; int median; if(r - l >=2) { if((*middle > *first && *middle < *last) || (*middle > *last & *middle < *first)) { // middle is the median, exchange middle with first median = *middle; *middle = *first; *first = median; } else if((*first > *middle && *first < *last) || (*first > *last & *first < *middle)) { // first is the median // do nothing } else if ((*last > *first && *last < *middle) || (*last > *middle && *last < *first)) { // last is the median, exchange last with first median = *last; *last = *first; *first = median; } } else if(r - l == 1) { // Only two numbers in the array // Do nothing } } // Using the middle element as the pivot element for quick sort void partionMP(int * A, int l, int r, unsigned long long * comparisonMP) { // A is the input array. l is the left boundary; r is the right boundary. if(r - l >= 1) { moveMedianToFirst(A, l, r); // Exhange the median to the first int p = A[l]; // Let p be the first element in the array int i = l + 1; for(int j = l + 1; j <= r; j++) { if (A[j] < p) { int a = A[j]; A[j] = A[i]; A[i] = a; i++; } } int b = A[l]; A[l] = A[i-1]; A[i-1] = b; *comparisonMP += r - l; partionMP(A, l, i-2, comparisonMP); partionMP(A, i, r, comparisonMP); } } void outputArray(int * nArray, int nArraySize, unsigned long long comparisonLP, unsigned long long comparisonRP, unsigned long long comparisonMP) { ofstream fout("output.txt"); if(!fout || !fout.good()) { cout<<"ERROR! Unable to open .txt file for writing!\n"; } else { fout << "comparisonLP " << comparisonLP << endl << endl; fout << "comparisonRP " << comparisonRP << endl << endl; fout << "comparisonMP " << comparisonMP << endl << endl; for(int i = 0; i < nArraySize; i++) { fout << nArray[i] << endl; } } } int main() { int * nArray; int nArraySize; clock_t t; unsigned long long comparisonLP = 0; unsigned long long comparisonRP = 0; unsigned long long comparisonMP = 0; // 1. Read the file readFile("QuickSort.txt", &nArray, &nArraySize); // 2. Quick Sort // Uncomment only one of partionLP, partionRP and partionMP to do quick sort and count the comparisons made for quick sort. //partionLP(nArray, 0, nArraySize - 1, &comparisonLP); partionRP(nArray, 0, nArraySize - 1, &comparisonRP); //partionMP(nArray, 0, nArraySize - 1, &comparisonMP); // 3. Output Comparisons outputArray(nArray, nArraySize, comparisonLP, comparisonRP, comparisonMP); return 0; }
true
e31d99a45f87173f741b3df088d7c1ac82d90ee1
C++
tonnac/TCP_IP
/NonBlockServer/P_Server.cpp
UHC
1,862
2.625
3
[]
no_license
#include "Util.h" int main(void) { const u_short port = 15000; const char* IPAddr = "127.0.0.1"; if (WSAStart() != 0) { return -1; } SOCKET ListenSock = socket(AF_INET, SOCK_STREAM, 0); if (ListenSock == INVALID_SOCKET) { return -1; } SOCKADDR_IN addr; memset(&addr, 0, sizeof(addr)); addr.sin_port = htons(port); addr.sin_family = AF_INET; InetPtonA(AF_INET, IPAddr, &addr.sin_addr.s_addr); int iRet = bind(ListenSock, (sockaddr*)&addr, sizeof(SOCKADDR_IN)); if (iRet == SOCKET_ERROR) { return -1; } iRet = listen(ListenSock, SOMAXCONN); if (iRet == SOCKET_ERROR) { return -1; } u_long on = TRUE; ioctlsocket(ListenSock, FIONBIO, &on); bool bConnect = true; SOCKET ClientSock; SOCKADDR_IN ClientAddr; memset(&ClientAddr, 0, sizeof(SOCKADDR_IN)); int ClientAddrlen = sizeof(SOCKADDR_IN); while (g_UserList.size() != 2) { ClientSock = accept(ListenSock, (sockaddr*)&ClientAddr, &ClientAddrlen); if (ClientSock == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { break; } } else { User user; user.sock = ClientSock; user.addr = ClientAddr; g_UserList.push_back(user); int SendByte = send(user.sock, "ȳ\n", strlen("ȳ\n"), 0); } } User_Iter iter = g_UserList.begin(); while (true) { char buffer[256] = { 0, }; int RecvByte = recv(iter->sock, buffer, sizeof(buffer), 0); buffer[strlen(buffer)] = '\n'; if (RecvByte == SOCKET_ERROR) { if (WSAGetLastError() != WSAEWOULDBLOCK) { break; } ++iter; if (iter == g_UserList.end()) { iter = g_UserList.begin(); } continue; } std::cout << " ڿ: " << buffer; for (int i = 0; i < g_UserList.size(); ++i) { send(g_UserList[i].sock, buffer, strlen(buffer), 0); } } closesocket(ListenSock); if (WSAClean() != 0) { return -1; } return 0; }
true
b541fe4d58ec8494231ec29c1437b250f42ee0c9
C++
V1t4/JumpMan
/src/Instrucciones.cpp
UTF-8
645
2.625
3
[]
no_license
#include "Instrucciones.h" Instrucciones::Instrucciones() { //Se agrega un margen margen.setTexture(Global::t_margen); } void Instrucciones::actualizar (Juego & j) { if(sf::Keyboard::isKeyPressed(sf::Keyboard::Return)){//Con enter se inicia un nivel Global::nivActual=1; j.cambiarEscena(new Nivel()); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) j.cambiarEscena(new Menu());//Con space se vuelve al menu } void Instrucciones::dibujar (sf::RenderWindow & ventana) { ventana.clear(sf::Color(0,127,0)); ventana.draw(margen); for (sf::Text linea : Global::txt_instrucciones) ventana.draw(linea); ventana.display(); }
true
a5136e37c696c4f0ee2ec9e84051051cdc99e0d0
C++
shakirali2244/associates
/CPSC_2150/3_SList/testSList.cpp
UTF-8
475
2.5625
3
[]
no_license
/* * testSList.cpp * * Created on: Oct 19, 2016 * Author: Shakir */ #include "SList.h" #include "SList.cpp" #include <iostream> using namespace std; int main(){ SList<int> tmp; Node<int>* test = tmp.getheader(); int level = 0; tmp.insert(3); tmp.insert(2); tmp.insert(3); tmp.insert(5); tmp.insert(7); tmp.insert(33); tmp.insert(77); tmp.insert(44); while(test != nullptr){ cout << test->key << endl; test = test->next[level]; } return 0; }
true
9ec0647ce197c952e9ad1ccc60fda181744789c0
C++
carlixyz/Galaxy-Olympics_ULL
/proyecto-galaxy-olympics/auroraengine/AuroraEngine/AuroraEngine/Game/Scene/Player.h
ISO-8859-3
1,266
2.734375
3
[]
no_license
#ifndef PLAYER_H #define PLAYER_H #include "../../Libraries/MathLib/MathLib.h" #include "Object.h" enum ePlayerState { ePS_Crash = 0, ePS_Running, ePS_Turbo, ePS_StandBy }; class cPlayer : public cObject { public: cPlayer() { meType = ePlayer; meState = ePS_Running; mfFloatingSwap = 0.0f; mfTurboBoost = 10.0f; mfDelay = 0.0f; mbSfx = false; } void Update( float lfTimestep ); void Render(); void SetCollisionObject(cObject *CollisionObject); inline void AddTurbo(void){ this->mfTurboBoost += 0.35f * (mfTurboBoost < 100.0f ) ; } void Reset(); inline void SetInitialPos(cVec3 lvInitialPos){ InitialPos = lvInitialPos;} float & GetTurboAmount() {return mfTurboBoost;} private: float mfFloatingSwap ; // float para Alternar entre flotar ascendiendo/descendiendo float mfTurboBoost; float mfDelay; bool mbSfx; bool mbCrash; cMatrix mAuxMatrix ; // Matriz de composicin para transformacines del player. cMatrix tmpMatrix; // Matriz Temporal para bloquear el avance del player cMatrix mAwesomeMatrix; // Matriz para accidente cObject *mCollisionObject; ePlayerState meState; cVec3 InitialPos; void Advance(float & lfTimestep, float lfSpeed); void Control(float & lfTimestep, float lfSpeed); }; #endif
true
512aede2469ba37209eada3a829ed15338b8ca7b
C++
tim-fa/Yugen
/Yugen/Events/Event.cpp
UTF-8
857
2.78125
3
[]
no_license
// STL #include <string> // Local #include "Event.h" namespace Yugen::Events { Event::Event(EventType type) : m_Type(type) , m_Handled(false) { } std::string Event::toString() const { return "Event: "; } std::string Event::typeToString(EventType type) { switch (type) { case EventType::KeyPressed: return "KeyPressed"; case EventType::KeyReleased: return "KeyReleased"; case EventType::KeyTyped: return "KeyTyped"; case EventType::MousePressed: return "MousePressed"; case EventType::MouseReleased: return "MouseReleased"; case EventType::MouseMoved: return "MouseMoved"; case EventType::MouseScrolled: return "MouseScrolled"; case EventType::WindowResize: return "WindowResize"; case EventType::WindowClose: return "WindowClose"; default: return "INVALID"; } } }
true
add661489642e4ebaef2fef6487f1c5a23897e54
C++
Natureal/Codeforces
/Templates/t_dsu.cpp
UTF-8
247
2.890625
3
[]
no_license
// Remember to define the range of fa[]. const int maxn = ; int fa[maxn]; int Find(int x){ return fa[x] == x ? x : fa[x] = Find(fa[x]); } void Union(int a, int b){ int x = Find(a), y = Find(b); if(x != y){ fa[x] = y; } }
true
88c16ca6c1c44ddf11f5e404e047d9d20601bd1d
C++
Justforfunc1/net
/reactor_test/main.cpp
UTF-8
1,694
2.65625
3
[]
no_license
#include <sys/socket.h> #include <arpa/inet.h> #include <iostream> #include <errno.h> #include "reactor.h" #include "event_handler.h" #include "accept_handler.h" #include "event.h" #include <fcntl.h> //设置非阻塞模式 int setnonblocking( int fd ) { int ret = fcntl(fd, F_SETFL, O_NONBLOCK ); if(ret < 0) printf("Setnonblocking error : %d\n", errno); return 0; } int main() { int listenfd = -1; struct sockaddr_in seraddr; seraddr.sin_family = AF_INET; seraddr.sin_port = htons(8008); seraddr.sin_addr.s_addr = htonl(INADDR_ANY); // seraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //创建监听sock if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cerr << "socket error " << errno << std::endl; exit(-1); } //设置成非阻塞模式 if(setnonblocking(listenfd) == -1) { printf("Setnonblocking Error : %d\n", errno); exit( EXIT_FAILURE ); } //允许端口重用 int on = 1; if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)) < 0) { printf("Setsockopt Error : %d\n", errno); exit( EXIT_FAILURE ); } //绑定监听sock if (bind(listenfd, (struct sockaddr*)&seraddr, sizeof(seraddr)) < 0) { std::cerr << "bind error " << errno << std::endl; exit(-2); } //设置监听最大数 if (listen(listenfd, 5) < 0) { std::cerr << "listen error " << errno << std::endl; exit(-3); } Reactor& actor = Reactor::get_instance(); EventHandler* handler = new AcceptHandler(listenfd); actor.regist(handler, AcceptEvent); actor.dispatch(100); return 0; }
true
2c64fb09d1d1cfd068934a5b744aef017b49aa2e
C++
danyaljj/combinatorialCircuitOptimization
/visualizer/digital_gate.h
UTF-8
1,624
3.28125
3
[]
no_license
#ifndef DIGITAL_GATE_H #define DIGITAL_GATE_H #include <vector> class digital_gate { public: digital_gate(); digital_gate( int g_pos_x, int g_pos_y, int g_input1_x, int g_input1_y, int g_input2_x, int g_input2_y, int g_type ); // get methods : int get_gate_pos_x(); int get_gate_pos_y(); int get_gate_input1_x(); int get_gate_input1_y(); int get_gate_input2_x(); int get_gate_input2_y(); int get_gate_type(); // int get_input1_connection_number(); int get_input2_connection_number(); std::vector<int> get_output_connection_number(); //set methods: void set_gate_pos_x(int a); void set_gate_pos_y(int a); void set_gate_input1_x(int a); void set_gate_input1_y(int a); void set_gate_input2_x(int a); void set_gate_input2_y(int a); void set_gate_type(int a); // void set_input1_connection_number( int a ); void set_input2_connection_number( int a ); void set_output_connection_number( std::vector<int> a ); /*! gate types: 0:WIRE 1:NOT 2:AND 3:OR 4:NAND 5:NOR 6:XOR 7:XNOR */ int gate_pos_x; // this is because of sort algorithm. private: int gate_pos_y; int gate_input1_x; int gate_input1_y; int gate_input2_x; int gate_input2_y; int gate_type; int input1_connection_number; int input2_connection_number; std::vector<int> output_connection_number; }; #endif // DIGITAL_GATE_H
true
47c56428be1505a808de6119c2d312dd453c95fe
C++
uniyalprashant9/CodeSpace
/Strings/stringSortLexicoGraphicOrder.cpp
UTF-8
538
3.1875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool compare (const string &s1, const string &s2) // & is used to prevent object copy which save time //const is used to prevent modifications { return s1.length()<s2.length(); } int main(){ string str[]={"hello","boi","yo","boii"}; for(int i=0;i<4;i++){ sort(str.begin(),str.end(),compare) // or sort(str,str+4,compare); } for(int i=0;i<4;i++){ cout<<str[i]<<endl; } return 0; }
true
b6c1a365ef66d2aa5358f7ebe7dd2b3ed81a0b8f
C++
tody411/MeshViewerFramework
/src/core/GreedyFlooding.h
UTF-8
861
2.71875
3
[ "MIT" ]
permissive
//! GreedyFlooding definition. /*! \file GreedyFlooding.h \author Tody \date 2016/03/10 */ #ifndef GREEDYFLOODING_H #define GREEDYFLOODING_H #include "Eigen/Dense" #include "Mesh.h" //! GreedyFlooding implementation. class GreedyFlooding { public : //! Constructor. GreedyFlooding ( Mesh* mesh ) : _mesh ( mesh ), _tol ( 0.1 ), _maxClusterSize ( 4000 ) {} //! Destructor. virtual ~GreedyFlooding() {} //! Set Tolerance. void setTolerance ( double tol ) { _tol = tol;} //! Set FaceNormal. void setFaceNormal ( const Eigen::MatrixXd& N ) { _N = N;} void flood ( Eigen::VectorXi& clusterIDs ); void floodSeed ( int seedFaceID, int clusterID, Eigen::VectorXi& clusterIDs ); private: double _tol; int _maxClusterSize; Eigen::MatrixXd _N; Mesh* _mesh; }; #endif
true
12e1f3c14f5bc7f624116e8893a1fbf2e79c5dae
C++
Graham-ella/leetcode
/每日一题/lc/lc6Z字形变换.cpp
UTF-8
658
2.953125
3
[]
no_license
class Solution { public: string convert(string s, int numRows) { string res = ""; int n = numRows; int len = s.size(); if (n == 1 || len == 1) { return s; } for (int k = 0; k < n; k++) { if (k == 0 || k == n - 1) { for (int i = k; i < len; i += (2 * n - 2)) { res += s[i]; } }//第0行和第n-1行比较特殊 else { for (int p = k, q = 2 * n - 2 - k; p < len || q < len; p += (2 * n - 2), q += (2 * n - 2)) { if(p<len)res += s[p]; if(q<len)res += s[q]; } } } return res; } };
true
ea5aa61594fe4b49beca927e03aa01d2df22c68d
C++
reckeyzhang/private-data-objects
/common/packages/block_store/block_store.h
UTF-8
4,482
2.578125
3
[ "CC-BY-4.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-public-domain", "Zlib", "MIT" ]
permissive
/* Copyright 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "pdo_error.h" #include "types.h" namespace pdo { namespace block_store { /** * Initialize the block store - must be called before performing gets/puts * Primary expected use: python / untrusted side * * @return * Success (return PDO_SUCCESS) - Block store ready to use * Failure (return nonzero) - Block store is unusable */ pdo_err_t BlockStoreInit(); /** * Gets the size of a block in the block store * Primary expected use: ocall * * @param inKey pointer to raw key byte array * @param inKeySize length of inKey * @param outValueSize size (in # bytes) of value will be written here * * @return * Success (return 0) - outValueSize set to the number of bytes of raw value * Failure (return nonzero) - outValueSize undefined */ int BlockStoreHead( const uint8_t* inKey, const size_t inKeySize, size_t* outValueSize ); /** * Gets a block from the block store * Primary expected use: ocall * * @param inKey pointer to raw key byte array * @param inKeySize length of inKey * @param outValue buffer where value should be copied * @param inValueSize length of caller's outValue buffer * * @return * Success (return 0) - outValue contains the requested block * Failure (return nonzero) - outValue unchanged */ int BlockStoreGet( const uint8_t* inKey, const size_t inKeySize, uint8_t *outValue, const size_t inValueSize ); /** * Puts a block into the block store * Primary expected use: ocall * * @param inKey pointer to raw key byte array * @param inKeySize length of inKey * @param inValue pointer to raw value byte array * @param inValueSize length of inValue * * @return * Success (return 0) - key->value stored * Failure (return nonzero) - block store unchanged */ int BlockStorePut( const uint8_t* inKey, const size_t inKeySize, const uint8_t* inValue, const size_t inValueSize ); /** * Gets the size of a block in the block store * Primary expected use: python / untrusted side * * @param inKey raw bytes * * @return * Block present - return size of block * Block not present - return -1 */ int BlockStoreHead( const ByteArray& inKey ); /** * Gets a block from the block store * Primary expected use: python / untrusted side * * @param inKey raw bytes * @param outValue raw bytes * * @return * Success (return 0) - outValue resized and contains block data * Failure (return nonzero) - outValue unchanged */ pdo_err_t BlockStoreGet( const ByteArray& inKey, ByteArray& outValue ); /** * Puts a block into the block store * Primary expected use: python / untrusted side * * @param inKey raw bytes * @param inValue raw bytes * * @return * Success (return PDO_SUCCESS) - key->value stored * Failure (return nonzero) - block store unchanged */ pdo_err_t BlockStorePut( const ByteArray& inKey, const ByteArray& inValue ); } /* contract */ } /* pdo */
true
f54149bc321805540747b17c6c02abb9a0457cb3
C++
QPKJEDL/deskgame
/NiuNiu_zhubo_mod/Structure.h
UTF-8
726
2.515625
3
[]
no_license
#ifndef __STRUCTURE_H__ #define __STRUCTURE_H__ #include <QLabel> #include <string> using namespace std; typedef struct{ int num = 0; int color = -1; bool hua = false; QLabel *label; string face = ""; }CARD; typedef struct node{ int num;// 0 代表闲家1 3代表庄家 struct node *next; CARD data[5] = {}; }FOURMAN; // players //分针走一轮,时针走一格 typedef struct{ int man = 0;//第几个玩家 int num = 0;//第几张牌 void increase(){ if(++man == 4){ num++; man = 0; } } }NUMBER; typedef struct{ int paiXing; CARD biggest; }PAIRESULT; typedef struct{ string face; bool win; }LABELRESULT; #endif
true
201b54a28735fc9d35508fcd42965ebf3ee1d02a
C++
mdmccra/programming-1
/GardenStore.cpp
UTF-8
1,124
3.84375
4
[]
no_license
#include <iostream> using namespace std; int main() { int x, y; cout << "How many plants are you purchasing? "; cin >> x; // user enters amount of plants being purchased cout << endl; if (x < 0) // no negative integers because the value of plants cannot be negative cout << "That's impossible!"; else if (x > 25) { y = (6 * (x - 25)) + 200; // price per plant multiplied by the amount of plants after 25 plus the cost of the first 25 plants cout << "That will cost $" << y; } else if (x <= 25 && x > 15) { y = (7 * (x - 15)) + 130; // price per plant multiplied by the amount of plants between 15 and 25 (inclusive) plus the cost of the first 15 plants cout << "That will cost $" << y; } else if (x <= 15 && x > 5) { y = (8 * (x - 5)) + 50; // price per plant multiplied by the amount of plants between 5 and 15 (inclusive) plus the cost of the first 5 plants cout << "That will cost $" << y; } else if (x <= 5 && x > 0) { y = 10 * x; // price per plant multiplied by the amount of plants for the first 5 plants cout << "That will cost $" << y; } }
true
b9a693d279f29b1673888c24c17d4ca9da7ee409
C++
Angelo768/Exercicios-em-C
/Classes/NumeroRacional.h
UTF-8
384
3.46875
3
[]
no_license
#include <iostream> using namespace std; class NumeroRacional{ public: NumeroRacional(int numerator, int denominator); int num1; int num2; }; NumeroRacional::NumeroRacional(int numerator, int denominator){ num1 = numerator; if(denominator <= 0){ cout << "Denominador inválido!" " por isso será inicializado com 1" << endl; num2 = 1; }else{num2 = denominator;} }
true
5da0e31f3c9395da3b2a156ef239bf2ef312ef58
C++
aashima91/ParallelHMM-master
/src/hmm.cc
UTF-8
605
2.515625
3
[]
no_license
#include "hmm.hh" #include <iostream> using namespace std; void HMM::print(){ /*cout<<"# of States "<<noOfStates<<endl; cout<<"# of Symbols "<<noOfSymbols<<endl; cout<<"Transition Probability"<<std::endl; cout<<transMat; cout<<"Emission Probability"<<endl; for(int idx=0;idx<noOfStates;idx++){ cout<<emissionMat[idx]; } cout<<"Pi"<<std::endl; cout<<piMat;*/ } void HMM::precomputeTransientC(){ for (int k=0;k<noOfSymbols;k++){ Matrix C(noOfStates,noOfStates); transMat.diagmult(emissionMat[k],C); transientC.push_back(C); //cout << "C" << k+1 << ":" << endl << C; } }
true
9a52f1e97496eadb193d710facec3960920c7afd
C++
rbangamm/raytracer
/shapes.h
UTF-8
4,811
3.265625
3
[]
no_license
// Header file for geometry classes #include <iostream> #include <cstdlib> #include <cmath> #include <fstream> template<typename T> class Vec3 { public: T x, y, z; Vec3() : x(T(0)), y(T(0)), z(T(0)) {} Vec3(T xx) : x(xx), y(xx), z(xx) {} Vec3(T xx, T yy, T zz) : x(xx), y(yy), z(zz) {} Vec3& normalize() { T nor2 = length2(); if (nor2 > 0) { T invNor = 1 / sqrt(nor2); x *= invNor, y *= invNor, z *= invNor; } return *this; } Vec3<T> operator * (const T &f) const { return Vec3<T>(x * f, y * f, z * f); } Vec3<T> operator * (const Vec3<T> &v) const { return Vec3<T>(x * v.x, y * v.y, z * v.z); } T dot(const Vec3<T> &v) const { return x * v.x + y * v.y + z * v.z; } Vec3<T> operator - (const Vec3<T> &v) const { return Vec3<T>(x - v.x, y - v.y, z - v.z); } Vec3<T> operator + (const Vec3<T> &v) const { return Vec3<T>(x + v.x, y + v.y, z + v.z); } Vec3<T>& operator += (const Vec3<T> &v) { x += v.x, y += v.y, z += v.z; return *this; } Vec3<T>& operator *= (const Vec3<T> &v) { x *= v.x, y *= v.y, z *= v.z; return *this; } bool operator != (const Vec3<T> &v) const { return x != v.x || y != v.y || z != v.z; } Vec3<T> operator - () const { return Vec3<T>(-x, -y, -z); } T length2() const { return x * x + y * y + z * z; } T length() const { return sqrt(length2()); } friend std::ostream & operator << (std::ostream &os, const Vec3<T> &v) { os << "[" << v.x << " " << v.y << " " << v.z << "]"; return os; } }; typedef Vec3<float> Vec3f; class Shape { public: Shape( const Vec3f &sc, const float &refl, const float &transp, const Vec3f &ec) : surfaceColor(sc), emissionColor(ec), transparency(transp), reflection(refl) {} virtual bool intersect( const Vec3f &rayorig, const Vec3f &raydir, float &t0, float &t1) const = 0; Vec3f surfaceColor, emissionColor; /// surface color and emission (light) float transparency, reflection; /// surface transparency and reflectivity }; class Sphere : public Shape { public: Vec3f center; /// position of the sphere float radius, radius2; /// sphere radius and radius^2 Sphere( const Vec3f &c, const float &r, const Vec3f &sc, const float &refl = 0, const float &transp = 0, const Vec3f &ec = 0) : center(c), radius(r), radius2(r * r), Shape(sc, refl, transp, ec) { } bool intersect(const Vec3f &rayorig, const Vec3f &raydir, float &t0, float &t1) const { Vec3f l = center - rayorig; float tca = l.dot(raydir); if (tca < 0) return false; float d2 = l.dot(l) - tca * tca; if (d2 > radius2) return false; float thc = sqrt(radius2 - d2); t0 = tca - thc; t1 = tca + thc; return true; } }; class Box : public Shape { public: Vec3f min; Vec3f max; Vec3f add = min + max; Vec3f center = Vec3f(add.x / 2.0, add.y / 2.0, add.z / 2.0); Box( const Vec3f &min, const Vec3f &max, const Vec3f &sc, const float &refl = 0, const float &transp = 0, const Vec3f &ec = 0) : min(min), max(max), Shape(sc, refl, transp, ec) { } bool intersect(const Vec3f &rayorig, const Vec3f &raydir, float &t0, float &t1) const { float tmin; float tmax; float tymin; float tymax; float tzmin; float tzmax; if (1 / raydir.x >= 0) { tmin = (min.x - rayorig.x) / raydir.x; tmax = (max.x - rayorig.x) / raydir.x; } else { tmin = (max.x - rayorig.x) / raydir.x; tmax = (min.x - rayorig.x) / raydir.x; } if (1 / raydir.y >= 0) { tymin = (min.y - rayorig.y) / raydir.y; tymax = (max.y - rayorig.y) / raydir.y; } else { tymin = (max.y - rayorig.y) / raydir.y; tymax = (min.y - rayorig.y) / raydir.y; } if ((tmin > tymax) || (tymin > tmax)) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; if (1 / raydir.z >= 0) { tzmin = (min.z - rayorig.z) / raydir.z; tzmax = (max.z - rayorig.z) / raydir.z; } else { tzmin = (max.z - rayorig.z) / raydir.z; tzmax = (min.z - rayorig.z) / raydir.z; } if ((tmin > tzmax) || (tzmin > tmax)) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; if (false) { std::cout << "Max: " << std::to_string(tmax) << "\n"; std::cout << "Min: " << std::to_string(tmin) << "\n"; } t0 = tmin; t1 = tmax; return true; } };
true