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
94078993fa81377f659d9139a5e2a0e8377d14db
C++
Morzkat/AgendaOfContact
/main.cpp
UTF-8
7,392
3.8125
4
[]
no_license
#include <iostream> #include <fstream> using namespace std; // struct basic for a contact struct contact { string name; string lastName; string phoneNumer; struct contact* next; }; // first and last contact objects contact* firstItem = NULL; contact* lastItem = NULL; //file fstream file; // class for action class Action { public: static void addContact(contact *newContact); static void showContacts(); static void menu(); static void createContact(); static void deleteContact(); static void alterContact(); }; class FileManager { public: static void WriteInFile(string,string,string); static void getAllFileContent(); }; void FileManager::getAllFileContent() { string line; ifstream file("contacts.txt", ios::in); if(file.is_open()) { while (getline(file,line)) { cout << line << "\n"; } file.close(); } } void FileManager::WriteInFile(string name, string lastName, string phoneNumber) { //open the txt file file.open("contacts.txt", ios::app); //write in the file file << "--------------------------------------------------------\n"; file << "Nombre del contacto: " << name << "\n"; file << "Apellido del contacto: " << lastName << "\n"; file << "Numero de telefo del contacto: " << phoneNumber << "\n"; file << "---------------------------------------------------------\n"; file.close(); } void Action::createContact() { //create a new struct for a contact contact* newContact = new (struct contact); //get the data for the contact cout << "Introduzca el nombre del contacto:"; string contactName; cin >> contactName; cout << "Introduza el apellido del contacto:"; string contactLastName; cin >> contactLastName; cout << "Introduza el numero de telefono del contacto:"; string contactPhoneNumber; cin >> contactPhoneNumber; //add the data to the contact newContact->name = contactName; newContact->lastName = contactLastName; newContact->phoneNumer = contactPhoneNumber; //add the contact to the list of items addContact(newContact); cout << "Contacto Agregado\n"; } void Action::addContact(contact *newContact) { //last contact like null newContact->next = NULL; //doesn't exist first contact if (firstItem == NULL) { //the first and the last contact are the same firstItem = newContact; lastItem = newContact; } //exist a first contact else { //the last(penultimate) contact the next contact is the newContact(latest created) lastItem->next = newContact; //the new last contact is the latest created lastItem = newContact; } } void Action::showContacts() { //show the items if there are if (firstItem != NULL) { contact *i = firstItem; while (i != NULL) { cout << "--------------------------------------------------------\n"; cout << "Nombre del contacto: " << i->name << "\n"; cout << "Apellido del contacto: " << i->lastName << "\n"; cout << "Numero de telefo del contacto: " << i->phoneNumer << "\n"; cout << "---------------------------------------------------------\n"; FileManager::WriteInFile(i->name, i->lastName, i->phoneNumer); i = i->next; } } //there aren't items else { cout << "La lista esta vacia\n"; } cout << "Contactos previamente guardados\n"; FileManager::getAllFileContent(); } void Action::menu() { //menu for the options cout << "Elige una de las opciones\n"; cout << "1- Listar contactos y guardar\n"; cout << "2- Nuevo Contacto\n"; cout << "3- Modificar un contacto \n"; cout << "4- Eliminar contacto\n"; cout << "5- Salir\n"; cout << "Elija una opcion =>"; } void Action::deleteContact() { //if there are contact show the items to choose which delete if (firstItem != NULL) { cout << "Selecciona el contacto a eliminar\n"; //show items showContacts(); //get the contact name string name; cin >> name; //object for the loop contact* i = firstItem; //the current contact contact* currentItem = firstItem; //the previous contact contact* previousItem = NULL; //the loop for search the contact while(i != NULL && i->name != name) { previousItem = currentItem; currentItem = currentItem->next; i = i->next; } //the first the contact will be delete if (previousItem == NULL) { firstItem = currentItem->next; delete currentItem; } //other contact will be delete if (currentItem->name == name) { firstItem->next = currentItem->next; delete currentItem; cout << "Contacto elimando\n"; } } else { cout << "La lista esta vacia o no se encontro el contacto"; } } void Action::alterContact() { //if there are contact show the items to choose which delete if (firstItem != NULL) { string newName; string newLastName; string newPhoneNumber; cout << "Selecciona el contacto a modificar\n"; //show items showContacts(); //get the contact name string name; cin >> name; //object for the loop contact* i = firstItem; //the current contact contact* currentItem = firstItem; //the previous contact contact* previousItem = NULL; cout << "Nuevo nombre del contacto: "; cin >> newName; cout << "Nuevo apellido del contacto: "; cin >> newLastName; cout << "Nuevo numero de telefono del contacto: "; cin >> newPhoneNumber; //the loop for search the contact while(i != NULL && i->name != name) { previousItem = currentItem; currentItem = currentItem->next; i = i->next; } //the first the contact will be alter if (previousItem == NULL) { currentItem->name = newName; currentItem->lastName = newLastName; currentItem->phoneNumer = newPhoneNumber; firstItem = currentItem; } //other contact will be alter if (currentItem->name == name) { currentItem->name = newName; currentItem->lastName = newLastName; currentItem->phoneNumer = newPhoneNumber; firstItem = currentItem; } cout << "Contacto modificado\n"; } else { cout << "La lista esta vacia o no se encontro el contacto"; } } int main() { // switch opcion short op; do { Action::menu(); cin >> op; switch (op) { case 1 : Action::showContacts(); break; case 2: Action::createContact(); break; case 3 : Action::alterContact(); break; case 4: Action::deleteContact(); break; } }while (op < 5); }
true
a738023f5d3e405091e941cd07908416c7db8148
C++
dacaraway/coin_collector
/thing.h
UTF-8
1,440
3.015625
3
[ "Apache-2.0" ]
permissive
#ifndef THING_H #define THING_H #include <QGraphicsPixmapItem> #include <QKeyEvent> #include <QPixmap> /** The Thing class is the base class for all of the objects in the game @author Daria Caraway @post BlueShell @post RedShell @post GreenShell @post Coin @post GreenMush */ class Thing: public QGraphicsPixmapItem { public: /** Constructor for a Thing, sets pixMap, x and y, sets initial position. @param pm Pixmap pointer to show picture @param nx Initial x cooridinate to set position @param ny Initial y coordinate to set poition **/ Thing(QPixmap *pm, int nx, int ny); /** A pure virtual function for the things to move **/ virtual void move() = 0; /** A pure virtual function for the things to return their power identifier **/ virtual int executePower() = 0; /** A pure virtual function for the things to set their x **/ void setX(int nx); /** A pure virtual function for the things to set their y **/ void setY(int ny); /** @return A boolean to help when iterating for collisions **/ bool getCheck(); protected: /** The current x location of the thing **/ double x; /** The current y location of the thing **/ double y; /** The current x velocity of the thing **/ double vX; /** The current y velocity of the thing **/ double vY; /** The bool returned in getCheck() **/ bool goodCheck; /** The current picture set to the object **/ QPixmap* pixMap; }; #endif
true
e279772a5ba63d460028526aa6543f9c7749f2e5
C++
clivic/C-code-examples
/_Course Assignments/_Data Structures and Algorithm/Integral and Float TypeSize/Integral and Float TypeSize.cpp
UTF-8
1,616
3.671875
4
[ "MIT" ]
permissive
//****************************************************************** // AllTypeSize program // This program can get the size of nearly all of integral and float data types // in the computer which executes the program // and the output results are aligned //****************************************************************** #include <iostream> #include <climits> #include <iomanip> //for set width using namespace std; int main() { cout << left; cout << setw(30) << "float type size is: " << sizeof(float) << endl; //float type cout << setw(30) << "double type size is: " << sizeof(double) << endl; //double type cout << setw(30) << "long double type size is: " << sizeof(long double) << endl; //longdouble type cout << setw(30) << "char type size is: " << sizeof(char) << endl; //char type cout << setw(30) << "short type size is: " << sizeof(short) << endl; //short type cout << setw(30) << "int type size is: " << sizeof(int) << endl; //int type cout << setw(30) << "long type size is: " << sizeof(long) << endl; //long type cout << setw(30) << "bool type size is: " << sizeof(bool) << endl; //long type cout << setw(30) << "unsigned char type size is: " << sizeof(unsigned char) << endl; //unsigned char type cout << setw(30) << "unsigned short type size is: " << sizeof(unsigned short) << endl; //unsigned char type cout << setw(30) << "unsigned int type size is: " << sizeof(unsigned int) << endl; //unsigned char type cout << setw(30) << "unsigned long type size is: " << sizeof(unsigned long) << endl; //unsigned char type return 0; }
true
8b1525d389cac28394f9a2ae8cc5bea7e9d9fd16
C++
dchodge1/pair-programming
/CISP1010/pp2/2c.cpp
UTF-8
491
3.515625
4
[]
no_license
/* * File: 2c.cpp * Author: David Hodge * Date: 2019/02/01 * Conditionals to print various life milestones */ #include <iostream> using namespace std; int main() { int age; cout << "Please enter your age: "; cin >> age; if (age < 18) { cout << "Nothing\n"; } else { if (age >= 18) cout << "You can vote\n"; if (age >= 21) cout << "You can drink\n"; if (age >= 25) cout << "You can rent a car\n"; if (age >= 65) cout << "You can collect social security\n"; } return 0; }
true
c458ca84858536909dcb334cfda1e303e6a5bc2b
C++
Leputa/Leetcode
/cpp/1.Two Sum.cpp
UTF-8
578
2.953125
3
[]
no_license
#include <vector> #include <unordered_map> #include <iostream> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int>ret; unordered_map<int, int>map; for(int i=0; i<nums.size(); i++){ map[target- nums[i]] = i; } for (int i=0; i<nums.size(); i++){ if (map.count(nums[i]) != 0 && map[nums[i]] != i){ ret.push_back(i); ret.push_back(map[nums[i]]); break; } } return ret; } };
true
7070f410b8e96faa86a4642455eb6d8990c6655e
C++
laurent-xu/CLFTPL
/tests/thread_bomb.hh
UTF-8
1,221
2.859375
3
[ "MIT" ]
permissive
#pragma once #include <future> #include <functional> #include <thread> namespace thread_bomb { class thread_pool { public: thread_pool(int) {} template <class Function, class... Args> std::future<typename std::result_of<Function(int, Args...)>::type> push(Function&& f, Args&&... args) { auto f_ = std::async(std::launch::async, f, 0, std::forward<Args>(args)...); return f_; } template <class Function> std::future<typename std::result_of<Function(int)>::type> push(Function&& f) { auto f_ = std::async(std::launch::async, f, 0); return f_; } template <class Function, class... Args> std::future<typename std::result_of<Function(Args...)>::type> push_no_index(Function&& f, Args&&... args) { auto f_ = std::async(std::launch::async, f, std::forward<Args>(args)...); return f_; } template <class Function> std::future<typename std::result_of<Function()>::type> push_no_index(Function&& f) { auto f_ = std::async(std::launch::async, f); return f_; } }; }
true
1a8e96adf9cc14d2227a0cf28fd72d634dfedf2b
C++
jaylamb/picolibrary-microchip-megaavr
/include/picolibrary/microchip/megaavr/asynchronous_serial.h
UTF-8
6,946
2.59375
3
[ "Apache-2.0" ]
permissive
/** * picolibrary-microchip-megaavr * * Copyright 2020-2021, Andrew Countryman <apcountryman@gmail.com> and the * picolibrary-microchip-megaavr contributors * * 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. */ /** * \file * \brief picolibrary::Microchip::megaAVR::Asynchronous_Serial interface. */ #ifndef PICOLIBRARY_MICROCHIP_MEGAAVR_PERIPHERAL_ASYNCHRONOUS_SERIAL_H #define PICOLIBRARY_MICROCHIP_MEGAAVR_PERIPHERAL_ASYNCHRONOUS_SERIAL_H #include <cstdint> #include "picolibrary/asynchronous_serial.h" #include "picolibrary/microchip/megaavr/peripheral/usart.h" #include "picolibrary/result.h" #include "picolibrary/void.h" /** * \brief Microchip megaAVR asynchronous serial facilities. */ namespace picolibrary::Microchip::megaAVR::Asynchronous_Serial { /** * \brief Microchip megaAVR asynchronous serial clock configuration. */ struct Clock_Configuration { /** * \brief The clock generator operating speed. */ Peripheral::USART::Operating_Speed operating_speed; /** * \brief The clock generator scaling factor. */ std::uint16_t scaling_factor; }; /** * \brief Microchip megaAVR asynchronous serial basic transmitter. * * \tparam Data_Type The integral type used to hold the data to be transmitted. */ template<typename Data_Type> class Basic_Transmitter { public: /** * \brief The integral type used to hold the data to be transmitted. */ using Data = Data_Type; /** * \brief Constructor. */ constexpr Basic_Transmitter() noexcept = default; /** * \brief Constructor. * * \param[in] usart The USART to be used by the transmitter. * \param[in] data_bits The desired number of data bits. * \param[in] parity The desired parity mode. * \param[in] stop_bits The desired number of stop bits. * \param[in] clock_configuration The desired clock generator configuration. */ Basic_Transmitter( Peripheral::USART & usart, Peripheral::USART::Data_Bits data_bits, Peripheral::USART::Parity parity, Peripheral::USART::Stop_Bits stop_bits, Clock_Configuration const & clock_configuration ) noexcept : m_usart{ &usart } { m_usart->disable(); m_usart->configure( data_bits, parity, stop_bits, clock_configuration.operating_speed, clock_configuration.scaling_factor ); } /** * \brief Constructor. * * \param[in] source The source of the move. */ constexpr Basic_Transmitter( Basic_Transmitter && source ) noexcept : m_usart{ source.m_usart } { source.m_usart = nullptr; } Basic_Transmitter( Basic_Transmitter const & ) = delete; /** * \brief Destructor. */ ~Basic_Transmitter() noexcept { disable(); } /** * \brief Assignment operator. * * \param[in] expression The expression to be assigned. * * \return The assigned to object. */ auto & operator=( Basic_Transmitter && expression ) noexcept { if ( &expression != this ) { disable(); m_usart = expression.m_usart; expression.m_usart = nullptr; } // if return *this; } auto operator=( Basic_Transmitter const & ) = delete; /** * \brief Initialize the transmitter's hardware. * * \return Success. */ auto initialize() noexcept -> Result<Void, Void> { m_usart->enable_transmitter(); return {}; } /** * \brief Transmit data. * * \param[in] data The data to transmit. * * \return Success. */ auto transmit( Data data ) noexcept -> Result<Void, Void> { while ( not m_usart->transmit_buffer_empty() ) {} m_usart->transmit( data ); return {}; } private: /** * \brief The USART used by the transmitter. */ Peripheral::USART * m_usart{}; /** * \brief Disable the transmitter. */ void disable() noexcept { if ( m_usart ) { m_usart->disable_transmitter(); } // if } }; /** * \brief Microchip megaAVR asynchronous serial transmitter. * * \tparam Data_Type The integral type used to hold the data to be transmitted. */ template<typename Data_Type> class Transmitter : public ::picolibrary::Asynchronous_Serial::Transmitter<Basic_Transmitter<Data_Type>> { public: using ::picolibrary::Asynchronous_Serial::Transmitter<Basic_Transmitter<Data_Type>>::Transmitter; }; /** * \brief Microchip megaAVR asynchronous serial 8 data bits, no parity bit, 1 stop bit * (8-N-1) transmitter. */ class Transmitter_8_N_1 : private Transmitter<std::uint8_t> { public: using Transmitter<std::uint8_t>::Data; /** * \brief Constructor. */ constexpr Transmitter_8_N_1() noexcept = default; /** * \brief Constructor. * * \param[in] usart The USART to be used by the transmitter. * \param[in] clock_configuration The desired clock generator configuration. */ Transmitter_8_N_1( Peripheral::USART & usart, Clock_Configuration const & clock_configuration ) noexcept : Transmitter<std::uint8_t>{ usart, Peripheral::USART::Data_Bits::_8, Peripheral::USART::Parity::NONE, Peripheral::USART::Stop_Bits::_1, clock_configuration } { } /** * \brief Constructor. * * \param[in] source The source of the move. */ constexpr Transmitter_8_N_1( Transmitter_8_N_1 && source ) noexcept = default; Transmitter_8_N_1( Transmitter_8_N_1 const & ) = delete; /** * \brief Destructor. */ ~Transmitter_8_N_1() noexcept = default; /** * \brief Assignment operator. * * \param[in] expression The expression to be assigned. * * \return The assigned to object. */ auto operator=( Transmitter_8_N_1 && expression ) noexcept -> Transmitter_8_N_1 & = default; auto operator=( Transmitter_8_N_1 const & ) = delete; using Transmitter<std::uint8_t>::initialize; using Transmitter<std::uint8_t>::transmit; }; } // namespace picolibrary::Microchip::megaAVR::Asynchronous_Serial #endif // PICOLIBRARY_MICROCHIP_MEGAAVR_PERIPHERAL_ASYNCHRONOUS_SERIAL_H
true
4815c1d1f10c5f52b00ef8cab6767fcf63faba17
C++
dek-an/Step-Diploma
/core/src/YUVImage.cpp
UTF-8
11,175
2.796875
3
[]
no_license
#include "../include/core/YUVImage.h" #include "../include/core/typedefs.h" #include <cassert> #include <memory> namespace core { // ---------------------------------------------------------- // -------------- YUVImage::iterator ------------------------ // ---------------------------------------------------------- YUVImage::iterator::iterator(const unsigned char* data, int width, int height, int divisor, int step) : m_ptr(data) , m_currPtr(data) , m_width(width) , m_height(height) , m_divisor(divisor) , m_step(step) , m_i(0) , m_j(0) { } unsigned char YUVImage::iterator::operator*() { return *m_currPtr; } YUVImage::iterator YUVImage::iterator::operator+=(int nShift) { m_j = (m_j + nShift) % m_width; m_i += nShift / m_width; assert(m_i < m_height); movePtr(); return *this; } void YUVImage::iterator::operator++() { ++m_j %= m_width; if (!m_j) ++m_i; movePtr(); } YUVImage::iterator YUVImage::iterator::operator++(int) { iterator it(*this); ++(*this); return it; } bool YUVImage::iterator::operator==(const YUVImage::iterator& it) { return (it.m_currPtr == m_currPtr); } bool YUVImage::iterator::operator!=(const YUVImage::iterator& it) { return (it.m_currPtr != m_currPtr); } YUVImage::iterator operator+(const YUVImage::iterator& it, int shift) { YUVImage::iterator res(it); res += shift; return res; } void YUVImage::iterator::movePtr() { int shift = ((m_i / m_divisor) * (m_width / m_divisor) + m_j / m_divisor) * m_step; m_currPtr = m_ptr + shift; } // ---------------------------------------------------------- // ------------------------ YUVImage ------------------------ // ---------------------------------------------------------- YUVImage::YUVImage(ImageFormat format, int width, int height, const unsigned char* data/* = 0*/) : m_format(format) , m_width(width) , m_height(height) , m_dataSize(3 * width * height) , m_yData(data) , m_uData(data) , m_vData(data) , m_yEnd(data) , m_uEnd(data) , m_vEnd(data) , m_yDivisor(1) , m_uDivisor(1) , m_vDivisor(1) , m_yStep(1) , m_uStep(1) , m_vStep(1) , m_dataOwner(false) , m_binaryMask(height, width) , m_integral(width, height) , m_maskBorder(5) { applyFormat(); } YUVImage::~YUVImage() { if (m_dataOwner) delete m_yData; } unsigned char YUVImage::operator()(char comp, int row, int col) const { switch(comp) { case 'y': case 'Y': return *(beginY() + row * m_width + col); break; case 'u': case 'U': return *(beginU() + row * m_width + col); break; case 'v': case 'V': return *(beginV() + row * m_width + col); break; default: return 0; } } const unsigned char* YUVImage::data() const { return m_yData; } YUVImage* YUVImage::scaled(int scale) const { if (scale <= 1) return 0; if ( m_width / scale < 2 || m_height / scale < 2 ) return 0; switch (m_format) { case GRAY: return scaledGRAY(scale); case YUV: return scaledYUV(scale); case YUV420P: return scaledYUV420P(scale); case YUV420SP: return scaledYUV420SP(scale); default: assert(false); return 0; } } YUVImage* YUVImage::scaledGRAY(int scale) const { assert(GRAY == m_format); return 0; } YUVImage* YUVImage::scaledYUV(int scale) const { assert(YUV == m_format); return 0; } YUVImage* YUVImage::scaledYUV420P(int scale) const { assert(YUV420SP == m_format); return 0; } YUVImage* YUVImage::scaledYUV420SP(int scale) const { assert(YUV420SP == m_format); const int scale2 = scale * scale; const float part = 1.f / scale2; const int scWidth = m_width / scale; const int scHeight = m_height / scale; const int scYDataSize = scWidth * scHeight; const int thYDataSize = m_width * m_height; const int scDataSize = (3 * scYDataSize) >> 1; uchar* scData = new uchar[scDataSize]; YUVImage* scImage = new YUVImage(m_format, scWidth, scHeight, scData); scImage->m_dataOwner = true; scImage->setMaskBorder(m_maskBorder); // y data const uchar* thIt = m_yData; const uchar* thE = m_yData + thYDataSize; const uchar* scE = scData + scYDataSize; int iter = 0; for(uchar* scIt = scData; scIt != scE && thIt != thE; ++scIt, ++iter) { thIt += m_width * (scale - 1) * ( iter && !(iter % scWidth) ); int scVal = 0; for (const uchar* thIE = thIt + scale; thIt != thIE; ++thIt) for (int i = 0, e = m_width * scale; i != e; i += m_width) scVal += *(thIt + i); *scIt = static_cast<uchar>(scVal * part); } // uv data iter = 1; const uchar* thUVIt = m_yData + thYDataSize; const uchar* thUVE = m_yData + m_dataSize; const uchar* scUVE = scData + scDataSize; bool isU = true; for (uchar* scUVIt = scData + scYDataSize; scUVIt != scUVE && thUVIt != thUVE; ++scUVIt, ++iter) { int scVal = 0; for (const uchar *thInnerIt = thUVIt, *thIE = thUVIt + scale + 2; thInnerIt != thIE; thInnerIt += 2) for (int i = 0, e = m_width * scale; i != e; i += m_width) scVal += *(thInnerIt + i); *scUVIt = static_cast<uchar>(scVal * part); thUVIt += isU + !isU * (2 * scale - 1) + !(iter % scWidth) * m_width * (scale - 1); isU = !isU; } return scImage; } void YUVImage::doBinaryMask(BinarizationFunction binFunc) { const YUVImageIterator yBegin = beginY(); const YUVImageIterator yEnd = endY(); const YUVImageIterator uBegin = beginU(); const YUVImageIterator uEnd = endU(); const YUVImageIterator vBegin = beginV(); const YUVImageIterator vEnd = endV(); YUVImageIterator yIt = yBegin; YUVImageIterator uIt = uBegin; YUVImageIterator vIt = vBegin; int i = 0; int j = 0; for (; yIt != yEnd && uIt != uEnd && vIt != vEnd; ++yIt, ++uIt, ++vIt) { int val = 0; if (i - m_maskBorder >= 0 && j - m_maskBorder >= 0 && i + m_maskBorder < m_height && j + m_maskBorder < m_width) // if not borders (if borders, val = 0; clean borders) { if ( binFunc(*yIt, *uIt, *vIt) ) val = 255; } m_binaryMask.set(i, j, val); m_integral.addVal(i, j, val); ++j %= m_width; if (!j) ++i; } } void YUVImage::smoothBinaryMask(int radius/* = 1*/) { int q = 1; const int b1 = 2; // error on the first layer; edit for (int i = 0; i < radius; ++i) q *= 2; const int error = b1 * (q - 1); // sum of the geometric progression const int kThreshold = (radius + 2) * (radius + 2) - 1 - error; const int rows = m_binaryMask.rows(); const int cols = m_binaryMask.cols(); for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) { // top left - (i1, j1); bottom right - (i2, j2). // i - row; j - column const int i1 = i - radius < 0 ? 0 : i - radius; const int i2 = i + radius >= rows ? rows - 1 : i + radius; const int j1 = j - radius < 0 ? 0 : j - radius; const int j2 = j + radius >= cols ? cols - 1 : j + radius; const int integralVal = m_integral(i2, j2) - m_integral(i1, j2) - m_integral(i2, j1) + m_integral(i1, j1); const int currentVal = m_binaryMask(i, j); if (currentVal && integralVal < error) m_binaryMask.set(i, j, 0); else if (!currentVal && integralVal >= kThreshold) m_binaryMask.set(i, j, 255); } } YUVImage::iterator YUVImage::beginY() const { return iterator(m_yData, m_width, m_height, m_yDivisor, m_yStep); } YUVImage::iterator YUVImage::endY() const { return iterator(m_yEnd, m_width, m_height, m_yDivisor, m_yStep); } YUVImage::iterator YUVImage::beginU() const { return iterator(m_uData, m_width, m_height, m_uDivisor, m_uStep); } YUVImage::iterator YUVImage::endU() const { return iterator(m_uEnd, m_width, m_height, m_uDivisor, m_uStep); } YUVImage::iterator YUVImage::beginV() const { return iterator(m_vData, m_width, m_height, m_vDivisor, m_vStep); } YUVImage::iterator YUVImage::endV() const { return iterator(m_vEnd, m_width, m_height, m_vDivisor, m_vStep); } void YUVImage::applyFormat() { switch (m_format) { case GRAY: m_dataSize /= 3; // = m_width * m_height; break; case YUV: //m_dataSize = 3 * width * height; break; case YUV420P: case YUV420SP: m_dataSize >>= 1; // = (3 * m_width * m_height) >> 1; break; default: assert(false); } if (!m_yData) { m_yData = new unsigned char[m_dataSize]; m_dataOwner = true; } switch (m_format) { case GRAY: { m_uData = m_yData; m_vData = m_yData; m_yEnd = m_yData + m_dataSize; m_uEnd = m_uData + m_dataSize; m_vEnd = m_vData + m_dataSize; break; } case YUV: { m_uData = m_yData + 1; m_vData = m_uData + 1; m_yEnd = m_yData + m_dataSize; m_uEnd = m_yEnd + 1; m_vEnd = m_uEnd + 1; // m_yDivisor = 1; // m_uDivisor = 1; // m_vDivisor = 1; m_yStep = 3; m_uStep = 3; m_vStep = 3; break; } case YUV420P: { const int imgSize = m_width * m_height; const int imgSizeDiv4 = imgSize >> 2; m_uData = m_yData + imgSize; m_vData = m_uData + imgSizeDiv4; m_yEnd = m_uData; m_uEnd = m_vData; m_vEnd = m_vData + imgSizeDiv4; //m_yDivisor = 1; m_uDivisor = 2; m_vDivisor = 2; //m_yStep = 1; //m_uStep = 1; //m_vStep = 1; break; } case YUV420SP: { const int imgSize = m_width * m_height; const int imgSizeDiv4 = imgSize >> 2; m_uData = m_yData + imgSize; m_vData = m_uData + 1; m_yEnd = m_uData; m_uEnd = m_yData + m_dataSize; m_vEnd = m_uEnd + 1; //m_yDivisor = 1; m_uDivisor = 2; m_vDivisor = 2; //m_yStep = 1; m_uStep = 2; m_vStep = 2; break; } } } } // namespace core
true
3db84b5ec6d6ec4e540dc6e6820b1ce773146ada
C++
cathreya/DS2
/A8/binSearch.h
UTF-8
753
3.328125
3
[]
no_license
#include <string.h> #include <vector> using namespace std; class binSearch{ public: template <class T> int binarySearch(const T obj, const vector<T> arr, int n){ int high= n-1; int low = 0; while(high>=low){ int mid = low + (high-low)/2; if(obj == arr[mid]){ return mid; } else if(obj < arr[mid]){ high = mid-1; } else{ low = mid+1; } } return -1; } int binarySearch(const char* obj, const vector<char*> arr, int n){ int high= n-1; int low = 0; while(high>=low){ int mid = low + (high-low)/2; if(strcmp(obj,arr[mid])==0){ return mid; } else if(strcmp(obj,arr[mid])<0){ high = mid-1; } else{ low = mid+1; } } return -1; } };
true
49a7ddb654bbdafb9424cc05d6b51e6155096515
C++
gal-rahamim/Dungeons-and-Dragons
/src/fightable/player/player.cpp
UTF-8
10,700
2.71875
3
[]
no_license
#include <random> #include "player.hpp" #include "sword.hpp" namespace d_d { std::unordered_map<std::string, Player::MF_ONE_ARG> Player::s_mf_dict_one_arg; std::unordered_map<std::string, Player::MF_ONE_ARG_CONST> Player::s_mf_dict_one_arg_const; std::unordered_map<std::string, Player::MF_TWO_ARG> Player::s_mf_dict_two_arg; Player::Player(const std::string& a_name, const std::shared_ptr<IRoom>& a_startingPosition, unsigned int a_starting_life, unsigned int a_starting_money) : IPlayer(a_name, a_starting_life, a_starting_money) , m_location(a_startingPosition) , m_sword(new Sword("niddle", 4, a_startingPosition, 20)) , m_shield() , m_keys() , m_direction(IRoom::NORTH) , m_starting_position(a_startingPosition) , m_starting_sword(m_sword) , m_starting_life(a_starting_life) , m_starting_money(a_starting_money) { s_mf_dict_one_arg.insert(std::make_pair("Forward", &Player::Forward)); s_mf_dict_one_arg.insert(std::make_pair("Backward", &Player::Backward)); s_mf_dict_one_arg.insert(std::make_pair("TurnRight", &Player::TurnRight)); s_mf_dict_one_arg.insert(std::make_pair("TurnLeft", &Player::TurnLeft)); s_mf_dict_one_arg_const.insert(std::make_pair("Describe", &Player::Describe)); s_mf_dict_one_arg_const.insert(std::make_pair("Open", &Player::Open)); s_mf_dict_one_arg_const.insert(std::make_pair("Close", &Player::Close)); s_mf_dict_one_arg_const.insert(std::make_pair("Lock", &Player::Lock)); s_mf_dict_one_arg_const.insert(std::make_pair("UnLock", &Player::UnLock)); s_mf_dict_one_arg_const.insert(std::make_pair("Where", &Player::Where)); s_mf_dict_one_arg_const.insert(std::make_pair("Look", &Player::Look)); s_mf_dict_two_arg.insert(std::make_pair("Take", &Player::Take)); s_mf_dict_two_arg.insert(std::make_pair("Fight", &Player::Fight)); } Player::~Player() { std::shared_ptr<IFightable> me; m_location->Exit(Name(), me); } static std::string directionToString(IRoom::Direction a_direction) { std::string ret; switch (a_direction) { case IRoom::NORTH : ret = "North"; break; case IRoom::SOUTH : ret = "South"; break; case IRoom::EAST : ret = "East"; break; case IRoom::WEST : ret = "West"; break; default: break; } return ret; } static void reverseDirection(IRoom::Direction& a_direction) { switch (a_direction) { case IRoom::NORTH : a_direction = IRoom::SOUTH; return; case IRoom::SOUTH : a_direction = IRoom::NORTH; return; case IRoom::EAST : a_direction = IRoom::WEST; return; case IRoom::WEST : a_direction = IRoom::EAST; return; default: break; } } static void right90(IRoom::Direction& a_direction) { switch (a_direction) { case IRoom::NORTH : a_direction = IRoom::EAST; return; case IRoom::SOUTH : a_direction = IRoom::WEST; return; case IRoom::EAST : a_direction = IRoom::SOUTH; return; case IRoom::WEST : a_direction = IRoom::NORTH; return; default: break; } } static void left90(IRoom::Direction& a_direction) { switch (a_direction) { case IRoom::NORTH : a_direction = IRoom::WEST; return; case IRoom::SOUTH : a_direction = IRoom::EAST; return; case IRoom::EAST : a_direction = IRoom::NORTH; return; case IRoom::WEST : a_direction = IRoom::SOUTH; return; default: break; } } void Player::Forward(std::string& a_out) { std::shared_ptr<IPassage> passage; m_location->Move(m_direction, passage); if(!passage) { a_out = "Can't move " + directionToString(m_direction) + " reached a wall"; return; } std::shared_ptr<IRoom> destRoom; if(passage->Pass(m_location, destRoom, a_out)) { std::shared_ptr<IFightable> me; m_location->Exit(Name(), me); destRoom->Enter(me); m_location = destRoom; return; } return; } void Player::Backward(std::string& a_out) { reverseDirection(m_direction); Forward(a_out); a_out = "You are now facing: " + directionToString(m_direction) + "\n" + a_out; } void Player::TurnRight(std::string& a_out) { right90(m_direction); a_out = "You are now facing: " + directionToString(m_direction); } void Player::TurnLeft(std::string& a_out) { left90(m_direction); a_out = "You are now facing: " + directionToString(m_direction); } void Player::Take(const std::string& a_objectName, std::string& a_out) { std::string getOutput; std::shared_ptr<IObject> obj; m_location->GetObject(a_objectName, obj, getOutput); if(!obj) { a_out = getOutput; return; } std::shared_ptr<ISword> sword = std::dynamic_pointer_cast<ISword>(obj); if(sword) { a_out = "Switching swords:\n" + getOutput + "\n"; std::string placeOutput; m_location->PlaceObject(m_sword, placeOutput); a_out += placeOutput; m_sword = sword; return; } std::shared_ptr<IShield> shield = std::dynamic_pointer_cast<IShield>(obj); if(shield) { if(m_shield) { a_out = "Switching shields:\n" + getOutput + "\n"; std::string placeOutput; m_location->PlaceObject(m_shield, placeOutput); a_out += placeOutput; return; } a_out = getOutput; m_shield = shield; return; } std::shared_ptr<Key> key = std::dynamic_pointer_cast<Key>(obj); if(key) { a_out = getOutput + "\nInserting key to chain"; m_keys.push_back(key); return; } } unsigned int Player::GetDefense() const { return m_shield ? m_shield->GetDefense() : 0; } unsigned int Player::GetAttack() const { return m_sword ? m_sword->GetStrength() : 0; } void Player::Fight(const std::string& a_name, std::string& a_out) { std::shared_ptr<IFightable> target; m_location->GetFightable(a_name, target); if(!target) { a_out = "No such victim was found in the room"; return; } else if(target.get() == this) { a_out = "You can't fight yourself O_O"; return; } unsigned int alpha = std::min((unsigned int)0, GetAttack() - target->GetDefense()); unsigned int beta = std::min((unsigned int)0, target->GetAttack()/3 - GetDefense()); std::uniform_int_distribution<int> alphaRange(alpha, alpha*2 + 10); std::uniform_int_distribution<int> betaRange(beta, beta*1.2 + 4); std::random_device rd; alpha = alphaRange(rd); beta = betaRange(rd); ReduceLife(alpha); target->ReduceLife(beta); a_out = "A hit was made!\nYou're damage: " + std::to_string(alpha) + ", current life: " + std::to_string(GetLife()) + "\nOpponent damage: " + std::to_string(beta) + ", opponent current life: " + std::to_string(target->GetLife()); if(target->GetLife() == 0) { unsigned int shinyMoney = target->GetMoney(); AddMoney(shinyMoney); a_out += "\nYou've killed " + target->Name() + "\nYou've got " + std::to_string(shinyMoney) + " new coins!"; target->Respawn(); } if(GetLife() == 0) { target->AddMoney(GetMoney()); a_out += "\nYou've died :(\nRespawning.."; Respawn(); } } void Player::Respawn() { std::string out; std::vector<std::shared_ptr<IObject> > dropping_objects(m_keys.begin(),m_keys.end()); if(m_sword) { dropping_objects.push_back(m_sword); m_sword = m_starting_sword; } if(m_shield) { dropping_objects.push_back(m_shield); m_shield = nullptr; } m_location->PlaceObjects(dropping_objects, out); SetLife(m_starting_life); SetMoney(m_starting_money); std::shared_ptr<IFightable> me; m_location->Exit(Name(), me); m_location = m_starting_position; m_location->Enter(me); } void Player::Describe(std::string& a_out) const { std::string swordDescription; m_sword->Describe(swordDescription); a_out = Name() + ":\nLife: " + std::to_string(GetLife()) + "\nMoney: " + std::to_string(GetMoney()) + "\nSword:\n" + swordDescription; if(m_shield) { std::string shieldDescription; m_shield->Describe(shieldDescription); a_out += "\nShield:\n" + shieldDescription; } a_out += "\nKeys: "; for(auto key : m_keys) { a_out += key->Name() + ';'; } } void Player::Open(std::string& a_out) const { std::shared_ptr<IPassage> passage; m_location->Move(m_direction, passage); if(passage) { passage->Open(a_out); return; } a_out = "You have reached a wall"; } void Player::Close(std::string& a_out) const { std::shared_ptr<IPassage> passage; m_location->Move(m_direction, passage); if(passage) { passage->Close(a_out); return; } a_out = "You have reached a wall"; } void Player::Lock(std::string& a_out) const { std::shared_ptr<IPassage> passage; m_location->Move(m_direction, passage); if(passage) { for(size_t i = 0 ; i < m_keys.size() ; ++i) { if(passage->Lock(m_keys[i], a_out)) { break; } } return; } a_out = "You have reached a wall"; } void Player::UnLock(std::string& a_out) const { std::shared_ptr<IPassage> passage; m_location->Move(m_direction, passage); if(passage) { for(size_t i = 0 ; i < m_keys.size() ; ++i) { if(passage->UnLock(m_keys[i], a_out)) { break; } } return; } a_out = "You have reached a wall"; } void Player::Where(std::string& a_out) const { a_out = m_location->Name(); } void Player::Look(std::string& a_out) const { m_location->Describe(a_out); } void Player::Call(const std::string& a_method, std::string& a_out) { auto no_const_res = s_mf_dict_one_arg.find(a_method); if(no_const_res != s_mf_dict_one_arg.end()) { (this->*(no_const_res->second))(a_out); return; } auto const_res = s_mf_dict_one_arg_const.find(a_method); if(const_res != s_mf_dict_one_arg_const.end()) { (this->*(const_res->second))(a_out); return; } a_out = "No such method found"; } void Player::Call(const std::string& a_method, const std::string& a_arg, std::string& a_out) { auto res = s_mf_dict_two_arg.find(a_method); if(res != s_mf_dict_two_arg.end()) { (this->*(res->second))(a_arg, a_out); return; } a_out = "No such methos found"; } } //d_d
true
a0bede8c0df1c91a34e99eca0d449dd7a432ff04
C++
Mamama22/Framework-C-
/learnopenGL/Source/EntityManager.h
UTF-8
2,051
2.984375
3
[]
no_license
#ifndef ENTITY_MANAGER_H #define ENTITY_MANAGER_H #include "Entity.h" /************************************************************* Entity manager. Only stores entities. DOES NOT UPDATE THEM Type: manager class Usage: Entity adds itself to this and gets a handle Author: Tan Yie Cher Date: 12/7/2016 /*************************************************************/ class EntityManager { protected: /******************** var **********************/ vector<Entity*> entityList; public: //to get list of child/comp from a entity (RESIZED TO 10) vector<Entity*> childrenList; vector<Component*> compList; void Init(); /******************** comp functions **********************/ int RegisterEntity(Entity* regMe); /******************** get functions **********************/ Entity* GetEntity(int handle); Entity* GetTopParent_Entity(int handle); void GetEntityChildren(int handle); void GetEntityComp(int handle); /******************** Core functions **********************/ void PreUpdate(); void UpdateStage1(); void UpdateStage2(); void UpdateStage3(); void UpdateStage4(); void Update_AllTRS(); /******************** Exit functions **********************/ void Exit(); /******************************************************************************** Check if given entity is of this class type ********************************************************************************/ template<class T> bool CheckEntityType(int handle) { if (dynamic_cast<T*>(entityList[handle])) return true; return false; } template<class T> static bool CheckEntityType(Entity* checkMe) { if (dynamic_cast<T*>(checkMe)) return true; return false; } /******************************************************************************** Check if given component is of this class type ********************************************************************************/ template<class T> static bool CheckCompType(Component* checkMe) { if (dynamic_cast<T*>(checkMe)) return true; return false; } }; #endif
true
f6924f25ce9db2b55870a9d8d47fb02115408933
C++
PapamichMarios/Crypto-Recommendation
/recommendation.cpp
UTF-8
3,585
2.546875
3
[]
no_license
#include <cstdlib> #include <iostream> #include <map> #include <vector> #include "utilities.h" #include "recommendationLSH.h" #include "recommendationClustering.h" #include "hash_table.h" #include "clustering.h" #include "validation.h" #define ARGS 7 using namespace std; int main(int argc, char** argv) { short int inputFileIndex, outputFileIndex, tweetsFileIndex; bool validateFlag = false; int k = 4; int L = 3; /*== check the #args*/ rerunCheck(argc, ARGS); /*== get inline arguments*/ getInlineArguments(argc, argv, inputFileIndex, outputFileIndex, validateFlag, tweetsFileIndex); /*== clear outputfile */ resetOutput(argv[outputFileIndex]); /*== create a map word : sentimental value*/ map<string, float> vaderLexicon = vaderLexiconMap(); /*== create a map crypto : index*/ map<string, int> cryptos = cryptosMap(); /*== create a map index : crypto*/ map<int, string> cryptosIndex = cryptosIndexMap(); /*== construct vector "user : crypto"*/ vector<vector<double>> users = createUserVector(argv[inputFileIndex], vaderLexicon, cryptos); /*== normalize user vectors*/ vector<vector<double>> normalisedUsers = users; normalisation(normalisedUsers); /*==== 1. Recommend cryptos based on user clustering*/ recommendationLSH(users, normalisedUsers, cryptosIndex, k, L, argv[inputFileIndex], argv[outputFileIndex]); cout << "1a - LSH Recommendation done!" << endl; recommendationClustering(users, normalisedUsers, cryptosIndex, argv[outputFileIndex]); cout << "2a - Clustering Recommendation done!" << endl; if(validateFlag) { F_FoldCrossValidation(k, L, users, normalisedUsers, argv[inputFileIndex], argv[outputFileIndex]); cout << "1a - 10 Fold Cross Validation done!" << endl; F_FoldCrossValidation(users, normalisedUsers, argv[outputFileIndex]); cout << "2a - 10 Fold Cross Validation done!" << endl; } /*====*/ /*== construct map "twitterid : vector<double> crypto sentiments"*/ map<int, vector<double>> tweets_sentiments = createTweetMap(argv[inputFileIndex], vaderLexicon, cryptos); map<int, vector<double>> tweets_sentiments_normalised = tweets_sentiments; normalisation(tweets_sentiments_normalised); /*== construct vector with the tweets from the previous assignment*/ vector<vector<double>> tweets = createTweetVector(argv[tweetsFileIndex]); /*== cluster tweets*/ vector<int> tweets_clusters = k_meanspp(tweets, tweets, CLUSTER_TWEETS); /*== find virtual user for every cluster*/ vector<vector<double>> virtual_users = createVirtualUsers(tweets_sentiments, tweets_clusters, CLUSTER_TWEETS, CRYPTO_NUMBER); vector<vector<double>> normalised_virtual_users = createVirtualUsersNormalised(tweets_sentiments_normalised, tweets_clusters, CLUSTER_TWEETS, CRYPTO_NUMBER); /*==== 2. Recommend cryptos based on twitter clustering*/ recommendationLSH(users, normalisedUsers, virtual_users, normalised_virtual_users, cryptosIndex, k, L, argv[inputFileIndex], argv[outputFileIndex]); cout << "1b - LSH Recommendation done!" << endl; recommendationClustering(users, normalisedUsers, virtual_users, normalised_virtual_users, cryptosIndex, argv[outputFileIndex]); cout << "2b - Clustering Recommendation done!" << endl; if(validateFlag) { virtualValidation(users, normalisedUsers, virtual_users, normalised_virtual_users, k, L, argv[inputFileIndex], argv[outputFileIndex]); cout << "1b - Validation done!" << endl; virtualValidation(users, normalisedUsers, virtual_users, normalised_virtual_users, argv[outputFileIndex]); cout << "2b - Validation done!" << endl; } /*===*/ exit(EXIT_SUCCESS); }
true
767fb91c2a7d8b13e80904658650860d0946d6df
C++
pytorch/pytorch
/c10/test/core/impl/SizesAndStrides_test.cpp
UTF-8
10,582
3.140625
3
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
#include <gtest/gtest.h> #include <c10/core/impl/SizesAndStrides.h> #include <c10/util/irange.h> #ifdef __clang__ #pragma clang diagnostic ignored "-Wself-assign-overloaded" #endif using namespace c10; using namespace c10::impl; static void checkData( const SizesAndStrides& sz, IntArrayRef sizes, IntArrayRef strides) { EXPECT_EQ(sizes.size(), strides.size()) << "bad test case: size() of sizes and strides don't match"; EXPECT_EQ(sz.size(), sizes.size()); int idx = 0; for (auto x : sizes) { EXPECT_EQ(sz.size_at_unchecked(idx), x) << "index: " << idx; EXPECT_EQ(sz.size_at(idx), x) << "index: " << idx; EXPECT_EQ(sz.sizes_data()[idx], x) << "index: " << idx; EXPECT_EQ(*(sz.sizes_begin() + idx), x) << "index: " << idx; idx++; } EXPECT_EQ(sz.sizes_arrayref(), sizes); idx = 0; for (auto x : strides) { EXPECT_EQ(sz.stride_at_unchecked(idx), x) << "index: " << idx; EXPECT_EQ(sz.stride_at(idx), x) << "index: " << idx; EXPECT_EQ(sz.strides_data()[idx], x) << "index: " << idx; EXPECT_EQ(*(sz.strides_begin() + idx), x) << "index: " << idx; idx++; } EXPECT_EQ(sz.strides_arrayref(), strides); } TEST(SizesAndStridesTest, DefaultConstructor) { SizesAndStrides sz; checkData(sz, {0}, {1}); // Can't test size_at() out of bounds because it just asserts for now. } TEST(SizesAndStridesTest, SetSizes) { SizesAndStrides sz; sz.set_sizes({5, 6, 7, 8}); checkData(sz, {5, 6, 7, 8}, {1, 0, 0, 0}); } TEST(SizesAndStridesTest, Resize) { SizesAndStrides sz; sz.resize(2); // Small to small growing. checkData(sz, {0, 0}, {1, 0}); // Small to small growing, again. sz.resize(5); checkData(sz, {0, 0, 0, 0, 0}, {1, 0, 0, 0, 0}); for (const auto ii : c10::irange(sz.size())) { sz.size_at_unchecked(ii) = ii + 1; sz.stride_at_unchecked(ii) = 2 * (ii + 1); } checkData(sz, {1, 2, 3, 4, 5}, {2, 4, 6, 8, 10}); // Small to small, shrinking. sz.resize(4); checkData(sz, {1, 2, 3, 4}, {2, 4, 6, 8}); // Small to small with no size change. sz.resize(4); checkData(sz, {1, 2, 3, 4}, {2, 4, 6, 8}); // Small to small, growing back so that we can confirm that our "new" // data really does get zeroed. sz.resize(5); checkData(sz, {1, 2, 3, 4, 0}, {2, 4, 6, 8, 0}); // Small to big. sz.resize(6); checkData(sz, {1, 2, 3, 4, 0, 0}, {2, 4, 6, 8, 0, 0}); sz.size_at_unchecked(5) = 6; sz.stride_at_unchecked(5) = 12; checkData(sz, {1, 2, 3, 4, 0, 6}, {2, 4, 6, 8, 0, 12}); // Big to big, growing. sz.resize(7); checkData(sz, {1, 2, 3, 4, 0, 6, 0}, {2, 4, 6, 8, 0, 12, 0}); // Big to big with no size change. sz.resize(7); checkData(sz, {1, 2, 3, 4, 0, 6, 0}, {2, 4, 6, 8, 0, 12, 0}); sz.size_at_unchecked(6) = 11; sz.stride_at_unchecked(6) = 22; checkData(sz, {1, 2, 3, 4, 0, 6, 11}, {2, 4, 6, 8, 0, 12, 22}); // Big to big, shrinking. sz.resize(6); checkData(sz, {1, 2, 3, 4, 0, 6}, {2, 4, 6, 8, 0, 12}); // Grow back to make sure "new" elements get zeroed in big mode too. sz.resize(7); checkData(sz, {1, 2, 3, 4, 0, 6, 0}, {2, 4, 6, 8, 0, 12, 0}); // Finally, big to small. // Give it different data than it had when it was small to avoid // getting it right by accident (i.e., because of leftover inline // storage when going small to big). for (const auto ii : c10::irange(sz.size())) { sz.size_at_unchecked(ii) = ii - 1; sz.stride_at_unchecked(ii) = 2 * (ii - 1); } checkData(sz, {-1, 0, 1, 2, 3, 4, 5}, {-2, 0, 2, 4, 6, 8, 10}); sz.resize(5); checkData(sz, {-1, 0, 1, 2, 3}, {-2, 0, 2, 4, 6}); } TEST(SizesAndStridesTest, SetAtIndex) { SizesAndStrides sz; sz.resize(5); sz.size_at(4) = 42; sz.stride_at(4) = 23; checkData(sz, {0, 0, 0, 0, 42}, {1, 0, 0, 0, 23}); sz.resize(6); sz.size_at(5) = 43; sz.stride_at(5) = 24; checkData(sz, {0, 0, 0, 0, 42, 43}, {1, 0, 0, 0, 23, 24}); } TEST(SizesAndStridesTest, SetAtIterator) { SizesAndStrides sz; sz.resize(5); *(sz.sizes_begin() + 4) = 42; *(sz.strides_begin() + 4) = 23; checkData(sz, {0, 0, 0, 0, 42}, {1, 0, 0, 0, 23}); sz.resize(6); *(sz.sizes_begin() + 5) = 43; *(sz.strides_begin() + 5) = 24; checkData(sz, {0, 0, 0, 0, 42, 43}, {1, 0, 0, 0, 23, 24}); } TEST(SizesAndStridesTest, SetViaData) { SizesAndStrides sz; sz.resize(5); *(sz.sizes_data() + 4) = 42; *(sz.strides_data() + 4) = 23; checkData(sz, {0, 0, 0, 0, 42}, {1, 0, 0, 0, 23}); sz.resize(6); *(sz.sizes_data() + 5) = 43; *(sz.strides_data() + 5) = 24; checkData(sz, {0, 0, 0, 0, 42, 43}, {1, 0, 0, 0, 23, 24}); } static SizesAndStrides makeSmall(int offset = 0) { SizesAndStrides small; small.resize(3); for (const auto ii : c10::irange(small.size())) { small.size_at_unchecked(ii) = ii + 1 + offset; small.stride_at_unchecked(ii) = 2 * (ii + 1 + offset); } return small; } static SizesAndStrides makeBig(int offset = 0) { SizesAndStrides big; big.resize(8); for (const auto ii : c10::irange(big.size())) { big.size_at_unchecked(ii) = ii - 1 + offset; big.stride_at_unchecked(ii) = 2 * (ii - 1 + offset); } return big; } static void checkSmall(const SizesAndStrides& sm, int offset = 0) { std::vector<int64_t> sizes(3), strides(3); for (const auto ii : c10::irange(3)) { sizes[ii] = ii + 1 + offset; strides[ii] = 2 * (ii + 1 + offset); } checkData(sm, sizes, strides); } static void checkBig(const SizesAndStrides& big, int offset = 0) { std::vector<int64_t> sizes(8), strides(8); for (const auto ii : c10::irange(8)) { sizes[ii] = ii - 1 + offset; strides[ii] = 2 * (ii - 1 + offset); } checkData(big, sizes, strides); } TEST(SizesAndStridesTest, MoveConstructor) { SizesAndStrides empty; SizesAndStrides movedEmpty(std::move(empty)); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(empty.size(), 0); EXPECT_EQ(movedEmpty.size(), 1); checkData(movedEmpty, {0}, {1}); SizesAndStrides small = makeSmall(); checkSmall(small); SizesAndStrides movedSmall(std::move(small)); checkSmall(movedSmall); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(small.size(), 0); SizesAndStrides big = makeBig(); checkBig(big); SizesAndStrides movedBig(std::move(big)); checkBig(movedBig); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(big.size(), 0); } TEST(SizesAndStridesTest, CopyConstructor) { SizesAndStrides empty; // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) SizesAndStrides copiedEmpty(empty); EXPECT_EQ(empty.size(), 1); EXPECT_EQ(copiedEmpty.size(), 1); checkData(empty, {0}, {1}); checkData(copiedEmpty, {0}, {1}); SizesAndStrides small = makeSmall(); checkSmall(small); // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) SizesAndStrides copiedSmall(small); checkSmall(copiedSmall); checkSmall(small); SizesAndStrides big = makeBig(); checkBig(big); // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) SizesAndStrides copiedBig(big); checkBig(big); checkBig(copiedBig); } TEST(SizesAndStridesTest, CopyAssignmentSmallToSmall) { SizesAndStrides smallTarget = makeSmall(); SizesAndStrides smallCopyFrom = makeSmall(1); checkSmall(smallTarget); checkSmall(smallCopyFrom, 1); smallTarget = smallCopyFrom; checkSmall(smallTarget, 1); checkSmall(smallCopyFrom, 1); } TEST(SizesAndStridesTest, MoveAssignmentSmallToSmall) { SizesAndStrides smallTarget = makeSmall(); SizesAndStrides smallMoveFrom = makeSmall(1); checkSmall(smallTarget); checkSmall(smallMoveFrom, 1); smallTarget = std::move(smallMoveFrom); checkSmall(smallTarget, 1); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(smallMoveFrom.size(), 0); } TEST(SizesAndStridesTest, CopyAssignmentSmallToBig) { SizesAndStrides bigTarget = makeBig(); SizesAndStrides smallCopyFrom = makeSmall(); checkBig(bigTarget); checkSmall(smallCopyFrom); bigTarget = smallCopyFrom; checkSmall(bigTarget); checkSmall(smallCopyFrom); } TEST(SizesAndStridesTest, MoveAssignmentSmallToBig) { SizesAndStrides bigTarget = makeBig(); SizesAndStrides smallMoveFrom = makeSmall(); checkBig(bigTarget); checkSmall(smallMoveFrom); bigTarget = std::move(smallMoveFrom); checkSmall(bigTarget); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(smallMoveFrom.size(), 0); } TEST(SizesAndStridesTest, CopyAssignmentBigToBig) { SizesAndStrides bigTarget = makeBig(); SizesAndStrides bigCopyFrom = makeBig(1); checkBig(bigTarget); checkBig(bigCopyFrom, 1); bigTarget = bigCopyFrom; checkBig(bigTarget, 1); checkBig(bigCopyFrom, 1); } TEST(SizesAndStridesTest, MoveAssignmentBigToBig) { SizesAndStrides bigTarget = makeBig(); SizesAndStrides bigMoveFrom = makeBig(1); checkBig(bigTarget); checkBig(bigMoveFrom, 1); bigTarget = std::move(bigMoveFrom); checkBig(bigTarget, 1); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(bigMoveFrom.size(), 0); } TEST(SizesAndStridesTest, CopyAssignmentBigToSmall) { SizesAndStrides smallTarget = makeSmall(); SizesAndStrides bigCopyFrom = makeBig(); checkSmall(smallTarget); checkBig(bigCopyFrom); smallTarget = bigCopyFrom; checkBig(smallTarget); checkBig(bigCopyFrom); } TEST(SizesAndStridesTest, MoveAssignmentBigToSmall) { SizesAndStrides smallTarget = makeSmall(); SizesAndStrides bigMoveFrom = makeBig(); checkSmall(smallTarget); checkBig(bigMoveFrom); smallTarget = std::move(bigMoveFrom); checkBig(smallTarget); // NOLINTNEXTLINE(bugprone-use-after-move,clang-analyzer-cplusplus.Move) EXPECT_EQ(bigMoveFrom.size(), 0); } TEST(SizesAndStridesTest, CopyAssignmentSelf) { SizesAndStrides small = makeSmall(); SizesAndStrides big = makeBig(); checkSmall(small); checkBig(big); // NOLINTNEXTLINE(clang-diagnostic-self-assign-overloaded) small = small; checkSmall(small); // NOLINTNEXTLINE(clang-diagnostic-self-assign-overloaded) big = big; checkBig(big); } // Avoid failures due to -Wall -Wself-move. static void selfMove(SizesAndStrides& x, SizesAndStrides& y) { x = std::move(y); } TEST(SizesAndStridesTest, MoveAssignmentSelf) { SizesAndStrides small = makeSmall(); SizesAndStrides big = makeBig(); checkSmall(small); checkBig(big); selfMove(small, small); checkSmall(small); selfMove(big, big); checkBig(big); }
true
4fb8a9ed5923213b0adf6e6d06f17635c84328f2
C++
eder-matheus/programming_challenges
/data_structs/training_dragon.cpp
UTF-8
1,982
3.53125
4
[ "BSD-3-Clause" ]
permissive
// training dragon #include <iostream> #include <algorithm> #include <vector> struct Dragon { long long int days_to_train_; long long int fee_per_day_; int curr_day_; Dragon(long long int days_to_train, long long int fee_per_day, int curr_day) { days_to_train_ = days_to_train; fee_per_day_ = fee_per_day; curr_day_ = curr_day; } float computeCost() const { return (float)days_to_train_/fee_per_day_; } }; struct greater1 { bool operator()(const Dragon& d0, const Dragon& d1) const { return d0.computeCost() > d1.computeCost(); } }; int main() { int days_to_train, cost_to_train; long long int total_fee = 0; int total_days = 0; int training_days = 0; std::vector<Dragon> dragons; std::make_heap(dragons.begin(), dragons.end(), greater1()); while (std::cin >> days_to_train >> cost_to_train) { dragons.push_back(Dragon(days_to_train, cost_to_train, total_days)); std::push_heap(dragons.begin(), dragons.end(), greater1()); // when previous training end, choose another dragon if (training_days == 0) { // get dragon with largest cost Dragon dragon = dragons.front(); std::pop_heap(dragons.begin(), dragons.end(), greater1()); dragons.pop_back(); // get the fee for the dragon multiplying the number of days it is waiting for training total_fee += (total_days-dragon.curr_day_)*dragon.fee_per_day_; training_days = dragon.days_to_train_; } training_days--; total_days++; } // same logic from above for the remaining dragons, after all were sent while (!dragons.empty()) { if (training_days == 0) { Dragon dragon = dragons.front(); std::pop_heap(dragons.begin(), dragons.end(), greater1()); dragons.pop_back(); total_fee += (total_days-dragon.curr_day_)*dragon.fee_per_day_; training_days = dragon.days_to_train_; } training_days--; total_days++; } std::cout << total_fee << "\n"; return 0; }
true
818c973c0355f32ce3a587dc55dcc73cfca425d6
C++
leyicai/LeetCode-Solution
/cpp/260_SingleNumberIII.cpp
UTF-8
1,116
3.78125
4
[]
no_license
class Solution { public: vector<int> singleNumber(vector<int>& nums) { vector<int> res = {0, 0}; int diff = 0; for (auto i : nums) { diff ^= i; } diff &= -diff; cout << diff << endl; for (auto i : nums) { if (i & diff) { res[0] ^= i; } else { res[1] ^= i; } } return res; } }; // Using XOR class Solution { public: vector<int> singleNumber(vector<int>& nums) { // Pass 1 : // Get the XOR of the two numbers we need to find int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>()); // Get a number with only 1 bit set to 1 and others are 0, the i indicates the rightmost position that a and b differs from each other // e.g. a=3(0011), b=5(0101), diff=(0110). -diff=(1010) // diff & -diff = 0010 diff &= -diff; // Pass 2 : vector<int> rets = {0, 0}; // this vector stores the two numbers we will return for (int num : nums) { if ((num & diff) == 0) // numbers with i-th pos set to 0 括号不能少!!! { rets[0] ^= num; } else // numbers with i-th pos set to 1 { rets[1] ^= num; } } return rets; } };
true
8fa4934ac6de276f84e4d1d9f45136fc9d0587a4
C++
Lumbi/cookie
/Cookie/AnimBlock.cpp
UTF-8
1,887
2.828125
3
[ "MIT" ]
permissive
// // AnimBlock.cpp // Cookie // // Created by Gabriel Lumbi on 2014-10-20. // Copyright (c) 2014 Gabriel Lumbi. All rights reserved. // #include "AnimBlock.h" Cookie::AnimBlock::AnimBlock(Cookie::Renderer* renderer) : Cookie::DrawBlock(renderer) { current_anim_ = NULL; } Cookie::AnimBlock::~AnimBlock() { for (auto it = animations_.begin(); it != animations_.end(); ++it) { delete (*it).second; } animations_.clear(); } void Cookie::AnimBlock::update(Cookie::Node& node, Cookie::Game& game) { if(current_anim_ != NULL) { current_anim_->update(game.time_elapsed()); Cookie::Point draw_offset = { -(draw_point_.x * current_anim_->frame().w), -(draw_point_.y * current_anim_->frame().h) }; renderer_->addToBatch(*current_anim_, draw_offset + node.position_world()); } } Cookie::Animation* const Cookie::AnimBlock::anim(Cookie::Int name) const { auto found = animations_.find(name); if(found != animations_.end()) { return (*found).second; }else{ return NULL; } } void Cookie::AnimBlock::add_anim(Cookie::Int name, Cookie::Animation* anim) { auto found = animations_.find(name); if(found != animations_.end()) { delete (*found).second; } animations_[name] = anim; if(current_anim_ == NULL) { current_anim_ = anim; } } void Cookie::AnimBlock::remove_anim(Cookie::Int name) { auto found = animations_.find(name); if(found != animations_.end()) { delete (*found).second; animations_.erase(found); } } Cookie::Animation* const Cookie::AnimBlock::switch_anim(Cookie::Int name) { auto found = animations_.find(name); if(found != animations_.end()) { current_anim_ = (*found).second; return current_anim_; }else{ return NULL; } }
true
664344d83348da5b672a06f1d1719fc8ffd8551f
C++
akrabulislam/UVA
/383.cpp
UTF-8
1,820
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define mx 500 int main() { //freopen ("input.txt","r",stdin); //freopen ("output.txt","w",stdout); int t,test=1; cin>>t; cout<<"SHIPPING ROUTES OUTPUT"<<endl; while(t--) { cout<<endl; printf("DATA SET %d\n", test++); cout<<endl; int n,m,p; cin>>n>>m>>p; string a,b; for(int i=0; i<n; i++) { string p; cin>>p; } map<string,vector<string> >graph; for(int i=0; i<m; i++) { cin>>a>>b; graph[a].push_back(b); graph[b].push_back(a); } for(int i=0; i<p; i++) { int siz,ds; cin>>siz>>a>>b; queue<string>q; map<string,int>visited; visited[a]=0; q.push(a); bool ok=false; while(!q.empty()) { string u=q.front(); ds=visited[u]; q.pop(); if(u==b) { ok=true; break; } int sz=graph[u].size(); for(int j=0; j<sz; j++) { string v=graph[u][j]; if(!visited[v]) { q.push(v); visited[v]=ds+1; } } } if(!ok) { cout<<"NO SHIPMENT POSSIBLE"<<endl; } else { printf("$%d\n",siz*ds*100); } } } cout<<endl<<"END OF OUTPUT"<<endl; return 0; }
true
4ffb9965b96380acf7a1a532702a36461b32a92c
C++
richard-hajek/pa2-semestralka
/src/units/Tile.h
UTF-8
1,017
3.234375
3
[]
no_license
#ifndef PROGTEST_PROJECT_TILE_H #define PROGTEST_PROJECT_TILE_H #include "Drawable.h" /** * Basic tile, goes on the map */ class Tile : public Drawable { public: /** * Must be constructed with initial coordinates and symbol to draw on the map */ Tile(int x, int y, char c); /** * Use this to get Tile's chracter * @return Symbol to draw */ char GetChar() const final; /** * Use this method if program needs to know if Tile can be walked upon by enemies * @return true if walkable */ bool GetWalkable(); /** * Use this method to make tile unwalkable */ void Obstruct(); /** * Returns true if this tile is buildable upon * @return true if buildable */ bool GetBuildable(); protected: /// Symbol to draw on the map char m_Symbol; /// Whether the Tile can be walked upon bool m_Walkable; /// Whether the Tile can be build upon bool m_Buildable; }; #endif //PROGTEST_PROJECT_TILE_H
true
41d114442aaea81275102844238638132bec2846
C++
MCBell/Senior-Project
/Project/Source/aSprite.cpp
UTF-8
2,370
2.859375
3
[]
no_license
#include "asprite.h" #include "graphic.h" #include "sprite.h" ASprite::ASprite(){} ASprite::ASprite(Graphic &graphic, const std::string &filePath, int sourceX, int sourceY, int width, int height, float posX, float posY, float timeToUpdate): Sprite(graphic, filePath, sourceX, sourceY, width, height, posX, posY), _frameIndex(0), _timeToUpdate(timeToUpdate), _visible(true), _currentAnimationOnce(false), _currentAnimation("") {} void ASprite::addAni(int frames, int x, int y, std::string name, int width, int height, Vector2 offset){ std::vector<SDL_Rect> rectangles; for (int i=0; i < frames; i++){ SDL_Rect newRect = { (i+x)*width, y, width, height}; rectangles.push_back(newRect); } this->_animations.insert(std::pair<std::string, std::vector<SDL_Rect>>(name, rectangles)); this->_offsets.insert(std::pair<std::string, Vector2>(name, offset)); } void ASprite::resetAni(){ this->_animations.clear(); this->_offsets.clear(); } void ASprite::playAni(std::string animation, bool once){ this->_currentAnimationOnce=once; if ( this-> _currentAnimation!= animation){ this->_currentAnimation = animation; this->_frameIndex = 0; } } void ASprite::setVis(bool visible){ this->_visible = visible; } void ASprite::stopAni(){ this->_frameIndex=0; this->doneAni(this->_currentAnimation); } void ASprite::update(int elapsedTime){ Sprite::update(); this->_timeElapsed += elapsedTime; if(this->_timeElapsed> this->_timeToUpdate){ this->_timeElapsed -=this->_timeToUpdate; if (this->_frameIndex < this->_animations[this->_currentAnimation].size()-1){ this->_frameIndex++; } else{ if (this->_currentAnimationOnce==true){ this->setVis(false); } this->_frameIndex = 0; this->doneAni(this->_currentAnimation); } } } void ASprite::draw(Graphic &graphic, int x, int y, SDL_RendererFlip flipSprite){ if (this->_visible){ SDL_Rect destinationRectangle; destinationRectangle.x= x+this->_offsets[this->_currentAnimation].x; destinationRectangle.y= y+this->_offsets[this->_currentAnimation].y; destinationRectangle.w= (this ->_sourceRect.w); destinationRectangle.h= (this ->_sourceRect.h); SDL_Rect sourceRect= this-> _animations[this->_currentAnimation][this->_frameIndex]; graphic.blitSurface(this->_spriteSheet, &sourceRect, &destinationRectangle, flipSprite); } }
true
a0fc136f957cb3bf3380dbd9a8058471af3902c2
C++
hjkwok/practise
/dlList.cpp
UTF-8
1,747
3.546875
4
[]
no_license
#include "dlList.h" node_t* CreateList(int array[], int len) { int idx = 0; node_t *node; node_t *head; node_t *pre = 0; if(len == 1) { head = (node_t *)malloc(sizeof(node_t)); head->value = array[idx]; head->pre = 0; head->next = 0; return head; } for(idx = 0; idx < len; idx++) { node = (node_t *)malloc(sizeof(node_t)); node->pre = pre; if(pre != 0){ pre->next = node; }else { head = node; } node->next = 0; node->value = array[idx]; pre = node; } return head; } void PrintList(node_t **head) { node_t *it = *head; int idx = 0; while(it != NULL) { printf("%d element: %d\n", idx++, it->value); it = it->next; } } void InsertNode(node_t **head, int value) { if(!head && !*head) return; node_t* node = (node_t *)malloc(sizeof(node_t)); node->pre = 0; node->value = value; node->next = *head; (*head)->pre = node; *head = node; } void PurgeList(node_t **head) { node_t *node = 0; while(*head != 0) { node = *head; *head = node->next; free(node); } } void SwapNode(node_t *left, node_t *right) { node_t *leftPre, *leftNext, *rightPre, *rightNext; leftPre = left->pre; leftNext = left->next; rightPre = right->pre; rightNext = right->Next; left->pre = right->pre; left->next = right->next; if(leftPre) leftPre->next = right; if(leftNext) leftNext->pre = right; if(rightPre) rightPre->next = left; if(rightNext) rightNext->pre = left; /* node_t *preHolder = left->pre; node_t *nextHolder = left->next; left->pre->next = right; left->next->pre = right; right->pre->next = left; right->next->pre = left; left->next = right->next; left->pre = right->pre; right->next = nextHolder; right->pre = preHolder;*/ } void SortList(node_t **head) { }
true
cb1fb5f2aaf9a4829e2f57e3b135fa9c078ac59e
C++
flexboni/algorithm_c
/7강/simpleSort.cpp
UTF-8
835
3.5
4
[]
no_license
#include <stdio.h> // 문제 : https://www.acmicpc.net/problem/2750 int array[1001]; // 주어진 수의 갯수보다 +1 된 배열을 선언하는게 좋다. int main(void) { int number, i, j, min, index, temp; scanf("%d", &number); for (i = 0; i < number; i++) { scanf("%d", &array[i]); } for (size_t i = 0; i < number; i++) { min = 1001; // 주어진 수의 최댓값 보다 항상 큰 값으로 초기화 for (size_t j = i; j < number; j++) { if (min > array[j]) { min = array[j]; index = j; } } temp = array[i]; array[i] = array[index]; array[index] = temp; } for (size_t i = 0; i < number; i++) { printf("%d\n", array[i]); } return 0; }
true
1db04391b6bad7c3dcd4ceedee788d857e9a797c
C++
Mahmood-Darwish/CodeForces-Problem-Solutions
/Problems/Minimal string/Minimal string.cpp
UTF-8
1,469
2.859375
3
[]
no_license
#include <iostream> using namespace std; int I, letter; string s, temp, ans; int arr[27]; int a[27]; int b[27]; int main() { cin >> s; for(int i = 0; i < s.size() ; i++){ a[s[i] - 'a']++; arr[s[i] - 'a']++; } while(I < s.size() || temp.size()){ if(!a[letter]){ letter++; continue; } //cout << s << ' ' << I << endl << temp << endl << ans << endl; if(s.size() <= I){ while(temp.size()){ ans.push_back(temp[temp.size() - 1]); b[temp[temp.size() - 1] - 'a']--; arr[temp[temp.size() - 1] - 'a']--; temp.pop_back(); } break; } while(temp.size() && temp[temp.size() - 1] - 'a' <= letter){ b[temp[temp.size() - 1] - 'a']--; arr[temp[temp.size() - 1] - 'a']--; ans.push_back(temp[temp.size() - 1]); temp.pop_back(); } while(I < s.size() && a[letter]){ if(s[I] - 'a' == letter){ a[letter]--; arr[letter]--; ans.push_back(s[I]); } else{ temp.push_back(s[I]); a[s[I] - 'a']--; b[s[I] - 'a']++; } I++; } letter++; } cout << ans << endl; return 0; } //abcbabbcc aabbbcbcc
true
18e31537b7e019352faf0548d22e5118fe041a86
C++
Cyvid7-Darus10/C-plus-plus
/Bigfactorial.cpp
UTF-8
627
3.546875
4
[]
no_license
#include <iostream> using namespace std; void factorial(int); int multiply(int[], int, int); int main() { int N; cin >> N; factorial(N); } void factorial(int N) { int holder[500]; holder[0] = 1; int size = 1; for (int i = 2; i <= N; i++) { size = multiply(holder, size, i); } for (int i = size - 1; i >=0; i--) { cout << holder[i]; } } int multiply(int holder[], int size, int num) { int carry = 0; for (int i = 0; i < size; i++) { holder[i] = holder[i] * num + carry; carry = holder[i]/10; holder[i] %= 10; } while (carry) { holder[size++] = carry % 10; carry /= 10; } return size; }
true
f82916e24e1e44aff0675b8d381901b7fafa4ac4
C++
vitkarpov/dcp
/codeforces/contest-1237/b.cpp
UTF-8
562
2.796875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> in(n + 1); vector<int> out(n + 1); vector<bool> visited(n + 1); for (int i = 1; i <= n; i++) { cin >> in[i]; } for (int i = 1; i <= n; i++) { cin >> out[i]; } int i = n; int j = n; int fines = 0; while (i > 1) { if (visited[out[j]]) { j--; } else { visited[in[i]] = true; if (in[i] != out[j]) { fines++; } else { j--; } i--; } } cout << fines << endl; }
true
31568ebaba1b200eca1f3e6ae6212ca9d09e4a70
C++
DeathGodBXX/learn_new_cpp
/LeetCode/Test/testmultimap.cpp
UTF-8
3,758
3.21875
3
[]
no_license
#include <iostream> #include <unordered_map> #include <string> #include <utility> #include <queue> #include <cstdio> #include <vector> using std::cout; using std::endl; using std::queue; using std::snprintf; using std::string; using std::unordered_multimap; using std::vector; int main() { unordered_multimap<std::string, std::string> mp = {{"a", "aaa"}, {"b", "bbbb"}}; mp.insert({"a", "ababab"}); mp.insert(std::make_pair("a", "acac")); mp.insert({"c", "cccc"}); mp.insert({"b", "bbbbbbbb"}); //since bucket maybe before or behind "a" bucket,then maybe not output "c" tag; for (auto fd = mp.find("a"); fd != mp.end(); fd++) { cout << fd->first << "\t" << fd->second << endl; } cout << "............." << endl; for (auto fd = mp.begin(); fd != mp.end(); fd++) { cout << fd->first << "\t" << fd->second << endl; } cout << ".............." << endl; auto fd = mp.equal_range("a"); //精确查找键对应的所有值 for (auto begin = fd.first; begin != fd.second; begin++) { cout << begin->first << "\t" << begin->second << endl; } //尽管使用这种数据结构,体现不了索引的加减等等效果比较大小(jumpgame6.cpp) unordered_multimap<int, std::pair<int, int>> map = {{100, {1, 0}}, {200, {2, 1}}}; map.insert({100, {1, 2}}); map.insert({100, {1, 1}}); auto fds = map.equal_range(100); for (auto bg = fds.first; bg != fds.second; bg++) { cout << bg->first << "\t\t" << bg->second.first << "\t" << bg->second.second << endl; } queue<int> dp; for (int i = 0; i < 5; i++) { dp.push(i); } cout << "dq........" << endl; cout << dp.size() << endl; dp.pop(); dp.pop(); cout << dp.size() << endl; dp.push(100); cout << dp.size() << endl; int n = dp.size(); for (int i = 0; i < n; i++) { cout << dp.front() << "\t"; dp.pop(); } // cout << "dp front......." << dp.front() << endl; // dp.pop(); // cout << dp.front() << endl; // cout << "first for" << endl; // while (!dp.empty()) // { // cout << dp.front() << "\t"; // dp.pop(); // } queue<string> str; char buf[20]; for (int i = 0; i < 5; i++) { snprintf(buf, 20, "value %d", i); str.push(string(buf)); } cout << "string........" << endl << str.size() << endl; for (int i = 0; i < 3; i++) { cout << str.front() << endl; str.pop(); } cout << "############" << endl; snprintf(buf, 20, "later value %d", 10); str.push(buf); snprintf(buf, 20, "later value %d", 20); str.push(buf); while (!str.empty()) { cout << str.front() << endl; str.pop(); } if (int i = 10; i < 9) { cout << "less than 9" << endl; } else if (i == 10) { cout << "equal to 10" << endl; } vector<int> arr = {7, 6, 8, 6, 8, 6, 8, 6, 8, 7}; // vector<int> tmp; // for (int i = 0; i < arr.size(); i++) // { // while (arr[i] == arr[i + 1] && arr[i + 1] == arr[i + 2]) // { // i++; // } // tmp.emplace_back(arr[i]); // } // for (auto i : tmp) // cout << i << "\t"; // cout << endl; // arr = std::move(tmp); // for (auto i : arr) // cout << i << "\t"; // cout << endl; // cout << arr.size() << endl; vector<int> tmp; for (int i = 0; i < arr.size(); i++) { while (arr[i] == arr[i + 1] && arr[i + 1] == arr[i + 2]) { i++; } tmp.emplace_back(arr[i]); } // arr=move(tmp); arr = tmp; for (int i : arr) cout << i << endl; }
true
b70b7959a0d5e3a4016c21cbbb5b352cdba9a64a
C++
furkanyildiz/Data_Glass_Project_Bil396
/Old Versions/Pong__/gameplay.cpp
UTF-8
11,301
2.5625
3
[]
no_license
#include "gameplay.h" #include<iostream> #include <QGraphicsItem> #include <QDebug> #include <QTimer> #include <QEvent> #include <QKeyEvent> #include <math.h> #include"mythread.h" #include "resultwindow.h" int x_pos_of_ball; int y_pos_of_ball; Gameplay::Gameplay(QGraphicsScene & scene, QGraphicsRectItem *p1, QGraphicsRectItem *p2, QGraphicsItem *ball,int gameMode, QGraphicsItem *token, QObject *parent) : QObject(parent), iScene ( scene ), iP1 ( p1 ), iP2 ( p2 ), iBall ( ball ), iToken ( token ), iTokenDirection(+1, -1), iBallDirection ( -3, -3 ), //ilk anda topun hareket yönü iP1Direction( 0 ), iP2Direction( 0 ) { g_mode = gameMode; if(g_mode == 1){ set_pong(); QObject::connect(iTimer, SIGNAL(timeout()), this, SLOT(pong_tick())); } else{ set_arkanoid(); QObject::connect(iTimer, SIGNAL(timeout()), this, SLOT(arkanoid_tick())); } } void Gameplay::set_arkanoid(){ iScene.setSceneRect(0, 0, Constant::GAME_AREA_WIDTH, Constant::GAME_AREA_HEIGHT); iP2->setRect(0,0,Constant::PLAYER2_WIDTH, Constant::PLAYER2_HEIGHT); iScene.addItem(iP2); iScene.addItem(iBall); iP2->setPos(Constant::PLAYER2_POS_X, Constant::PLAYER2_POS_Y-8); iBall->setPos(Constant::GAME_AREA_WIDTH/2, Constant::GAME_AREA_HEIGHT/2); iTimer = new QTimer(this); iTimer->setInterval(5); iTimer->start(); setBlocks(); for(int i=0;i<BLOCK_SIZE;i++){ block_state[i]=true; } std::cout << "arkanoids blocks and boolean array are set" << std::endl; } void Gameplay::set_pong(){ iScene.setSceneRect(0, 0, Constant::GAME_AREA_WIDTH, Constant::GAME_AREA_HEIGHT); iScene.addItem(iP1); iScene.addItem(iToken); // iP2->setRect(0,0,Constant::PLAYER2_WIDTH, Constant::PLAYER2_HEIGHT); iScene.addItem(iP2); iScene.addItem(iBall); iP2->setPos(Constant::PLAYER2_POS_X, Constant::PLAYER2_POS_Y-8); iBall->setPos(Constant::GAME_AREA_WIDTH/2, Constant::GAME_AREA_HEIGHT/2); iToken->setPos(Constant::GAME_AREA_WIDTH/3, Constant::GAME_AREA_HEIGHT/2); iP1->setPos(Constant::PLAYER1_POS_X, Constant::PLAYER1_POS_Y+8); std::cout << "the position of token and p1 are set" << std::endl; iTimer = new QTimer(this); iTimer->setInterval(20); iTimer->start(); } void Gameplay::check_pong_winner(int player){ std::cout << "player" << player << " kazandi" << std::endl; game_over = true; } void Gameplay::check_arkanoid_winner(){ game_over = true; } void Gameplay::check_blocks(){ for(int i = 0; i < 8; ++i){ if(block_state[i] == false) ++block_count; } if(block_count != 8){ block_count = 0; }else if (block_count == 8){ std::cout << "block count : " << block_count << std::endl; game_over = true; } } void Gameplay::arkanoid_tick(){ // if(game_over == true){ // return; // } check_blocks(); qreal newX = iBall->pos().x() + iBallDirection.x(); qreal newY = iBall->pos().y() + iBallDirection.y(); qreal pnewx = iP1->pos().x(); //int gy = MyThread::gyro1; gyro1 = MyThread::getGyro1()* 2; gyro2 = MyThread::getGyro2()* 2; iP1->setPos(gyro1,iP1->pos().y()); if ( ( newX < 0 ) || ( newX + iBall->boundingRect().right() > iScene.sceneRect().right() ) ) { iBallDirection.rx() *= -1; } if ( ( newY < 0 ) || ( newY + iBall->boundingRect().bottom() > iScene.sceneRect().bottom() ) ) { // 1 for hitting the bottom wall, -1 for hitting the top wall if(newY > 0){ p1Score++; if(p1Score > 10) check_arkanoid_winner(); } if(game_over == true && control == 0){ std::cout << "8 block yok edildi" << std::endl; emit goal(5); control++; return; } else if(control == 0) emit goal(newY / fabs(newY)); iBallDirection.ry() *= -1; } if ( ( iP2->collidesWithItem(iBall) ) && ( iBallDirection.y() > 0 )) { iBallDirection.ry() *= -1; } detectCollusion(); iBall->moveBy(iBallDirection.x(), iBallDirection.y()); // iP2->setPos(Constant::PLAYER2_POS_X, Constant::PLAYER2_POS_Y); // 0 orta, 1 en sag, -1 en sola gider if(iP2Direction == 0){ iP2->setPos(Constant::PLAYER2_POS_X, Constant::PLAYER2_POS_Y); }else if(iP2Direction == 1){ iP2->setPos(Constant::GAME_AREA_WIDTH-Constant::PLAYER2_WIDTH, Constant::PLAYER2_POS_Y); } else if(iP2Direction == -1){ iP2->setPos(0, Constant::PLAYER2_POS_Y); } iP2->moveBy(iP2Direction, 0); //qDebug()<<"Ball position:"<<iBall->pos(); x_pos_of_ball=iBall->pos().rx(); y_pos_of_ball=iBall->pos().ry(); MyThread::setBallX(iBall->pos().x()); MyThread::setBallY(iBall->pos().y()); } void Gameplay::pong_tick(){ if(game_over == true){ return; } qreal newX = iBall->pos().x() + iBallDirection.x(); qreal newY = iBall->pos().y() + iBallDirection.y(); qreal newTokenX= iToken->pos().x()+iTokenDirection.x(); qreal newTokenY = iToken->pos().y()+iTokenDirection.y(); qreal pnewx = iP1->pos().x(); qreal p2newx = iP2->pos().x(); //int gy = MyThread::gyro1; gyro1 = MyThread::getGyro1()* 2; //gyro2 = MyThread::getGyro2()* 2; iP1->setPos(gyro1,iP1->pos().y()); //iP2->setPos(gyro2,iP2->pos().y()); if ( ( newX < 0 ) || ( newX + iBall->boundingRect().right() > iScene.sceneRect().right() ) ) { iBallDirection.rx() *= -1; } if ( ( newY < 0 ) || ( newY + iBall->boundingRect().bottom() > iScene.sceneRect().bottom() ) ) { // 1 for hitting the bottom wall, -1 for hitting the top wall if(newY < 0){ p2Score++; std::cout << "player2" << " : " << p2Score << std::endl; if(p2Score == 3){ check_pong_winner(2); // player 2 kazandi } }else{ p1Score++; std::cout << "player1" << " : " << p1Score << std::endl; if(p1Score == 3){ check_pong_winner(1); // player 1 kazandi } } emit goal(newY / fabs(newY)); iBallDirection.ry() *= -1; } if ( ( pnewx < 0 ) || ( pnewx + iP1->boundingRect().right() > iScene.sceneRect().right() ) ) { iP1Direction = 0; } if ( ( p2newx < 0 ) || ( p2newx + iP2->boundingRect().right() > iScene.sceneRect().right() ) ) { iP2Direction = 0; } if ( ( iP2->collidesWithItem(iBall) ) && ( iBallDirection.y() > 0 )) { iBallDirection.ry() *= -1; } ////////Son eklenen token if ( ( newTokenX < 0 ) || ( newTokenX + iToken->boundingRect().right() > iScene.sceneRect().right() ) ) { iTokenDirection.rx() *= -1; } if ( newTokenY < 0 ) { // -1 for hitting the top wall orgin1=orgin1-5; //iP1->setRect(0,0,orgin1,5); iTokenDirection.ry() *= -1; } if( newTokenY + iToken->boundingRect().bottom() > iScene.sceneRect().bottom()){ //hitting bottom orgin2=orgin2-5; //iP2->setRect(0,0,orgin2,5); iTokenDirection.ry() *= -1; } if ( ( iP1->collidesWithItem(iBall) ) && ( iBallDirection.y() < 0 ) ){ iBallDirection.ry() *= -1; } if ( ( iP1->collidesWithItem(iToken) ) && ( iTokenDirection.y() < 0 ) ){ iTokenDirection.ry() *= -1; orgin1=orgin1+5; //iP1->setRect(0,0,orgin1,5); } if ( ( iP2->collidesWithItem(iToken) ) && ( iTokenDirection.y() > 0 ) ){ iTokenDirection.ry() *= -1; orgin2=orgin2+5; //iP2->setRect(0,0,orgin2,5); } if ( ( iBall->collidesWithItem(iToken) ) ){ iTokenDirection.ry() *= -1; iTokenDirection.rx() *= -1; iBallDirection.ry() *= -1; } if ( qrand() % 10 == 0 ){ //iP2Direction = calculateP2Direction(gyro2); }else if(qrand() % 7 == 0){ iP1Direction = calculateP1Direction(gyro1); } iBall->moveBy(iBallDirection.x(), iBallDirection.y()); iToken->moveBy(iTokenDirection.x(), iTokenDirection.y()); // if(iP1Direction==0){ // iP1->setPos(1,5); // }else if(iP1Direction==1){ // iP1->setPos(80,5); // } // else if(iP1Direction==-2){ // iP1->setPos(160,5); // } // else if(iP1Direction==3){ // iP1->setPos(240,5); // } // else{ //iP1->moveBy(iP1Direction, 0); // } iP2->moveBy(iP2Direction, 0); //qDebug()<<"Ball position:"<<iBall->pos(); x_pos_of_ball=iBall->pos().rx(); y_pos_of_ball=iBall->pos().ry(); MyThread::setBallX(iBall->pos().x()); MyThread::setBallY(iBall->pos().y()); } bool Gameplay::eventFilter(QObject *target, QEvent *e) { Q_UNUSED(target); bool handled = false; // if ( e->type() == QEvent::KeyPress ) // { // QKeyEvent *keyEvent = (QKeyEvent *)e; // if ( keyEvent->key() == Qt::Key_Left ) // { // iP1Direction = (iP1Direction == 0 ? -5 : 0); // handled = true; // } // else if ( keyEvent->key() == Qt::Key_Right ) // { // iP1Direction = (iP1Direction == 0 ? 5 : 0); // handled = true; // } // } return handled; } qreal Gameplay::calculateP2Direction(int client_data) { qreal dir = 0; dir=client_data; if((iP2->pos().x()>=98)&&client_data%2!=0){//EGER RAKET EN SAGDAYSA SADECE RAKETI SOLA HAREKET ETTIRECEK KOMUT BEKLEYECEK dir=0;//AKSI HALDE RAKET HAREKET ETMEYECEK } else if(iP2->pos().x()<=0&&client_data%2==0){dir=0;} return dir; } qreal Gameplay::calculateP1Direction(int client_data){ qreal dir = 0; dir=client_data; if((iP1->pos().x()>=98)&&client_data%2!=0){ //EGER RAKET EN SAGDAYSA SADECE RAKETI SOLA HAREKET ETTIRECEK KOMUT BEKLEYECEK dir=0;//AKSI HALDE RAKET HAREKET ETMEYECEK } else if(iP1->pos().x()<=0&&client_data%2==0){dir=0;} return dir; } void Gameplay::setBlocks(){ for(int i=0;i<8;i++){ blocks[i]=new QGraphicsRectItem(0,0,Constant::BLOCK_WIDTH,Constant::BLOCK_HEIGHT); iScene.addItem(blocks[i]); blocks[i]->setBrush(QBrush(Qt::red)); if(i<5) blocks[i]->setPos(i*(Constant::BLOCK_WIDTH + 8)+12,10); else{ blocks[i]->setPos((i%5)*(Constant::BLOCK_WIDTH + 8)+12+Constant::BLOCK_WIDTH,30); } } } void Gameplay::detectCollusion(){ for(int i=0;i<8;i++){ if((blocks[i]->collidesWithItem(iBall))&&block_state[i]==true){ iBallDirection.ry()*=-1; iScene.removeItem(blocks[i]); block_state[i]=false; defaultP2Size=defaultP2Size-5; iP2->setRect(0,0,defaultP2Size,5); std::cout << "bir block yok edildi" << std::endl; } } } /*qreal Gameplay::calculateP2Direction() { qreal dir = 0; if ( iBall->pos().x() + iBallDirection.x() > iP2->sceneBoundingRect().right() ) { // move right dir = 5; } else if ( iBall->pos().x() + iBallDirection.x() < iP2->sceneBoundingRect().left() ) { // move left dir = -5; } return dir;*/
true
17e0976522ce495de889731a77d5a1c8816b0760
C++
jo-va/hop
/src/util/stop_watch.h
UTF-8
404
2.53125
3
[]
no_license
#pragma once #include <time.h> namespace hop { class StopWatch { public: StopWatch(); ~StopWatch(); void start(); void stop(); double get_elapsed_time_s(); double get_elapsed_time_ms(); double get_elapsed_time_us(); double get_elapsed_time_ns(); private: struct timespec m_start_count; struct timespec m_end_count; bool m_stopped; }; } // namespace hop
true
1ad46c64ba8670c4a3f123b511273785f2b3338a
C++
Dahlia-Chehata/Coursera
/Data Structures and Algorithms Specialization/Algorithmic Toolbox/week 3/different_summands.cpp
UTF-8
663
3.140625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector <long long> summands; vector <long long> solve (long long k,long long l) { /**recursion**/ /* if (k<=2*l) { summands.push_back(k); return summands; } summands.push_back(l); solve (k-l,l+1);*/ while (k>2*l) { summands.push_back(l); k-=l; l++; } summands.push_back(k); return summands; } int main() { long long n; cin>>n; vector <long long> x = solve (n,1); cout <<summands.size()<<endl; for (vector<long long>::const_iterator i =summands.begin();i!=summands.end();i++) cout <<*i<<" "; return 0; }
true
658e8c965af23ac3d00b802fad0852cb46a25aa1
C++
yhzhm/Practice
/OJ/OpenJudge/1.7 字符串/1.7-21 单词替换.cpp
UTF-8
1,092
3.359375
3
[]
no_license
/*21:单词替换 查看 提交 统计 提问 总时间限制: 1000ms 内存限制: 65536kB 描述 输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。 输入 输入包括3行, 第1行是包含多个单词的字符串 s; 第2行是待替换的单词a(长度 <= 100); 第3行是a将被替换的单词b(长度 <= 100). s, a, b 最前面和最后面都没有空格. 输出 输出只有 1 行,将s中所有单词a替换成b之后的字符串。 样例输入 You want someone to help you You I 样例输出 I want someone to help you*/ // Created by Hz Yang on 2017.03 #include <bits/stdc++.h> using namespace std; int main() { string a, s1, s2; vector<string> v; while (cin.peek() != '\n') { cin >> a; v.push_back(a); } cin >> s1 >> s2; for (vector<string>::iterator i = v.begin(); i != v.end(); ++i) { if (*i == s1) *i = s2; cout << *i << ' '; } return 0; }
true
f319f567146b61b8fd23aaeb7b3c6f54a05dd0b3
C++
dpkkumr/J-Pet_Code
/code/SignalExtraction.cpp
UTF-8
7,926
2.515625
3
[]
no_license
#include "signalDataTree.h" #include "SignalAnalysisTools.h" #include "SignalExtraction.h" const int chNb = 2; // there are 3 channels on the scope // /home/szymon/data/srodek/ // /home/szymon/data/srodek.root int SignalExtraction( std::string path, int signalsToProcess = 0, bool toPlot = false ) { std::string directoryPath = path; std::string terminalCode = "ls -l "; terminalCode+= directoryPath; terminalCode+="/*ch"; terminalCode+=convertIntToString(chNb); terminalCode+= "* | wc -l"; int totalSignals = -1; if( signalsToProcess == 0 ) totalSignals = atoi( exec( terminalCode).c_str() ); else totalSignals = signalsToProcess; std::string name = path; if( name.back() == '/') name.pop_back(); name += ".root"; std::cout << "Saving to file: " << name << std::endl; signalDataTree tree( name ); int counter = 0; for( int signalNb = 0; signalNb < totalSignals; signalNb++) { if(signalNb%100 == 0) std::cout << signalNb << std::endl; for( int channelNb = 1; channelNb < chNb+1; channelNb++) { if( !checkIfFileExists( makeFilePath(directoryPath, channelNb, signalNb) ) ) { std::cout<<"File does not exist for SignalNb:"<< signalNb<<" ChannelNb: "<<channelNb<<std::endl; continue; } std::pair<std::vector<double>, std::vector<double>> data; std::ifstream dataFile( makeFilePath(directoryPath, channelNb, signalNb).c_str() ); readDataFile( dataFile, data ); dataFile.close(); double baseline = signalAnalysisTools::calculateBaseline(data.second); for(unsigned int index = 0; index < data.second.size(); index++) { data.second[index] = data.second[index] - baseline; } std::vector<double>& Yaxis = data.second; double amplitude = TMath::MinElement(data.second.size(), &Yaxis[0]); double charge = signalAnalysisTools::calculateAreaFromStartingIndex(data, 0); double time = signalAnalysisTools::calculateTimeAtThreshold(data, 0.25*amplitude); double riseTime = signalAnalysisTools::timeRise(data, baseline, amplitude); double fallTime = signalAnalysisTools::timeFall(data, baseline, amplitude); if(counter < 1000 && toPlot ) { generateGraphs( data, channelNb, signalNb, directoryPath); counter++; } if( !tree.setBaseline( baseline, channelNb ) ) continue; if( !tree.setAmplitude( amplitude, channelNb ) ) continue; if( !tree.setCharge( charge, channelNb ) ) continue; if( !tree.setTimeAtThr( time, channelNb ) ) continue; if( !tree.setRiseTime( riseTime, channelNb ) ) continue; if( !tree.setFallTime( fallTime, channelNb ) ) continue; } tree.setFileNumber( signalNb ); tree.fill(); } return 0; } std::string convertIntToString(const int integer) { std::string convertedInt = std::to_string(integer); // to convert int to string return convertedInt; } std::string makeFilePath(const std::string initialPath, const int channelNb, const int eventNb) { std::string pathToFile = initialPath; if( pathToFile.back() != '/' ) pathToFile+= "/"; if( eventNb < 10000 ) pathToFile+="0"; if( eventNb < 1000 ) pathToFile+="0"; if( eventNb < 100 ) pathToFile+="0"; if( eventNb < 10 ) pathToFile+="0"; pathToFile += convertIntToString(eventNb); pathToFile+= "_ch"; if( channelNb > 0 && channelNb < 4 ) pathToFile+= convertIntToString(channelNb); else return ""; pathToFile += ".tsv"; return pathToFile; } void readDataFile( std::ifstream& file, std::pair<std::vector<double>, std::vector<double> >& data ) { std::string test=""; for( int headerLines = 0; headerLines < 0; headerLines++ ) std::getline(file,test); while( !file.eof() ) { double amplitude, time; file >> time >> amplitude; data.first.push_back(time*1E9); data.second.push_back(amplitude*1E3); } } void generateGraphs( std::pair<std::vector<double>, std::vector<double> >& data , const int channelNb, const int eventNb, const std::string path) { TCanvas* c = new TCanvas(); if( data.first.size() == 0 ) return; TGraph* signal = new TGraph( data.first.size(), &data.first[0], &data.second[0] ); //TGraph* signal = new TGraph( data.first.size(), &data.first[0], &data.second[0] ); signal->GetXaxis()->SetTitle("Time [ns]"); signal->GetXaxis()->CenterTitle(); signal->GetYaxis()->SetTitle("Amplitude [mV]"); signal->GetYaxis()->CenterTitle(); std::string graphTitle = setTitleofGraphs( channelNb, eventNb); signal->SetTitle( graphTitle.c_str() ); double base = signalAnalysisTools::calculateBaseline(data.second); TLine* baseline = new TLine(data.first[0], base, data.first[ data.first.size() -1], base ); baseline->SetLineColor(2); baseline->SetLineWidth(8); std::vector<double>& Yaxis = data.second; double amplitude = TMath::MinElement(data.second.size(), &Yaxis[0]); TLine* amplitudeLine = new TLine(data.first[0], amplitude, data.first[ data.second.size() -1], amplitude); amplitudeLine->SetLineColor(5); amplitudeLine->SetLineWidth(8); double timeAtThr = signalAnalysisTools::calculateTimeAtThreshold(data, -50); TLine* threshold = new TLine(data.first[0], -50, timeAtThr, -50); threshold->SetLineColor(3); threshold->SetLineWidth(8); double timeAt10 = signalAnalysisTools::calculateTimeAtThreshold(data, amplitude*0.2); TLine* lineAt10 = new TLine( data.first[0], amplitude*0.2, timeAt10, amplitude*0.2 ); lineAt10->SetLineColor(4); lineAt10->SetLineWidth(3); gPad->SetTicks(1,1); gStyle->SetOptStat(0); signal->Draw("AP"); baseline->Draw(); amplitudeLine->Draw(); threshold->Draw(); lineAt10->Draw(); signal->SetMarkerStyle(23); std::string signalName = makeSignalPath(path, channelNb, eventNb); c->SaveAs(signalName.c_str()); // conversion of string to const char* } std::string makeSignalPath(const std::string initialPath, const int channelNb, const int eventNb) { std::string pathToFile = initialPath; if( pathToFile.back() != '/' ) pathToFile+= "/"; pathToFile+="toPNG/"; pathToFile+= "C"; if( channelNb > 0 && channelNb < 5 ) pathToFile+= convertIntToString(channelNb); else return ""; pathToFile += "_"; if( eventNb < 10000 ) pathToFile+="0"; if( eventNb < 1000 ) pathToFile+="0"; if( eventNb < 100 ) pathToFile+="0"; if( eventNb < 10 ) pathToFile+="0"; pathToFile += convertIntToString(eventNb); pathToFile += ".png";//".root"; return pathToFile; } bool checkIfFileExists(const std::string path) { std::fstream fileCheck( path.c_str() ); if (fileCheck) { //std::cout<<"File exists: " << path <<std::endl; return true; } std::cout<<"File does not exists: " << path <<std::endl; fileCheck.close(); return false; } std::string exec(std::string cmd) { char buffer[128]; std::string result = ""; FILE* pipe = popen(cmd.c_str(), "r"); if (!pipe) throw std::runtime_error("popen() failed!"); try { while (fgets(buffer, sizeof buffer, pipe) != NULL) { result += buffer; } } catch (...) { pclose(pipe); throw; } pclose(pipe); return result; } std::string setTitleofGraphs( const int channelNb, const int eventNb) { std::string pathToFile = "C"; if( channelNb > 0 && channelNb < 5 ) pathToFile+= convertIntToString(channelNb); else return ""; pathToFile += "_"; if( eventNb < 10000 ) pathToFile+="0"; if( eventNb < 1000 ) pathToFile+="0"; if( eventNb < 100 ) pathToFile+="0"; if( eventNb < 10 ) pathToFile+="0"; pathToFile += convertIntToString(eventNb); return pathToFile; }
true
3185465c97237997cc0d37eec8dd69df813c0bd5
C++
BekzhanKassenov/olymp
/NSUTS/2014/H/Main.cpp
UTF-8
3,163
2.609375
3
[]
no_license
/**************************************** ** Solution by NU #2 ** ****************************************/ #include <bits/stdc++.h> using namespace std; #define F first #define S second #define MP make_pair #define all(x) (x).begin(), (x).end() typedef long long ll; typedef unsigned long long ull; typedef long double ld; const double EPS = 1e-9; const double PI = acos(-1.0); const int MOD = 1000 * 1000 * 1000 + 7; const int INF = 2000 * 1000 * 1000; const int MAXN = 200; template <typename T> inline T sqr(T n) { return n * n; } struct Triple { Triple() : x(0), y(0), c(0) { } long long x, y, c; }; char s[MAXN], t[MAXN], temp[MAXN]; int pos; void make(char dest[], char source[]) { int last = 0; for (int i = 0; source[i]; i++) { if (source[i] != '=') dest[last++] = source[i]; else { dest[last++] = '-'; dest[last++] = '('; } } dest[last++] = ')'; } Triple val(char s[]); Triple expr(char s[]); Triple term(char s[]); Triple val(char s[]) { Triple res; if (s[pos] == 'x') { res.x = 1; pos++; return res; } if (s[pos] == 'y') { res.y = 1; pos++; return res; } int num = 0; bool mn = false; if (s[pos] == '-') { pos++; mn = true; } while (isdigit(s[pos])) { num *= 10; num += s[pos] - '0'; pos++; } if (mn) num *= -1; if (s[pos] == 'x') { res.x = num; pos++; } else if (s[pos] == 'y') { res.y = num; pos++; } else res.c = num; return res; } Triple expr(char s[]) { Triple res = term(s); while (s[pos] == '+' || s[pos] == '-') { char sign = s[pos]; pos++; Triple temp = term(s); if (sign == '+') { res.x += temp.x; res.y += temp.y; res.c += temp.c; } else { res.x -= temp.x; res.y -= temp.y; res.c -= temp.c; } } return res; } Triple term(char s[]) { Triple res; if (isdigit(s[pos]) || s[pos] == 'x' || s[pos] == 'y') { Triple temp = val(s); if (s[pos] == '(') { pos++; Triple temp1 = expr(s); temp1.x *= temp.c; temp1.y *= temp.c; temp1.c *= temp.c; pos++; temp = temp1; } res = temp; } else if (s[pos] == '(') { pos++; res = expr(s); pos++; } return res; } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); gets(temp); make(s, temp); gets(temp); make(t, temp); Triple a = expr(s); pos = 0; Triple b = expr(t); if (a.x == 0) swap(a, b); //cout << a.x << ' ' << a.y << ' ' << a.c << endl; //cout << b.x << ' ' << b.y << ' ' << b.c << endl; double y = (b.x * a.c - b.c * a.x + .0) / (b.y * a.x - b.x * a.y + .0); double x = (-a.c - a.y * y) / a.x; printf("%.10lf\n%.10lf\n", x, y); return 0; }
true
a9041e18b255516d14cbf20eba434754de8af581
C++
Reintjuu/GamesProgramming
/CPP/Lecture4Stack/main.cpp
UTF-8
1,200
3.375
3
[]
no_license
#include "MyStack.h" #include <iostream> using namespace std; void main() { MyStack stack; stack.push(8); stack.push(6); stack.push(7); stack.push(5); stack.push(3); stack.push(0); stack.push(9); stack.print(); cout << "The size is: " << stack.size() << endl; cout << "The sum is: " << stack.sum() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; stack.print(); cout << "The size is: " << stack.size_recursive() << endl; cout << "The sum is: " << stack.sum_recursive() << endl; stack.push(11); stack.push(13); stack.print(); cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; cout << "Popping: " << stack.pop() << endl; stack.print(); cout << "The size is: " << stack.size_recursive() << endl; cout << "The sum is: " << stack.sum_recursive() << endl; cin.get(); }
true
507fead90b963e566359fb411ea87a33942b8134
C++
Gospodzin/edami-project
/clustering/src/EpsNeighborhood.h
UTF-8
1,963
3.171875
3
[]
no_license
#ifndef _EPSNEIGHBORHOOD_H #define _EPSNEIGHBORHOOD_H #include "Neighborhood.h" #include "Point.h" template<class T> class EpsNeighborhood : public Neighborhood<T> { private: vector<double> subspacePreferenceVector; int subspacePreferenceDimensionality; public: EpsNeighborhood(){} EpsNeighborhood(T * thePoint, vector<T*> points) : Neighborhood<T>(thePoint, points), subspacePreferenceDimensionality(0) {} double getVarianceAlongAttr(int n); void computeSubspacePreferenceParameters(double delta, double kappa); vector <double> getSubspacePreferenceVector(); int getPreferenceDimensionality(); double getPreferenceWeightedDistanceTo(T * point); }; template<class T> double EpsNeighborhood<T>::getVarianceAlongAttr(int n) { double sum = 0.0; for (typename vector<T*>::iterator oneOfPoints = this->points.begin(); oneOfPoints != this->points.end(); ++oneOfPoints) { double dist = (*(this->thePoint))[n] - (**oneOfPoints)[n]; sum = sum + (dist * dist); } return sum / this->getCount(); } template<class T> void EpsNeighborhood<T>::computeSubspacePreferenceParameters(double delta, double kappa){ for (int i = 0; i < (this->thePoint)->Coordinates.size(); ++i) { double variance = getVarianceAlongAttr(i); if(variance <= delta){ subspacePreferenceVector.push_back(kappa); subspacePreferenceDimensionality++; } else subspacePreferenceVector.push_back(1.0); } } template<class T> vector<double> EpsNeighborhood<T>::getSubspacePreferenceVector(){ return subspacePreferenceVector; } template<class T> int EpsNeighborhood<T>::getPreferenceDimensionality(){ return subspacePreferenceDimensionality; } template<class T> double EpsNeighborhood<T>::getPreferenceWeightedDistanceTo(T * otherPoint){ double sum = 0.0; for (int i = 0; i < (this->thePoint)->Coordinates.size(); ++i) { double diff = (*(this->thePoint))[i] - (*otherPoint)[i]; sum += subspacePreferenceVector[i] * diff * diff; } return sqrt(sum); } #endif
true
2d6e1c7934079d140900ec7f8d479536ef5c773d
C++
wangfuli217/ld_note
/cheatsheet/ops_doc-master/Service/cfaq/example_c/std_copy/main.cpp
UTF-8
818
3.15625
3
[]
no_license
#include <stdio.h> #include <algorithm> #include <vector> int main(int argc, char **argv) { std::vector<int> v1; int ia[] = {1, 2, 3, 4, 5}; std::vector<int> v2; v1.resize(sizeof ia / sizeof(int)); // 这里必须保证目的verctor有足够的空间,copy不会自动增加verctor的空间 std::copy(ia, ia + 5, v1.begin()); // input_last 是最后一个元素+1的位置,类似end()的概念,copy的范围是start ~ last - 1 v2.resize(v1.size()); std::copy(v1.begin(), v1.begin() + v1.size(), v2.begin()); //std::copy(v1.begin(), v1.end(), v2.begin()); for (unsigned int idx = 0; idx < v1.size(); idx++) { printf("v1[%u]:%d ", idx, v1[idx]); } printf("\n"); for (unsigned int idx = 0; idx < v2.size(); idx++) { printf("v2[%u]:%d ", idx, v2[idx]); } printf("\n"); return 0; } 
true
98dcd49056859fddf21e767457d530c666c58995
C++
newmen/qt_cellularDiamondBuilder
/cellsclearer.h
UTF-8
369
2.5625
3
[]
no_license
#ifndef CELLSCLEARER_H #define CELLSCLEARER_H #include "cellsvisitor.h" class CellsClearer : public CellsVisitor { public: CellsClearer() {} void visitComplexCell(ComplexCell &cell); void visitSimpleCell(SimpleCell &cell); private: CellsClearer(const CellsClearer &); CellsClearer &operator= (const CellsClearer &); }; #endif // CELLSCLEARER_H
true
848a4eeef0d41b5728d0d1d2496f734fa144eb1a
C++
OnlyCaptain/leetcode
/1362. Closest Divisors.cpp
UTF-8
649
3.234375
3
[]
no_license
#include <math.h> #include <vector> #include <iostream> using namespace std; class Solution { public: vector<int> closestDivisors(int num) { int ex = (int)sqrt(num+2); vector<int> ans; for (int i = ex; i > 0; i --) { if ((num+2) % i == 0) { ans.push_back(i); ans.push_back((num+2)/i); return ans; } else if ((num+1) % i == 0) { ans.push_back(i); ans.push_back((num+1)/i); return ans; } } return ans; } }; int main() { cout << (int)sqrt(999) << endl; }
true
f53c3c7c8dd92a780f29c557c742a36ff882fb66
C++
GuilhermeSaito/UsingCppToGenerateJS
/main.cpp
UTF-8
1,055
3.109375
3
[]
no_license
#include <fstream> #include <iostream> #include <iomanip> using std::ofstream; #include "nlohmann/json.hpp" using json = nlohmann::json; void createHTML(); int main() { createHTML(); return 0; } void createHTML() { ofstream out("func.js", std::ios::trunc); json j; j["persons"] = { { {"name", "Arudina"}, {"age", "?"} }, { {"name", "Saito"}, {"age", 19} } }; try { // Eh possivel fazer assim, dai eu passo os valores pra la :D //out << "function touched() {document.write('Kyaaa Someone touched me!'); a = 10; b = 11; document.write(a + b);}"; out << "function touched() {" << std::endl << "let text = " << std::setw(4) << j << std::endl << "document.write('Kyaaa Someone touched me!');\nlet jso = JSON.parse(text);\nconsole.log(jso)" << std::endl << "}"; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } out.close(); }
true
b5dd703dd5e71567be67401d15b86236d1cea0be
C++
cuxxie/mycjam
/cj2017qualC.cpp
UTF-8
1,645
3
3
[]
no_license
//codejam2017qualificationC #include <iostream> #include <math.h> #include <vector> #include <stdio.h> #include <time.h> #define LOG2(X) ((unsigned) (8*sizeof (unsigned long long) - __builtin_clzll((X)) - 1)) using namespace std; void calculate(unsigned long long n, unsigned long long k, unsigned long long output[]) { unsigned long maxHeight = LOG2(k); // get the binary tree height unsigned long long baseNum = n>>(maxHeight); // get the base number of the leaf unsigned long long minKBase = pow(2,maxHeight); //get the Base of K (max power of 2 up to K) unsigned long long deltaK = k - minKBase; // get the left behind number e.g. K=17 baseK=16, delta = 1 unsigned long long baseN = baseNum<<(maxHeight); //get the Base of N (used to get the bit which are taken from shift right) unsigned long long deltaN = n-baseN; // get the bit which are shifted right unsigned long long zeros = deltaN+1; // add +1 if(deltaK<zeros) // if deltaK < the taken bit + 1, the baseNum is the large basenum { output[0]=baseNum>>1; if(baseNum%2==0 && output[0]>0) output[1] = output[0]-1; else output[1] = output[0]; } else // else the baseNum is the lower base { baseNum--; output[0]=baseNum>>1; if(baseNum%2==0 && output[0]>0) output[1] = output[0]-1; else output[1] = output[0]; } } int main() { unsigned long long t, n, k; unsigned long long output[2]; cin >> t; for (int i = 1; i <= t; ++i) { cin >> n >> k; calculate(n,k,output); cout << "Case #" << i << ": "<< output[0] << " " << output[1]<<endl; } return 0; }
true
364dd16de615a14673afa2b2881bd09cd662f85c
C++
wengsht/USACO-Acceptor
/section4/section4.1/1.cpp
UTF-8
2,497
2.9375
3
[]
no_license
/* ID: wengsht1 LANG: C++ TASK: cryptcow */ #include <iostream> #include <memory.h> #include <fstream> #include <string> using namespace std; const int MAX = 100; const int MOD = 131071; const int LEN = 47; const string plaintext = "Begin the Escape execution at the Break of Dawn"; ifstream fin("cryptcow.in"); ofstream fout("cryptcow.out"); bool visited[MOD+1]; inline bool ELFHash(string s, int length){ unsigned long h=0,g; for (int i=0; i<length; i++){ h=(h<<4)+s[i]; g=h&0xf0000000l; if(g){ h^=g>>24; } h&=~g; } h = h%MOD; if(visited[h]) return true; else{ visited[h] = true; return false; } } void dfs(string s, int num){ if(plaintext == s){ fout<<1<<" "<<num<<endl; exit(0); } int length = s.length(); if(ELFHash(s, length)) return ; int cnt=0, c_cnt=0, o_cnt=0, w_cnt=0; int c[MAX], o[MAX], w[MAX], label[MAX]; memset(c, 0, sizeof(c)); memset(o, 0, sizeof(o)); memset(w, 0, sizeof(w)); memset(label, 0, sizeof(label)); int i,j,k; label[cnt++] = -1; for(i = 0; i<length; ++i){ if(s[i] == 'C'){ c[c_cnt++] = i; label[cnt++] = i; }else if(s[i] == 'O'){ o[o_cnt++] = i; label[cnt++] = i; }else if(s[i] == 'W'){ w[w_cnt++] = i; label[cnt++] = i; } } label[cnt++] = length; if(c_cnt!=o_cnt || o_cnt!=w_cnt) return; for(i=0; i<cnt-1; ++i){ if(label[i]+1 < label[i+1]){ string sub = s.substr(label[i]+1, label[i+1]-label[i]-1); if(plaintext.find(sub)==string::npos) return; } } for(i=0; i<o_cnt; ++i){ for(j=0; j<c_cnt; ++j){ for(k=w_cnt-1; k>=0; --k){ if(c[j]<o[i] && o[i]<w[k]){ string t1 = s.substr(0, c[j]); string t2 = s.substr(o[i]+1, w[k]-o[i]-1); string t3 = s.substr(c[j]+1, o[i]-c[j]-1); string t4 = s.substr(w[k]+1, length-w[k]); string t = t1+t2+t3+t4; dfs(t, num+1); } } } } } int main(){ string s; getline(fin, s); int length = s.length(); if( (length-LEN)%3 !=0 ){ fout<<"0 0"<<endl; return 0; } dfs(s,0); fout<<"0 0"<<endl; return 0; }
true
36a1a574cfb827a6049b035468f49c63595618cb
C++
elfmedy/vvdn_tofa
/mdk_release_18.08.10_general_purpose/mdk/common/components/kernelLib/MvISP/kernels/localTM/shave/src/cpp/localTM.cpp
UTF-8
2,303
2.515625
3
[]
no_license
/// /// @file localTM.cpp /// @copyright All code copyright Movidius Ltd 2013, all rights reserved. /// For License Warranty see: common/license.txt /// /// @brief Applies a tone mapping function to the Luma channel. /// The mapping function is based on both the original Luma value, /// plus a second local brightness input image /// Local Tone Mapping increases contrast locally, applying a contrast /// curve that is adapted to the local image intensity /// #include "localTM.h" void mvispLocalTM(half** luma_in, u8** bg8, half** output, half *curves, u32 width, u32 run_no) { half *luma, *out; half bg, csel, psel; half alphaCol, alphaRow; unsigned int i, wi; int bgidx; int csel1, csel2, psel1, psel2; static half wt[4][4] = { { 3.0/4096, 9.0/4096, 1.0/4096, 3.0/4096 }, { 9.0/4096, 3.0/4096, 3.0/4096, 1.0/4096 }, { 1.0/4096, 3.0/4096, 3.0/4096, 9.0/4096 }, { 3.0/4096, 1.0/4096, 9.0/4096, 3.0/4096 }, }; luma = *luma_in; out = *output; bgidx = -1; for (i = 0; i < width; i++) { /* * Bilinear upsample of "background" input, and conversion * from U8f to FP16. */ wi = (run_no & 1) << 1 | (i & 1); bg = (half)(float)bg8[0][bgidx] * wt[wi][0] + (half)(float)bg8[0][bgidx+1] * wt[wi][1] + (half)(float)bg8[1][bgidx] * wt[wi][2] + (half)(float)bg8[1][bgidx+1] * wt[wi][3]; /* Pick two curves - two adjacent columns */ csel = bg*8; csel1 = csel; alphaCol = csel - csel1; csel2 = csel1+1; /* * Pick points in curves to interpolate between (row indices). * * Note: It's important that "luma" is >= 0. Otherwise we * could exceed the bounds of the array. Might want to * explicitly clamp "luma" to 0, but it isn't needed if the * input is guaranteed to be >= 0. */ psel = luma[i]*14; psel1 = psel; alphaRow = psel - psel1; psel2 = psel1+1; out[i] = curves[psel1 * 10 + csel1] * (1-alphaRow) * (1-alphaCol) + curves[psel1 * 10 + csel2] * (1-alphaRow) * alphaCol + curves[psel2 * 10 + csel1] * alphaRow * (1-alphaCol) + curves[psel2 * 10 + csel2] * alphaRow * alphaCol; if ((i & 1) == 0) { bgidx++; } } }
true
90bb40b874a8068db205420dba5ed91973549d20
C++
joemlevin/LevinJoseph_CSC17a_43950
/Hmwk/Assignment 4/Assignment 4/Circle.h
UTF-8
491
2.78125
3
[]
no_license
/* File: Circle.h * Author: Joseph Levin * Assignment: C++ Assignment 4 - Spring 2015 43950 * Created on May 11, 2015, 3:15 PM */ #ifndef CIRCLE_H #define CIRCLE_H class Circle{ private: float radius; const static float pi = 3.14159f; public: Circle(); Circle(float); void setRadius(float); float getRadius(); float getArea(); float getDiameter(); float getCircumference(); }; #endif /* CIRCLE_H */
true
ca30bdc3a5d2fc27f61e6bda1a3d8be055c4d737
C++
Aehcaoiggc/notes-of-learning-with-luogu
/主题库/入门/P1047 [NOIP2005 普及组] 校门外的树.cpp
UTF-8
482
2.65625
3
[]
no_license
#include <iostream> using namespace std; int a[10001]; int main() { int l, m; cin >> l >> m; for (int i = 0; i <= l; ++i) { a[i] = 1; } int x, y; for (int i = 1; i <= m; ++i) { cin >> x >> y; for (int j = x; j <= y; ++j) { a[j] = 2; } } int sum = 0; for (int i = 0; i <= l; ++i) { if (a[i] == 1) { sum++; } } cout << sum; return 0; }
true
8751cd3c2284cea14835d14115547b71062c5f5f
C++
joscame/Bingo
/bingogame.h
UTF-8
1,548
2.6875
3
[]
no_license
#ifndef BINGOGAME_H #define BINGOGAME_H #include <vector> #include <cstdio> #include <iostream> #include <cstdlib> #include "singing_square.h" class BingoGame { private: size_t numero_cartones; size_t contador_de_impresos = 0; size_t winners = 0; std::string name; std::vector < std::string > words; std::vector < size_t > the_winners; bool nums = true; public: BingoGame(size_t cartones, const char* fill_words = ""); BingoGame(const char *fill_words); public: bool imprimir_cartones(const char *cstr); int card_shuffle(); bool crear_vector(const char* fill_words); bool vect_shuffle(std::vector<std::string> &temp); bool crear_archivo_fichas(const char *callingcard_name, const char *texts_name); bool sing(const char* symbols_file_name, const char *game_mode, int max_winners, const char *index_file_name); bool check_winners(const char* index_file_name, const char *game_mode, Singing_square& square); bool check_carton(const char* game_mode, std::ifstream& index_file, Singing_square& square); bool check_four_corners(std::ifstream& index_file, Singing_square& square); bool check_straight_line(std::ifstream& index_file, Singing_square& square); bool check_diagonal(std::ifstream& index_file, Singing_square& square); bool check_any_line(std::ifstream& index_file, Singing_square& square); bool check_roving_L(std::ifstream& index_file, Singing_square& square); bool check_blackout(std::ifstream& index_file, Singing_square& square); bool revisar_ganador(size_t the_winner); }; #endif // BINGOGAME_H
true
4af76319b84d349639a496d4835d624ef8857e7a
C++
Ronak786/helloworld
/third_party/algorithm/tree/findMaxLen/max_len5.cpp
UTF-8
1,879
3.421875
3
[]
no_license
#include<iostream> using namespace std; typedef struct BiTNode { BiTNode *left; BiTNode *right; }BiTNode, *BiTree; int maxDis = 0; void createTree(BiTree &root) { BiTree left1 = new(BiTNode); BiTree right1 = new(BiTNode); left1->left = NULL; left1->right = NULL; right1->left = NULL; right1->right = NULL; root->left = left1; root->right = right1; BiTree left2 = new(BiTNode); left2->left = NULL; left2->right = NULL; BiTree right2 = new(BiTNode); right2->left = NULL; right2->right = NULL; left1->left = left2; left1->right = right2; BiTree left3 = new(BiTNode); left3->left = NULL; left3->right = NULL; BiTree right3 = new(BiTNode); right3->left = NULL; right3->right = NULL; left2->left = left3; left2->right = right3; } void deleteTree(BiTree root) { if(root) { deleteTree(root->left); deleteTree(root->right); delete(root); root = NULL; } } int height(BiTree root) { if(root == NULL) return 0; else return height(root->left) > height(root->right) ? height(root->left) + 1 : height(root->right) + 1; } int max(int a, int b, int c) { int tmp = a > b ? a : b; return tmp > c ? tmp : c; } int treeDistance(BiTree root) { if(root == NULL) return 0; else if(root->left == NULL && root->right == NULL) return 0; int dis = max(height(root->left) + height(root->right), treeDistance(root->left), treeDistance(root->right)); if(maxDis < dis) maxDis = dis; return dis; } int main() { BiTree root = new(BiTNode); root->right = root->left = NULL; createTree(root); cout << "height:" << height(root) << endl; cout << "treeDistance:" << treeDistance(root) << endl; cout << "_____________________" << endl; deleteTree(root); }
true
d7dbb34640314165614c0cbd5fb38deab8ad7dc9
C++
kinochen/MultiTrigger
/multitrigger/libraries/ICGroup.cpp
UTF-8
2,200
2.640625
3
[]
no_license
// // ICGroup.cpp // ICGroup // // Created by kinochen on 12/3/19. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #include "ICGroup.h" #include "Arduino.h" ICGroup::ICGroup(int latch, int clock, int data){ latchPin = latch; clockPin = clock; dataPin = data; } void ICGroup::setup(){ pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); for(int i = 0;i<4;i++){ for(int j = 0;j < 8;j++){ clocks[i][j].setOutputByte(j*2, j*2+1); } } // c1.setOutputByte(0, 1); } void ICGroup::update(){ for(int i = 0;i<4;i++){ for(int j = 0;j < 8;j++){ clocks[i][j].update(); } } // c1.update(); writeOut(); } void ICGroup::writeOut(){ for (int i=0; i<4; i++) { for(int j = 0;j < 8;j++){ setBytes(i,j); } } // setBytes(0); // 送資料前要先把 latchPin 拉成低電位 digitalWrite(latchPin, LOW); for (int i=0; i<4; i++) { passValue(i); } // passValue(0); digitalWrite(latchPin, HIGH); for (int i=0; i<4; i++) { for(int j = 0;j < 8;j++){ setBytes2(i,j); } } digitalWrite(latchPin, LOW); for (int i=0; i<4; i++) { passValue(i); } digitalWrite(latchPin, HIGH); //delay(100); } void ICGroup::passValue(int ic ){ shiftOut(dataPin, clockPin, MSBFIRST, highByte(HC595[ic]) ); shiftOut(dataPin, clockPin, MSBFIRST, lowByte( HC595[ic]) ); } void ICGroup::setBytes(int ic,int c){ bitWrite(HC595[ic], clocks[ic][c].getLOutByte() ,clocks[ic][c].writeLOut()); bitWrite(HC595[ic], clocks[ic][c].getROutByte() ,clocks[ic][c].writeROut()); } void ICGroup::setBytes2(int ic,int c){ bitWrite(HC595[ic], clocks[ic][c].getLOutByte() ,0); bitWrite(HC595[ic], clocks[ic][c].getROutByte() ,0); } void ICGroup::setInterval(int ic,int clock,int interValue){ clocks[ic][clock].setInterval(interValue); }
true
cf3fa71a5e549f7246dea1bfa93020e9f1ae20ac
C++
Liusihan-1/c100
/兔子繁殖问题.cpp
UTF-8
339
2.96875
3
[]
no_license
#include<stdio.h> long fun(int month) { if(month==1||month==2) { return 1; } else { return fun(month-1)+fun(month-2); } } int main() { int n,sum=0,mon=0; scanf("%d",&n); do { mon++; if(mon==1||mon==2) { sum=1; } else { sum=fun(mon-1)+fun(mon-2); } } while(sum<n); printf("%d\n",mon); return 0; }
true
bdb2965d41be1b930daecc2d4d78c956fe4e7b91
C++
KartikDholakia/CP-KartikDholakia
/Contests/FB HackerCup 2020/Qualification Round/Problem A Travel Restrictions.cpp
UTF-8
1,545
2.609375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef unsigned long long ll; typedef short int st; #define mod 1000000007 #define MAX 1000001 //Problem A: Travel Restrictions void solve() { st n, i, j; cin >> n; vector<char> I(n); vector<char> O(n); vector<vector<char>> ans; for (i = 0; i < n; i++) { cin >> I[i]; } for (i = 0; i < n; i++) { cin >> O[i]; } for (i = 0; i < n; i++) { ans.push_back(vector<char> ()); for(j = 0; j < n; j++) { ans[i].push_back('x'); } } for (i = 0; i < n; i++) { for (j = i; j < n; j++) { if (i == j) ans[i][j] = 'Y'; else if (ans[i][j-1] == 'N') ans[i][j] = 'N'; else { if (O[j-1] == 'Y' && I[j] == 'Y') ans[i][j] = 'Y'; else ans[i][j] = 'N'; } } if (i > 0) { for (j = i-1; j >= 0; j--) { if (ans[i][j+1] == 'N') ans[i][j] = 'N'; else { if (O[j+1] == 'Y' && I[j] == 'Y') ans[i][j] = 'Y'; else ans[i][j] = 'N'; } } } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { cout << ans[i][j]; } cout << "\n"; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("error.txt", "w", stderr); freopen("output.txt", "w", stdout); //freopen is used to associate a file with stdin or stdout stream in C++ #endif st t = 1; cin >> t; for (st i = 0; i < t; i++) { cout << "Case #" << i+1 << ":\n"; solve(); } // cerr << "time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl; return 0; }
true
8b5a6fb82fd4d0ce119b1dd0f883502d86fa7c5c
C++
ertugrulaypek-zz/METU-Computer-Engineering
/CENG213-Data Structures/HW2/title_comparator.hpp
UTF-8
366
2.671875
3
[ "MIT" ]
permissive
#ifndef _title_h__ #define _title_h__ #include "book.hpp" #include <cstring> class TitleComparator { public: bool operator( ) (const Book::SecondaryKey & key1, const Book::SecondaryKey & key2) const { //if key1 is less than key2 wrt specifications //return true //otherwise //return false } }; #endif
true
06074e67f7fb4ad68c9437e271bb3fa8a009f0f1
C++
AndroidHot/CppPrimer5
/ch17/ex17_35.cpp
UTF-8
271
2.5625
3
[]
no_license
#include <cmath> #include <iostream> int main(int argc, char const *argv[]) { std::cout << std::showbase << std::hexfloat << std::uppercase << std::sqrt(2) << std::noshowbase << std::defaultfloat << std::nouppercase << std::endl; return 0; }
true
e2ecc12da18f59d332648b93881b39ea9439cc6d
C++
ArturoBurela/DataStructures
/LinkedLists/test_vector_list.cpp
UTF-8
850
3.53125
4
[]
no_license
#include<iostream> #include<string> #include "LinkedList.h" #include "Vector3D.h" void listTest(); Vector3D vectorAddition(const LinkedList<Vector3D> & vector_list); int main(){ listTest(); return 0; } void listTest(/* arguments */) { Vector3D result; //Create the list that holds the vectors LinkedList<Vector3D> vector_list; vector_list.insertTail(Vector3D(3.6,7.2,8.1)); vector_list.insertTail(Vector3D(7.12,23.54,34.2)); vector_list.insertTail(Vector3D(232,23,234123)); vector_list.printList(); result = vectorAddition(vector_list); std::cout << "The addition of all vectors is: " << result << std::endl; } Vector3D vectorAddition(const LinkedList<Vector3D> & vector_list){ Vector3D result; for (int i = 0; i < vector_list.getLength(); i++) { result += vector_list.getDataAtPosition(i); } return result; }
true
605ee17bfabec94a977742acc37fd6fcc0086831
C++
solomonwzs/leetcode
/cpp/src/recover_binary_search_tree.cpp
UTF-8
1,160
3.0625
3
[]
no_license
#include <vector> #include "leetcode.h" using namespace std; using namespace leetcode; #define xor_swap(_a, _b) do{\ _a=_a xor _b;\ _b=_a xor _b;\ _a=_a xor _b;\ } while(0) class Solution{ public: void recoverTree(TreeNode *root){ vector<TreeNode *> sort; inorder_traversal(root, sort); int a=-1; int b=-1; for (int i=0; i<(int)sort.size()-1; ++i){ if (sort[i]->val>sort[i+1]->val){ if (a==-1){ a=i; } else{ b=i; } } } b=b==-1?a+1:b+1; xor_swap(sort[a]->val, sort[b]->val); } private: void inorder_traversal(TreeNode *node, vector<TreeNode *> &out){ if (node){ inorder_traversal(node->left, out); out.push_back(node); inorder_traversal(node->right, out); } } }; int main(int argc, char **argv){ // vector<TreeNode *> v; // new_vector_treenode(v, 7); // v[3]->left=v[1]; // v[3]->right=v[5]; // v[1]->left=v[6]; // v[1]->right=v[2]; // v[5]->left=v[4]; // v[5]->right=v[0]; // print_tree(v[3]); // Solution s; // s.recoverTree(v[3]); // print_tree(v[3]); // delete_vectot_obj(v); return 0; }
true
6b4e982938dab80ddb5624f6a0f2e92e8102e3f2
C++
KhanShaheb34/Solved-OJ-Problems
/LightOJ/1028 - Trailing Zeroes (I).cpp
UTF-8
1,316
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long #define FastIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); const ll MAX_SIZE = 1000010; vector<ll> isprime(MAX_SIZE, true); vector<ll> primes; vector<ll> SPF(MAX_SIZE); void manipulated_seive(int N) { isprime[0] = isprime[1] = false; for (ll int i = 2; i < N; i++) { if (isprime[i]) { primes.push_back(i); SPF[i] = i; } for (ll int j = 0; j < (int)primes.size() && i * primes[j] < N && primes[j] <= SPF[i]; j++) { isprime[i * primes[j]] = false; SPF[i * primes[j]] = primes[j]; } } } map<ll, ll> primeFact(ll n) { map<ll, ll> facts; for (auto p : primes) { if (p * p > n) break; while (n % p == 0) { facts[p]++; n /= p; } } if (n >= 2) facts[n]++; return facts; } int main() { FastIO; manipulated_seive(MAX_SIZE); ll t; cin >> t; for (ll i = 0; i < t; i++) { ll x, ans = 1; cin >> x; map<ll, ll> facts = primeFact(x); for (auto kv : facts) ans *= (kv.second + 1); cout << "Case " << i + 1 << ": " << ans - 1 << endl; } return 0; }
true
2f7557d9c5c347fc11bf768988588c5c2446f738
C++
lcsszz/Samples
/build/lcore/Sort.h
UTF-8
4,992
2.796875
3
[]
no_license
#ifndef INC_LCORE_SORT_H__ #define INC_LCORE_SORT_H__ /** @file Sort.h @author t-sakai @date 2011/12/31 create */ #include "lcore.h" namespace lcore { template<class T> struct SortCompFuncType { typedef bool(*SortCmp)(const T& lhs, const T& rhs); }; template<class T> bool less(const T& lhs, const T& rhs) { return (lhs<rhs); } //------------------------------------------------ //--- //--- insertionsort //--- //------------------------------------------------ /** Uはbool operator(const T& a, const T& b) const{ return a<b;}が必要 */ template<class T, class U> void insertionsort(s32 n, T* v, U func) { for(s32 i=1; i<n; ++i){ for(s32 j=i; 0<j; --j){ s32 k = j-1; if(func(v[j], v[k])){ lcore::swap(v[j], v[k]); }else{ break; } } } } template<class T> void insertionsort(s32 n, T* v) { insertionsort(n, v, less<T>); } //------------------------------------------------ //--- //--- heapsort //--- //------------------------------------------------ /** Uはbool operator(const T& a, const T& b) const{ return a<b;}が必要 */ template<class T, class U> void heapsort(s32 n, T* v, U func) { LASSERT(0<=n); --v; s32 i, j; T x; for(s32 k=n>>1; k>=1; --k){ i=k; x = v[k]; while((j=i<<1)<=n){ if(j<n && func(v[j], v[j+1])){ ++j; } if(!func(x, v[j])){ break; } v[i] = v[j]; i = j; } v[i] = x; } while(n>1){ x = v[n]; v[n] = v[1]; --n; i = 1; while((j=i<<1)<=n){ if(j<n && func(v[j], v[j+1])){ ++j; } if(!func(x, v[j])){ break; } v[i] = v[j]; i = j; } v[i] = x; } } template<class T> void heapsort(s32 n, T* v) { heapsort(n, v, less<T>); } //------------------------------------------------ //--- //--- quicksort //--- //------------------------------------------------ /** Uはbool operator(const T& a, const T& b) const{ return a<b;}が必要 */ template<class T, class U> void quicksort(s32 n, T* v, U func) { static const s32 SwitchN = 47; if(n<SwitchN){ insertionsort(n, v, func); return; } s32 i0 = 0; s32 i1 = n-1; T pivot = v[ (i0+i1)>>1 ]; for(;;){ while(func(v[i0], pivot)){ ++i0; } while(func(pivot, v[i1])){ --i1; } if(i1<=i0){ break; } lcore::swap(v[i0], v[i1]); ++i0; --i1; } if(1<i0){ quicksort(i0, v, func); } ++i1; n = n-i1; if(1<n){ quicksort(n, v+i1, func); } } template<class T> void quicksort(s32 n, T* v) { quicksort(n, v, less<T>); } //------------------------------------------------ //--- //--- introsort //--- //------------------------------------------------ /** Uはbool operator(const T& a, const T& b) const{ return a<b;}が必要 */ template<class T, class U> void introsort(s32 n, T* v, s32 depth, U func) { static const s32 SwitchN = 47; if(n<SwitchN){ insertionsort(n, v, func); return; } if(depth<=0){ heapsort(n, v, func); return; } s32 i0 = 0; s32 i1 = n-1; T pivot = v[ (i0+i1)>>1 ]; for(;;){ while(func(v[i0], pivot)){ ++i0; } while(func(pivot, v[i1])){ --i1; } if(i1<=i0){ break; } lcore::swap(v[i0], v[i1]); ++i0; --i1; } --depth; if(1<i0){ introsort(i0, v, depth, func); } ++i1; n = n-i1; if(1<n){ introsort(n, v+i1, depth, func); } } template<class T, class U> void introsort(s32 n, T* v, U func) { s32 depth = 0; s32 t = n; while(1<t){ ++depth; t >>= 1; } introsort(n, v, depth, func); } template<class T> void introsort(s32 n, T* v) { introsort(n, v, less<T>); } } #endif //INC_LCORE_SORT_H__
true
282d78a74aabfe18d61121bf8bbb2ce3e80d9ffd
C++
itewqq/myCpp
/math/所有因子之和,快速幂溢出,素因子分解,逆元.cpp
UTF-8
1,916
2.671875
3
[]
no_license
第一个错误是没有分清每一步里是对谁取模,实际上利用逆元的时候是对mb取模,而其他运算的时候则是对MOD取模,这个是第一个错误 另外,需要对取模的结果加上模(为什么? 第二个就是没想到快速幂会中间结果会超出int64,因为这时候的模是mb,而mb可能相当大,即mb的平方是有可能超出int64的 记住模值超过int的话平方快速幂就可能超过int64! 此时用了一种神奇的类似于快速幂的二分乘法算法,解决了 //poj1845 //#include<bits/stdc++.h> #include<iostream> #include<cmath> #include<cstdio> #include<cstring> #include<vector> #include<string> #include<set> #include<map> #include<queue> using namespace std; typedef long long ll; const int MOD=9901; ll multi(ll a,ll b,ll m) { ll ans = 0; a %= m; while(b) { if(b & 1) { ans = (ans + a) % m; b--; } b >>= 1; a = (a + a) % m; } return ans; } ll qpow(ll a,ll b,ll mb) { ll ans=1; a%=mb; while(b) { if(b&1) ans=multi(ans,a,mb); a=multi(a,a,mb); b>>=1; } return ans; } int p[10001]; int n[10001]; int main() { ll A,B; cin>>A>>B; int k=0; if(A%2==0) { p[++k]=2; n[k]=0; while(!(A%2)) { n[k]++; A/=2; } } for(int i=3;i*i<=A;i+=2) { if(A%i==0) { p[++k]=i; n[k]=0; while(!(A%i)) { n[k]++; A/=i; } } } if(A!=1) { p[++k]=A; n[k]=1; } ll mb; ll ans=1; for(int i=1;i<=k;i++) { mb=(ll)MOD*(ll)(p[i]-1); ans*=(qpow(p[i],B*n[i]+1,mb)%mb+mb-1)/(p[i]-1); ans%=MOD; } cout<<ans<<endl; return 0; }
true
9fc44ec92a4b336443a307a7084c900d0966dd74
C++
40174030/AGE-Week-1-Project
/src/SettingsMenu.cpp
UTF-8
3,473
2.84375
3
[ "Apache-2.0" ]
permissive
#include "stdafx.h" #include "SettingsMenu.h" #include "Game.h" SettingsMenu::MenuOptions SettingsMenu::Show(sf::RenderWindow& window) { selection = Back_to_Main; sf::Texture image; if (image.loadFromFile("res/img/Settings_Temp.png") != true) { throw std::invalid_argument("FAILED TO LOAD: SettingsMenu"); } sprite.setTexture(image); highlight.setSize(sf::Vector2f(700.0f, 135.0f)); highlight.setOutlineColor(sf::Color(255, 255, 0)); highlight.setFillColor(sf::Color::Transparent); highlight.setOutlineThickness(10.0f); highlight.setPosition(highlightBack); window.draw(sprite); return GetMenuResponse(window); } SettingsMenu::MenuOptions SettingsMenu::GetMenuResponse(sf::RenderWindow& window) { sf::Event menuEvent; while (true) { window.clear(); window.draw(sprite); window.draw(highlight); window.display(); while (window.pollEvent(menuEvent)) { if (sf::Joystick::isConnected(0)) { float y = sf::Joystick::getAxisPosition(0, sf::Joystick::PovY); float y2 = sf::Joystick::getAxisPosition(0, sf::Joystick::Y); if (y > 15) MoveUp(); else if (y < -15) MoveDown(); else if (y2 > 15) { if (!stickHeld) { MoveDown(); stickHeld = true; } } else if (y2 < -15) { if (!stickHeld) { MoveUp(); stickHeld = true; } } else if (sf::Joystick::isButtonPressed(0, 0)) { if (!buttonHeld) return selection; } else if (sf::Joystick::isButtonPressed(0, 1)) return Back_to_Main; else { stickHeld = false; buttonHeld = false; } moveHighlight(window, selection); } else { if (menuEvent.type == sf::Event::EventType::KeyPressed && menuEvent.key.code == sf::Keyboard::Escape) return Back_to_Main; if (menuEvent.type == sf::Event::EventType::KeyReleased && eligibleKeyPressed) { eligibleKeyPressed = false; keyHeld = false; } if (!keyHeld) { if (menuEvent.type == sf::Event::EventType::KeyPressed && menuEvent.key.code == sf::Keyboard::Space) { eligibleKeyPressed = true; keyHeld = true; return selection; } else if (menuEvent.type == sf::Event::EventType::KeyPressed && menuEvent.key.code == sf::Keyboard::Down) { MoveDown(); moveHighlight(window, selection); } else if ((menuEvent.type == sf::Event::EventType::KeyPressed && menuEvent.key.code == sf::Keyboard::Up)) { MoveUp(); moveHighlight(window, selection); } else if (menuEvent.type == sf::Event::Closed) { eligibleKeyPressed = true; keyHeld = true; return Quit_Game; } } } } } } void SettingsMenu::moveHighlight(sf::RenderWindow& window, SettingsMenu::MenuOptions newSelection) { switch (newSelection) { case Full_HD: { highlight.setPosition(highlightFullHD); break; } case HD: { highlight.setPosition(highlightHD); break; } case SD: { highlight.setPosition(highlightSD); break; } case Back_to_Main: { highlight.setPosition(highlightBack); break; } } } void SettingsMenu::MoveUp() { eligibleKeyPressed = true; keyHeld = true; selection = static_cast<MenuOptions>(selection - 1); if (selection == -1) selection = Back_to_Main; } void SettingsMenu::MoveDown() { eligibleKeyPressed = true; keyHeld = true; selection = static_cast<MenuOptions>((selection + 1) % (Back_to_Main + 1)); }
true
328d19f7cc42edb2f8d21b5775e0940d8d7fa66f
C++
CyberSmart02/competitive-programming
/Interview Bit/Spiral Order Matrix II.cpp
UTF-8
589
2.984375
3
[]
no_license
vector<vector<int> > Solution::generateMatrix(int n) { vector<vector<int>> sol; for(int i=0;i<n;i++) { vector<int> arr(n,0); sol.push_back(arr); } int val=1; for(int r1=0,r2=n-1,c1=0,c2=n-1;r1<=r2;) { for(int i=c1;i<=c2;i++) sol[r1][i]=val++; r1++; for(int i=r1;i<=r2;i++) sol[i][c2]=val++; c2--; for(int i=c2;i>=c1;i--) sol[r2][i]=val++; r2--; for(int i=r2;i>=r1;i--) sol[i][c1]=val++; c1++; } return sol; }
true
fa7b2d4fe06c0a6c8974c8a0a5893ab3f59eac17
C++
abufarhad/Programming
/AAA (CODE) Programming tools(Fuad)/dfs_component.cpp
UTF-8
651
2.84375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool vis[100]; vector<int>v[100]; void dfs(int source) { if(vis[source]==false){ vis[source]=true; for(int i=0;i<v[source].size();i++){ dfs(v[source][i]); } } } int main() { int n_node,n_edge; cin>>n_node>>n_edge; int t1,t2; for(int i=0;i<n_edge;i++) { cin>>t1>>t2; v[t1].push_back(t2); v[t2].push_back(t1); } int component=0; for(int i=1;i<=n_node;i++){ if(vis[i]==false){ dfs(i); component++; } } cout<<"COMPONENT : "<<component<<endl; return 0; }
true
a5d291c7326ad172ab3a294847de665c6c60b16f
C++
SnaebjornB/MainAssignment
/MainAssignment/include/Services/salesperson_service.h
UTF-8
942
2.515625
3
[]
no_license
#ifndef SALESPERSON_SERVICE_H #define SALESPERSON_SERVICE_H #include <vector> #include <iostream> #include <string> #include "vectors.h" #include "salesperson_repo.h" #include "pizza.h" #include "orders.h" #include "InvalidNameEx.h" #include "InvalidPhonenumberEx.h" using namespace std; class Salesperson_service { public: Salesperson_service(); Vectors read_types(Vectors& vectors, string type); void get_base_price(Pizza& pizza); void write_order(Orders& orders, string location); void add_order(Orders& orders, string location); Vectors read_locations(Vectors& vectors); Vectors read_orders(Vectors& vectors, string& status, string location); private: Salesperson_repo salesperson_repo; Pizza pizza; InvalidNameException invalidNameException; InvalidPhonenumberException invalidPhonenumberException; }; #endif // SALESPERSON_SERVICE_H
true
9d18a96ac1be2d9cb5b90fb3704044e981ba11c8
C++
DengHaoyu/OI
/P4147.cpp
UTF-8
1,523
2.53125
3
[]
no_license
// // Created by dhy on 19-2-13. // #include <cstring> #include <cstdio> int read(){ int x = 0,f = 1; static char c = getchar(); while(c<'0'||c>'9'){ if(c=='-')f = -1;c = getchar(); } while(c>='0'&&c<='9'){ x = (x<<1)+(x<<3)+c-'0';c = getchar(); } return x*f; } const int MAXN = 1010; int up[MAXN][MAXN],left[MAXN][MAXN],right[MAXN][MAXN]; char map[MAXN][MAXN]; char s[5]; inline int max(int a,int b){return a>b?a:b;} inline int min(int a,int b){return a<b?a:b;} int main(){ int n = read(),m = read(); for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ scanf("%s",s); map[i][j] = s[0]; up[i][j] = 1;right[i][j] = left[i][j] = j; } } for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(map[i][j] == 'F'&&map[i][j-1]=='F'){ left[i][j] = left[i][j-1]; } } } for(int i = 1;i<=n;i++){ for(int j = m-1;j>=1;j--){ if(map[i][j] == 'F'&&map[i][j+1]=='F'){ right[i][j] = right[i][j+1]; } } } int ans = 0; for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(i>1&&map[i][j]=='F'&&map[i-1][j]=='F'){ right[i][j] = min(right[i-1][j],right[i][j]); left[i][j] = max(left[i-1][j],left[i][j]); up[i][j] = up[i-1][j]+1; } ans = max(ans,up[i][j]*(right[i][j]-left[i][j]+1)); } } printf("%d",ans*3); return 0; }
true
d95459e73bc3dfbe106f8e0fa503f4eca7c83a49
C++
HekpoMaH/Olimpiads
/Shumen AiB/nadahva6to/g.cpp
UTF-8
541
2.8125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct forma{ int sum; char name; }; forma f[9]; bool cmp(forma fi,forma se){ return fi.sum<se.sum; } int main(){ int a,b,c; cin>>a>>b; f[1].sum=a+b; f[1].sum*=2; f[1].name='P'; cin>>a>>b>>c; f[2].sum=a+b+c; f[2].name='T'; cin>>a; f[3].sum=4*a; f[3].name='K'; sort(f+1,f+4,cmp); for(int i=1;i<=2;i++){ if(f[i].sum==f[i+1].sum){ cout<<"NO\n"; exit(0); } } cout<<f[1].name<<" "<<f[2].name<<" "<<f[3].name<<"\n"; }
true
924cda3682367ec1cd99632cb072745d3245542d
C++
Li-Crazy/-Image-Processing-
/9/2d_dft.cpp
UTF-8
1,341
2.859375
3
[]
no_license
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #define M 128 #define N 128 #define Maxgray 255 double Pi; struct Complex { double real; double img; }; void setimage(int data[M][N]) { srand((int)time(0)); for(int i=0;i<M;i++) for(int j=0;j<N;j++) data[i][j]=rand()%Maxgray; } void fft(int data[M][N],Complex dst[M][N]) { clock_t start,end; start=clock(); int m,n,x,y; double t1cos,t1sin,t2cos,t2sin; double uxvy; for(m=0;m<M;m++) for(n=0;n<N;n++) { t2cos=0.0; t2sin=0.0; for(x=0;x<M;x++) { for(y=0;y<N;y++) { uxvy=m*x+n*y; uxvy=2.0*Pi*uxvy; t1cos=cos(uxvy/M); t1sin=-sin(uxvy/M); t2cos=t2cos+data[x][y]*t1cos; t2sin=t2sin+data[x][y]*t1sin; } dst[m][n].real=t2cos; dst[m][n].img=t2sin; } } end=clock(); printf("DFT use time:%lf second\n ",double(end-start)/CLOCKS_PER_SEC); } void ffttrans(Complex dst[M][N],int imagefft[M][N]) { for(int m=0;m<M;m++) for(int n=0;n<N;n++) imagefft[m][n]=sqrt(dst[m][n].real*dst[m][n].real+dst[m][n].img*dst[m][n].img)/M; } int main() { struct Complex dst[M][N]; int image[M][N]; int imagefft[M][N]; system("clear"); Pi=atan(1)*4.0; printf("SET image......\n"); setimage(image); printf("waiting for foriour tansformation......\n"); fft(image,dst); ffttrans(dst,imagefft); }
true
181543b237978d4ba26d41b0bf6623d72343e7f1
C++
jqk6/CodeArchive
/Kattis/racingalphabet.cpp
UTF-8
602
2.671875
3
[]
no_license
#include<iostream> #include<iomanip> #include<cmath> #include<algorithm> using namespace std; string ring="ABCDEFGHIJKLMNOPQRSTUVWXYZ \'"; double dis(char a,char b){ double aa=ring.find(a),bb=ring.find(b); if(aa>bb)swap(aa,bb); return min(bb-aa,aa+28-bb)/28*4*M_PI; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string quote; int n; double ans; cin>>n; cin.ignore(); while(n--){ ans=0; getline(cin,quote); for(int i=0;i<quote.size()-1;i++){ ans+=dis(quote[i],quote[i+1]); } ans+=quote.size(); cout<<setprecision(10)<<fixed<<ans<<'\n'; } return 0; }
true
018b86ea84eb0e217cb8faed2bced38818a8d0c9
C++
rcore-os-infohub/ossoc2020-VitalyAnkh-daily
/Notebook/cpp_primer/ch5/ex_5_23_add_and_divide_tuned.cpp
UTF-8
460
3.359375
3
[]
no_license
#include <iostream> #include <stdexcept> int main() { int a, b; std::cout << "请输入两个数字: " << std::endl; std::cin >> a >> b; int q; // try // { // 不要写成 b = 0 if (b == 0) { throw std::runtime_error("The second argument must not be 0!"); } else { q = a / b; } // } std::cout << "第一个数字除以第二个数字的商是: " << q << std::endl; return 0; }
true
ab95f5bb26cc1e52d79abefde12ea4abd049a06a
C++
zxy0728/gitProject
/BinaryTree.cpp
UTF-8
5,542
3.421875
3
[]
no_license
#include <iostream> //树 #include <cstring> #include <stack> #include <queue> using namespace std; int i=0; struct BinaryNode { int data; BinaryNode *left; BinaryNode *right; }; class BinaryTree { private: BinaryNode *root; public: explicit BinaryTree(); BinaryNode * createBTree(); virtual ~BinaryTree(); void deleteBTree(BinaryNode *root); BinaryNode * returnroot(); void setroot(BinaryNode *r); void preorder(BinaryNode *root); //前序遍历 void inorder(BinaryNode *root); //中序遍历 void postorder(BinaryNode *root); //后序遍历 int BTreeSize(BinaryNode *r); //求节点个数 int BTreeleaves(BinaryNode *r); //求叶子节点数 //int BTreeHeight(BinaryNode *r); //求树高 int BTreeDepth(BinaryNode *r); //求深度 void addTreeNode(BinaryNode *r,BinaryNode *node); //添加节点 BinaryNode * findTreeNode(BinaryNode *r,int data); void DFS(BinaryNode *root); //深度优先遍历 void BFS(BinaryNode *root); //广度优先遍历 }; BinaryTree::BinaryTree() { this->root=createBTree(); } BinaryNode * BinaryTree::createBTree() { BinaryNode *T; int c; cin>>c; if(c==-1) { T=NULL; } else { T=new BinaryNode; T->data=c; T->left=NULL; T->right=NULL; if(i==0) { root=T; i++; } T->left=createBTree(); T->right=createBTree(); } return T; } BinaryTree::~BinaryTree() { } void BinaryTree::deleteBTree(BinaryNode *root) { if(root==NULL) return; else { deleteBTree(root->left); deleteBTree(root->right); delete root; root=NULL; } } BinaryNode * BinaryTree::returnroot() { return root; } void BinaryTree::setroot(BinaryNode *r) { root=r; } void BinaryTree::preorder(BinaryNode *r) { if(r!=NULL) { cout<<r->data; preorder(r->left); preorder(r->right); } } void BinaryTree::inorder(BinaryNode *r) { if(r!=NULL) { inorder(r->left); cout<<r->data; inorder(r->right); } } void BinaryTree::postorder(BinaryNode *r) { if(r!=NULL) { postorder(r->left); postorder(r->right); cout<<r->data; } } int BinaryTree::BTreeSize(BinaryNode *r) { if(r==NULL) return 0; else return 1+BTreeSize(r->left)+BTreeSize(r->right); } int BinaryTree::BTreeleaves(BinaryNode *r) { if(r==NULL) return 0; else { if(r->left==NULL&&r->right==NULL) return 1; else return(BTreeleaves(r->left)+BTreeleaves(r->right)); } } //int BinaryTree::BTreeHeight(BinaryNode *r) //{ // if(r==NULL) // return 0; // else // { // int m=BTreeHeight(r->left); // int n=BTreeHeight(r->right); // return (m>n)?m+1:n+1; // } //} int BinaryTree::BTreeDepth(BinaryNode *r) { if(r==NULL) return 0; else { int m=BTreeDepth(r->left); int n=BTreeDepth(r->right); return (m>n)?m+1:n+1; } } BinaryNode *BinaryTree::findTreeNode(BinaryNode *r,int data) { BinaryNode *p=NULL; if(r==NULL) { return NULL; } else { if(r->data==data) return r; else if(p=findTreeNode(r->left,data)) { return p; } else if(p=findTreeNode(r->right,data)) return p; else return NULL; } } void BinaryTree::addTreeNode(BinaryNode *r,BinaryNode *node) { BinaryNode *parent; int data; node->left=NULL; node->right=NULL; cout<<"输入该结点父亲数据:"<<endl; cin>>data; parent=findTreeNode(r,data); if(!parent) { cout<<"没有该父亲。"<<endl; return; } cout<<"1、添加该节点到左子树;2、添加该节点到右子树。"<<endl; int input; do { cin>>input; if(input==1||input==2) { switch(input) { case 1: if(parent->left) { cout<<"左子树不为空。"<<endl; } else { parent->left=node; cout<<"数据添加成功!"<<endl; } break; case 2: if(parent->right) { cout<<"右子树不为空。"<<endl; } else { parent->right=node; cout<<"数据添加成功!"<<endl; } break; default: cout<<"选择错误!"<<endl; break; } } }while(input!=1&&input!=2); } void BinaryTree::DFS(BinaryNode *root) { if(root!=NULL) { stack<BinaryNode *> nodestack; nodestack.push(root); BinaryNode *node; while(!nodestack.empty()) { node=nodestack.top(); cout<<node->data; nodestack.pop(); if(node->right) { nodestack.push(node->right); } if(node->left) { nodestack.push(node->left); } } } else return; } void BinaryTree::BFS(BinaryNode *root) { if(root!=NULL) { queue<BinaryNode *> nodequeue; nodequeue.push(root); BinaryNode *node; while(!nodequeue.empty()) { node=nodequeue.front(); nodequeue.pop(); cout<<node->data; if(node->left) { nodequeue.push(node->left); } if(node->right) { nodequeue.push(node->right); } } } else return; } int main() { BinaryTree *BT=new BinaryTree; BinaryNode *T=NULL; cout<<"已建立树:"<<endl; cout<<"前序遍历:"<<endl; BT->preorder(BT->returnroot()); cout<<endl; cout<<"中序遍历:"<<endl; BT->inorder(BT->returnroot()); cout<<endl; cout<<"后序遍历:"<<endl; BT->postorder(BT->returnroot()); cout<<endl; cout<<"叶子节点数:"<<BT->BTreeleaves(BT->returnroot())<<endl; cout<<"节点数:"<<BT->BTreeSize(BT->returnroot())<<endl; cout<<"深度优先遍历:"<<endl; BT->DFS(BT->returnroot()); cout<<endl; cout<<"广度优先遍历:"<<endl; BT->BFS(BT->returnroot()); cout<<endl; cout<<"插入节点:"<<endl; BinaryNode *n=new BinaryNode; cout<<"输入插入数据:"; int data; cin>>data; n->data=data; n->left=NULL; n->right=NULL; BT->addTreeNode(BT->returnroot(),n); return 0; }
true
9bc4227f6eb0a1e3dc2e208205e9b77967513ae6
C++
lpc0503/UVA
/UVA1610/UVA1610.cpp
UTF-8
704
2.578125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define PROBLEM "1610" #define String string int main(void){ #ifdef DBG freopen(PROBLEM ".in", "r", stdin); freopen(PROBLEM ".out", "w", stdout); #endif int n; String str[1005]; String str1, str2; while(scanf("%d", &n) && n){ for(int i = 0 ; i < n ; i++) cin >> str[i]; sort(str, str+n); str1 = str[(n/2)-1]; str2 = str[(n/2)]; String ans = "A"; int idx = 0; while(idx < str1.size()){ while(ans < str1 && ans[idx] < 'Z') ans[idx]++; if(ans[idx] <= 'Z' && str1 <= ans && ans < str2) break; if(str1[idx] != ans[idx]) ans[idx]--; ans += 'A'; idx++; } cout << ans << endl; } return 0; }
true
7b93e78fef64c4455ec91b3281f85d37b7879c0f
C++
Eunomia2016/EunomiaTree
/persistent/log_test.cc
UTF-8
797
2.578125
3
[]
no_license
#include "log.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "log.h" #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define COUNT 4*4096 int main() { char * path = "test.txt"; printf("path %s\n", path); Log log(path); for(int i = 0; i < COUNT; i++) { log.writeLog((char *)&i, sizeof(i)); } log.closelog(); int fd = open(path, O_RDWR|O_CREAT); if(fd < 0) { perror("TEST ERROR: open log file\n"); exit(1); } int tmp = 0; int i = 0; for(i = 0; i < COUNT; i++) { read(fd, (void *)&tmp, sizeof(int)); // printf("%d\n", tmp); if(tmp != i) printf("ERROR i %d tmp %d\n", i , tmp); } printf("FINAL i %d tmp %d\n", i , tmp); return 1; }
true
b8445fe96292df4eff4de85863f905c4a3adddbe
C++
xih108/LeetCode
/112.cpp
UTF-8
1,495
4
4
[]
no_license
// 112. Path Sum // Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. // Note: A leaf is a node with no children. // Use a queue, each element is a pair of TreeNode and the updated sum. // Everytime get the front of the queue, and push its left, right node if there exists, and the int part is sum - the curr val. // If there exists a leaf node has its val == the sum, then return true, else return false. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int sum) { queue<pair<TreeNode*,int>> que; if (root){ que.push(pair<TreeNode*,int>(root,sum)); } while(!que.empty()){ TreeNode* curr = que.front().first; sum = que.front().second; que.pop(); if(curr->left){ que.push(pair<TreeNode*,int>(curr->left,sum - curr->val)); } if(curr->right){ que.push(pair<TreeNode*,int>(curr->right,sum - curr->val)); } // cout<<curr->val<<" "<<sum<<endl; if (!curr->left && !curr->right && sum-curr->val == 0){ return true; } } return false; } };
true
f1935d9e8d90892842faec513c915ea8d54d2588
C++
jeevita06/LeetCode
/array/Valid Mountain Array.cpp
UTF-8
282
2.734375
3
[]
no_license
/* https://leetcode.com/problems/valid-mountain-array/ */ class Solution { public: bool validMountainArray(vector<int>& A) { int n=A.size(),i=0,j=n-1; while(i+1<n&&A[i]<A[i+1]) ++i; while(j>0&&A[j-1]>A[j]) --j; return i>0&&i==j&&j<n-1; } };
true
70a1ce35c964e466cd03c295aff6bcb98d7a0e76
C++
ZhenyingZhu/ClassicAlgorithms
/src/CPP/src/leetcode/RotateArray.cpp
UTF-8
1,087
3.65625
4
[]
no_license
/* * [Source] https://leetcode.com/problems/rotate-array/ * [Difficulty]: Easy * [Tag]: Array */ #include <iostream> #include <vector> #include <algorithm> using namespace std; // [Solution]: Use O(k) space // [Corner Case]: class SolutionCopyToTmp { public: void rotate(vector<int>& nums, int k) { int len = nums.size(); k %= len; vector<int> tmp(nums.begin() + len - k, nums.end()); for (int i = len - 1; i >= k; --i) nums[i] = nums[i - k]; for (int i = 0; i < k; ++i) nums[i] = tmp[i]; } }; // [Solution]: In place, use reverse class Solution { public: void rotate(vector<int>& nums, int k) { int len = nums.size(); k %= len; reverse(nums.begin(), nums.begin() + len - k); reverse(nums.begin() + len - k, nums.end()); reverse(nums.begin(), nums.end()); } }; /* Java solution */ int main() { Solution sol; vector<int> nums = {1,2}; sol.rotate(nums, 3); for (int num:nums) cout << num << " "; cout << endl; return 0; }
true
805704e4888100ff12aba8f184188785bc2ca3ee
C++
mdemirst/Model-Predictive-Control
/src/vehicle.h
UTF-8
653
2.703125
3
[]
no_license
#ifndef VEHICLE_H #define VEHICLE_H #include "Eigen-3.3/Eigen/Core" class Vehicle { public: Vehicle(); Vehicle(const double lf); void Drive(const double dt); void Drive2(const double dt); double& X(); double& Y(); double& Psi(); double& V(); double& Steer(); double& Acc(); double& Cte(); double& Epsi(); const double& X()const ; const double& Y()const ; const double& Psi()const ; const double& V()const ; const double& Steer()const ; const double& Acc()const ; const double& Cte()const ; const double& Epsi()const ; private: Eigen::VectorXd state_m; double Lf_m; //Wheelbase }; #endif // VEHICLE_H
true
f7b65d579b8f80a16f2bb45955a62bac9cab77e3
C++
toha993/my-code
/diehard3.cpp
UTF-8
340
2.78125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main() { int t; cin>>t; while(t--) { int a,b,c,d; cin >> a >> b >> c; if(a<b) swap(a,b); d=gcd(a,b); if(c<=a && c%d==0) cout << "YES" << endl; else cout << "NO" << endl; } }
true
782021fff0f29e9bab92d3ebf159c9014ef41150
C++
vkurbatov/mcu_remake
/liblargo/core/media/video/video_frame_rect.h
UTF-8
2,682
2.625
3
[]
no_license
#ifndef VIDEO_FRAME_RECT_H #define VIDEO_FRAME_RECT_H #include "video_frame_point.h" #include "video_frame_size.h" namespace core { namespace media { namespace video { template<typename T> struct frame_rect_base_t { frame_point_base_t<T> point; frame_size_base_t<T> size; frame_rect_base_t(const frame_point_base_t<T>& point = frame_point_base_t<T>() , const frame_size_base_t<T>& size = frame_size_base_t<T>()); frame_rect_base_t(const frame_point_base_t<T> & point , const frame_point_base_t<T> & br_point); frame_rect_base_t(const frame_size_base_t<T> & size); frame_rect_base_t(T x , T y , T width , T height); bool operator == (const frame_rect_base_t<T>& frame_rect); bool operator != (const frame_rect_base_t<T>& frame_rect); frame_rect_base_t<T>& operator += (const frame_point_base_t<T> & frame_point); frame_rect_base_t<T>& operator -= (const frame_point_base_t<T> & frame_point); frame_rect_base_t<T>& operator += (const frame_size_base_t<T>& frame_size); frame_rect_base_t<T>& operator -= (const frame_size_base_t<T>& frame_size); frame_point_base_t<T> br_point() const; frame_rect_base_t<T>& set_br_point(const frame_point_base_t<T>& frame_point); bool is_join(const frame_size_base_t<T>& size) const; frame_rect_base_t<T>& merge(const frame_rect_base_t<T>& frame_rect); frame_rect_base_t<T>& cut(const frame_rect_base_t<T>& frame_rect); frame_rect_base_t<T>& put(const frame_point_base_t<T>& frame_point); }; typedef frame_rect_base_t<std::int32_t> frame_rect_t; typedef frame_rect_base_t<double> relative_frame_rect_t; /* struct frame_rect_t { frame_point_t point; frame_size_t size; frame_rect_t(const frame_point_t& point = default_frame_point , const frame_size_t& size = default_frame_size); frame_rect_t(const frame_point_t& point , const frame_point_t& br_point); frame_rect_t(std::int32_t x , std::int32_t y , std::int32_t width , std::int32_t height); bool operator == (const frame_rect_t& frame_rect); bool operator != (const frame_rect_t& frame_rect); frame_rect_t& operator += (const frame_point_t& frame_point); frame_rect_t& operator -= (const frame_point_t& frame_point); frame_rect_t& operator += (const frame_size_t& frame_size); frame_rect_t& operator -= (const frame_size_t& frame_size); frame_point_t br_point() const; bool is_join(const frame_size_t& size) const; }; */ } } } #endif // VIDEO_FRAME_RECT_H
true
89ef07edb3eca42d5137f0df94bf18fbffc6847a
C++
yinyanghu/OI
/OJ/usaco/cpp/msquare.cpp
UTF-8
3,146
2.703125
3
[]
no_license
/* ID:oifox20071 LANG:C++ PROG:msquare */ #include <iostream> #include <fstream> #include <cstring> using namespace std; const int n = 8; const int limitsize = 50000; ifstream fin("msquare.in"); ofstream fout("msquare.out"); struct queuenode { int num[n], len, father; char last; } queue[limitsize]; int target[n]; bool flag[n][n][n][n][n][n][n]; inline bool check(int *a) { for (int i = 0; i < n; ++ i) if (a[i] != target[i]) return false; return true; } inline void swap(int &a, int &b) { int k = a; a = b; b = k; } void print(int x) { if (x == 0) return; print(queue[x].father); fout << queue[x].last; } int main() { for (int i = 0; i <= 3; ++ i) { fin >> target[i]; queue[0].num[i] = i; } for (int i = n - 1; i >= 4; -- i) { fin >> target[i]; queue[0].num[i] = 11 - i; } for (int i = 0; i < n; ++ i) -- target[i]; memset(flag, true, sizeof(flag)); queue[0].len = 0; flag[queue[0].num[0]][queue[0].num[1]][queue[0].num[2]][queue[0].num[3]][queue[0].num[4]][queue[0].num[5]][queue[0].num[6]] = false; if (check(queue[0].num)) { fout << 0 << endl; fout << endl; return 0; } int head = -1, tail = 0; while (head != tail) { ++ head; //A queuenode temp = queue[head]; for (int i = 0; i <= 3; ++ i) swap(temp.num[i], temp.num[i + 4]); if (flag[temp.num[0]][temp.num[1]][temp.num[2]][temp.num[3]][temp.num[4]][temp.num[5]][temp.num[6]]) { queue[++ tail] = temp; ++ queue[tail].len; queue[tail].father = head; queue[tail].last = 'A'; if (check(queue[tail].num)) { fout << queue[tail].len << endl; print(tail); break; } flag[temp.num[0]][temp.num[1]][temp.num[2]][temp.num[3]][temp.num[4]][temp.num[5]][temp.num[6]] = false; } //B temp = queue[head]; int x = temp.num[3], y = temp.num[7]; temp.num[3] = temp.num[2]; temp.num[2] = temp.num[1]; temp.num[1] = temp.num[0]; temp.num[0] = x; temp.num[7] = temp.num[6]; temp.num[6] = temp.num[5]; temp.num[5] = temp.num[4]; temp.num[4] = y; if (flag[temp.num[0]][temp.num[1]][temp.num[2]][temp.num[3]][temp.num[4]][temp.num[5]][temp.num[6]]) { queue[++ tail] = temp; ++ queue[tail].len; queue[tail].father = head; queue[tail].last = 'B'; if (check(queue[tail].num)) { fout << queue[tail].len << endl; print(tail); break; } flag[temp.num[0]][temp.num[1]][temp.num[2]][temp.num[3]][temp.num[4]][temp.num[5]][temp.num[6]] = false; } //C temp = queue[head]; x = temp.num[1]; temp.num[1] = temp.num[5]; temp.num[5] = temp.num[6]; temp.num[6] = temp.num[2]; temp.num[2] = x; if (flag[temp.num[0]][temp.num[1]][temp.num[2]][temp.num[3]][temp.num[4]][temp.num[5]][temp.num[6]]) { queue[++ tail] = temp; ++ queue[tail].len; queue[tail].father = head; queue[tail].last = 'C'; if (check(queue[tail].num)) { fout << queue[tail].len << endl; print(tail); break; } flag[temp.num[0]][temp.num[1]][temp.num[2]][temp.num[3]][temp.num[4]][temp.num[5]][temp.num[6]] = false; } } fout << endl; return 0; }
true
ef65a31c3304fd5bb59d1f0c4496246543c6453b
C++
2swap/AbStrat
/walletbox.cpp
UTF-8
850
2.9375
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string> #include <random> using namespace std; const int BOXES = 100; int boxes[BOXES]; void randomize(){ for(int i = 0; i < BOXES; i++) { boxes[i]=-1; } for(int i = 0; i < BOXES; i++) { int r = rand()%BOXES; while(true){ if(boxes[r] == -1) { boxes[r] = i; break; } r++; r%=BOXES; } } } int flood(int i){ if(boxes[i] == -1) return 0; boxes[i] = -1; int len = flood(boxes[i]); return len+1; } int longestChain(){ int big = 0; for(int i = 0; i < BOXES; i++){ big = max(big, flood(i)); } return big; } int main(int argcount, char** args){ randomize(); cout << flood(50) << endl; int wins = 0; for(int i = 0; i < 1000; i++){ randomize(); if(longestChain()<=50) wins++; } cout << wins/1000.0 << endl; }
true
317b414aac20ecdbb91605b5e6492eb3db590ada
C++
jzhang1901/lintcode
/solutions/586. Sqrt(x) II.cpp
UTF-8
883
3.671875
4
[]
no_license
/* Description Implement double sqrt(double x) and x >= 0. Compute and return the square root of x. You do not care about the accuracy of the result, we will help you to output results. Have you met this question in a real interview? Example Given n = 2 return 1.41421356 */ class Solution { public: /* * @param x: a double * @return: the square root of x */ double sqrt(double x) { // write your code here double s = 0.0; double e = x; if(x < 1.0) e = 1.0 / x; while(s + 1e-10 < e) { double mid = (s + e) / 2.0; double midS = mid*mid; if(abs(midS - x) < 1e-10){ return mid; } else if (midS > x) { e = mid; } else { s = mid; } } return (s+e)/2.0; } };
true
949c9c3f54f360f62a63c2985c9144154f9bb95a
C++
isliulin/JFC-Tools
/Atelier Courrier/Jmtfr03/JMTFR03/Source/JMTFR03Logs.cpp
ISO-8859-1
617
2.578125
3
[]
no_license
// // Fichier: JMTFR03Logs.cpp // Auteur: Sylvain SAMMURI // Date: 02/12/2003 // // on inclut les dfinitions ncessaires #include "JMTFR03Logs.h" //////////////////// // les constructeurs JMTFR03Logs::JMTFR03Logs() { // on ne fait rien } JMTFR03Logs::JMTFR03Logs(const JMTFR03Logs & Source) { // on ne fait rien } ///////////////////////////////////////// // l'oprateur pour recopier les lments JMTFR03Logs & JMTFR03Logs::operator =(const JMTFR03Logs & Source) { // on renvoie notre rfrence return (*this); } ///////////////// // le destructeur JMTFR03Logs::~JMTFR03Logs() { // on ne fait rien }
true
e3cf6565a91cc9059c3698007d9198f022a53f2e
C++
wooken/cpp_practice
/split/main.cpp
UTF-8
2,833
3.90625
4
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> // find_if using std::cin; using std::cout; using std::endl; using std::find_if; using std::string; using std::vector; // split_func1() code --------------------------------------------------------- vector<string> split_func1_helper(const string &s) { vector<string> ret; typedef string::size_type string_size; string_size i = 0; // invariant: we have processed characters [original value of i, i) while (i != s.size()) { // ignore leading blanks // invariant: characters in range [original i, current i) are all spaces while (i != s.size() && isspace(s[i])) i++; // find end of next word string_size j = i; // invariant: none of the characters in range [original j, current j) is a space while (j != s.size() && !isspace(s[j])) j++; // if we found some non-whitespace characters if (i != j){ // copy from s starting at i and taking j - i chars ret.push_back(s.substr(i, j - i)); i = j; } } return ret; } void split_func1() { string s; // read and split each line of input while (getline(cin, s)) { vector<string> v = split_func1_helper(s); // write each word in v for (vector<string>::size_type i = 0; i != v.size(); i++) { cout << v[i] << endl; } } } // end split_func1() code ----------------------------------------------------- // split_func3() code --------------------------------------------------------- bool space(char c) { return isspace(c); } bool not_space(char c) { return !isspace(c); } // uses iterators and find_if() from <algorithm> vector<string> split_func3_helper(const string &str) { typedef string::const_iterator iter; vector<string> ret; iter i = str.begin(); while (i != str.end()) { // ignore leading blanks i = find_if(i, str.end(), not_space); // find end of next word iter j = find_if(i, str.end(), space); // copy the characters in [i, j) if (i != str.end()) ret.push_back(string(i, j)); i = j; } return ret; } void split_func3() { string s; // read and split each line of input while (getline(cin, s)) { vector<string> v = split_func3_helper(s); // write each word in v for (vector<string>::size_type i = 0; i != v.size(); i++) { cout << v[i] << endl; } } } // end split_func3() code ----------------------------------------------------- void split_func2() { string s; while (cin >> s) { cout << s << endl; } } int main() { //split_func1(); //split_func2(); split_func3(); return 0; }
true
d01be2200095018e2e4ee4f7e2d9120b8c396542
C++
sh999/Cplusplus-Study-Snippets
/PointersToPointers/PointersToPointers/main.cpp
UTF-8
471
3.421875
3
[]
no_license
/* Create pointers to pointers (and beyond) */ #include <iostream> using namespace std; int main(){ int a = 20; int &b = a; int *p = &a; int **p2 = &p; int ***p3 = &p2; cout << "a = " << a; cout << "\nb = " << b; cout << "\np = " << p; cout << "\nvalue pointed by p = " << *p; cout << "\np2 = " << p2; cout << "\nvalue pointed by p2 = " << *p2; cout << "\np3 = " << p3; cout << "\nvalue pointed by p3 = " << *p3; }
true
0769f748aa6b224830bc79f5f626e98384ca38f8
C++
walkccc/LeetCode
/solutions/0008. String to Integer (atoi)/0008.cpp
UTF-8
596
3.125
3
[ "MIT" ]
permissive
class Solution { public: int myAtoi(string s) { trim(s); if (s.empty()) return 0; const int sign = s[0] == '-' ? -1 : 1; if (s[0] == '+' || s[0] == '-') s = s.substr(1); long num = 0; for (const char c : s) { if (!isdigit(c)) break; num = num * 10 + (c - '0'); if (sign * num < INT_MIN) return INT_MIN; if (sign * num > INT_MAX) return INT_MAX; } return sign * num; } private: void trim(string& s) { s.erase(0, s.find_first_not_of(' ')); s.erase(s.find_last_not_of(' ') + 1); } };
true
1ca3ee5a05dcae11177fd2a0d4fb7184232cf0bd
C++
doraneko94/AtCoder
/ABS/049C.cpp
UTF-8
744
3.109375
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; string divide[4] = {"dream", "dreamer", "erase", "eraser"}; int main() { string S; cin >> S; reverse(S.begin(), S.end()); for (int i=0; i<4; ++i) reverse(divide[i].begin(), divide[i].end()); bool can = true; int len = S.size(); for (int i=0; i<len;) { bool can2 = false; for (int j=0; j<4; ++j) { if (S.substr(i, divide[j].size()) == divide[j]) { can2 = true; i += divide[j].size(); } } if (!can2) { can = false; break; } } if (can) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
true
bb6610f65a79204c5fe3b1431da7ba2b98b557d0
C++
JudsonSS/Compiladores
/Labs/Lab08/symtable.h
UTF-8
398
3.015625
3
[ "MIT" ]
permissive
#include <unordered_map> #include <string> using std::unordered_map; using std::string; // modelo para símbolos struct Symbol { string var; string type; }; // tabela de símbolos class SymTable { private: unordered_map<string,Symbol> table; SymTable * prev; public: SymTable(); SymTable(SymTable * t); bool Insert(string s, Symbol symb); Symbol * Find(string s); };
true
2edc18695269a404221b705a0e7c657fc5d7391b
C++
dtbinh/M1S2
/Prog3D/TP1/Point.cpp
UTF-8
1,496
3.484375
3
[]
no_license
#include "Point.h" Point::Point(void){ x = 0; y = 0; z = 0; } Point::Point(long double x1, long double y1, long double z1){ x = x1; y = y1; z = z1; } Point::Point(const Point& p){ x = p.x; y = p.y; z = p.z; } Point::~Point(void){ } long double Point::getX(void) const{ return x; } long double Point::getY(void) const{ return y; } long double Point::getZ(void) const{ return z; } void Point::setX(long double x1){ x = x1; } void Point::setY(long double y1){ y = y1; } void Point::setZ(long double z1){ z = z1; } Point Point::projectOnLine(Point point1Line, Point point2Line){ Vector v( (point2Line.getX()-point1Line.getX()), point2Line.getY()-point1Line.getY(), point2Line.getZ()-point1Line.getZ()); return this->projectOnLine(v,point1Line); } Point Point::projectOnLine(Vector vecteur, Point pLine){ long double norme = vecteur.norme(); long double scalaire; long double taille; Vector v( (this->getX()-pLine.getX()), this->getY()-pLine.getY(), this->getZ()-pLine.getZ()); scalaire = v.scalar(vecteur); taille = scalaire / norme; vecteur.normalize(); return Point(pLine.getX()+vecteur.getX()*taille,pLine.getY()+vecteur.getY()*taille,pLine.getZ()+vecteur.getZ()*taille); } void Point::affiche(){ cout << "(" << this->getX() << "," << this->getY() << "," << this->getZ() << ")" << endl; } bool Point::compare(Point p){ return ( ( this->getX() == p.getX() ) && ( this->getY() == p.getY() ) && ( this->getZ() == p.getZ() ) ); }
true
c891363db04116e10309e0cd382cd73202f36a71
C++
tudinfse/intel_mpx_explained
/src/parsec/raytrace/src/RTTL/common/MapOptions.cxx
UTF-8
20,022
2.921875
3
[ "GPL-3.0-only", "GPL-2.0-only", "MIT" ]
permissive
#include <cstring> #include "RTTL/common/MapOptions.hxx" namespace RTTL { /// Instantiates MapOptions entry which is visible in any file which includes MapOptions.hxx. /// \note The preferred way to parse command line parameters is to add them to options as /// <b>options.parse(argc-1, argv+1);</b> /// In this case, this variable must be defined (for example, by including this file in the project). MapOptions options; /// Remove blank chars from the end of token. static _INLINE char* trimEnd(char* token) { char* pe = token + strlen(token) - 1; while ((*pe == ' ' || *pe == '\t' || *pe == 10 || *pe == 13) && pe >= token) *pe-- = 0; return token; } /// Return size of directory name of filename fn. static _INLINE int pathLength(const string& fn) { #ifdef _WIN32 const char* del = "\\/:"; #else const char* del = "/"; #endif return string(fn).find_last_of(del) + 1; } /// Dtor. MapOptions::~MapOptions() { // First, report unused entries. bool start = true; for (iterator it = begin(); it != end(); it++) { vector_of_strings* entry = it->second; map<void*, bool>::iterator itused = m_used_entries.find(it->second); if (itused->second == false) { if (start) { start = false; puts("\n"); } //printf("MapOptions: unused parameter: -%s\n", it->first.c_str()); } } // Second, clear m_used_entries m_used_entries.clear(); // Third, free everything. clear(); } void MapOptions::remove_all_entries() { /// iterate, clear and delete all entries. for (iterator it = begin(); it != end(); it++) { vector_of_strings* entry = it->second; entry->clear(); delete entry; } } /// Clean everything (it is not required if dtor is called implicitly). void MapOptions::clear() { remove_all_entries(); map_strings_to_vector_of_strings::clear(); } // /// Add converted value to the named parameter. // template<typename DataType> // void add(const string& name, const DataType value) { // add_string(name, Convert::to_string(value)); // } /// Add value string to the named parameter. void MapOptions::add_string(const string& name, const string& value) { (*this)[name]->push_back(value); } /// Return 1st entry (with index 0) of the named parameter as a string /// or return name as a string if it does not exist (even in the environment). string MapOptions::get(string name) const { return get(name, name, 0); } /// Return the named vector using defvalue for missing components. // template<int N, typename DataType> // RTVec_t<N, DataType> getVector(string name, DataType defvalue = 0) const { // RTVec_t<N, DataType> v; // getArray<N, DataType>(name, v, defvalue); // return v; // } /// Specialization <3, float>. RTVec3f MapOptions::getVec3f(string name, float defvalue) const { return RTVec3f(getVector<3, float>(name, defvalue)); } /// Specialization <3, int>. RTVec3f MapOptions::getVec3i(string name, int defvalue) const { return RTVec3f(getVector<3, int>(name, defvalue)); } /// Specialization <2, float>. RTVec2f MapOptions::getVec2f(string name, float defvalue) const { return RTVec2f(getVector<2, float>(name, defvalue)); } /// Specialization <2, int>. /// X windows-like settings of n1Xn2 are allowed. RTVec2i MapOptions::getVec2i(string name, int defvalue) const { if (defined(name)) { string rs = get(name); const char* rc = rs.c_str(); int lx = strcspn(rc, "xX"); if (rc[lx]) { return RTVec2i(atoi(rc), atoi(rc + lx + 1)); } else { return getVector<2, int>(name, defvalue); } } return RTVec2i(defvalue); } /// Write the named vector to vtgt (no more than N entries) or use defvalue /// if it is smaller than N. // template<int N, typename DataType> // void getArray(string name, DataType* vtgt, DataType defvalue = 0) const { // int n = vector_size(name); // int verboselevel = verbose(); // if (n == 0 && verboselevel >= 1) { // std::cout << "MapOptions: parameter " << name << " is undefined; using default value of " << defvalue << std::endl; // } // int i = 0; // if (n) { // if (verboselevel >= 2) { // std::cout << "MapOptions: using " << name << " = [ "; // } // const vector_of_strings& vs = *(*this)[name]; // for (vector_of_strings::const_iterator it = vs.begin(); it != vs.end(); it++) { // vtgt[i++] = Convert::to<DataType>(*it); // if (verboselevel >= 2) { // std::cout << vtgt[i-1] << " "; // } // } // if (verboselevel >= 2) { // std::cout << "]" << std::endl; // } // } // for (; i < N; i++) { // vtgt[i] = defvalue; // } // } /// Indicate what MapOptions should report during calls to get() functions. /// It is based on (user supplied) integer value of 'verbose' keyword and /// is choosen as follows: /// <ul> /// <li> 0 - do nothing except reporting unused parameters at the exit (default value) /// <li> 1 - report undefined parameters (ones for which default values were used) /// <li> 2 - report all requested parameters. /// </ul> int MapOptions::verbose() const { const_iterator it = find("verbose"); if (it == end()) return 0; const vector_of_strings& entry = *it->second; return Convert::to<int>(entry[0]); } /// return index entry in the named parameter if it exists or /// defvalue otherwise. // template<typename DataType> // DataType get(const string& name, DataType defvalue, unsigned int index = 0) const { // const_iterator it = find(name); // int verboselevel = verbose(); // if (it == end()) { // // See if it is defined in the environment... // const char* parenv = getenv(name.c_str()); // if (parenv) { // return Convert::to<DataType>(parenv); // } // // Nope, return caller-supplied default value. // if (verboselevel >= 1) { // std::cout << "MapOptions: parameter " << name << "[" << index << "]" // << " is undefined; using default value of " << defvalue << std::endl; // } // return defvalue; // } else { // const vector_of_strings& entry = *it->second; // if (index >= entry.size()) return defvalue; // if (entry[index].size() == 0) return defvalue; // DataType value = Convert::to<DataType>(entry[index]); // if (verboselevel >= 2) { // std::cout << "MapOptions: using " << name << "[" << index << "] = " << value << std::endl; // } // return value; // } // } /// Return # of components in the named vector or 0. unsigned int MapOptions::vector_size(const string& name) const { const_iterator it = find(name); if (it == end()) { return 0; } else { vector_of_strings& entry = *it->second; return entry.size(); } } /// Return true iff the parameter defined by len characters of name exists either in this or in the environment. bool MapOptions::defined(const char* name, int len) const { return defined(string(name, len)); } /// Return true iff the named parameter exists either in this or in the environment. bool MapOptions::defined(const string& name) const { return find(name) != end(); } /// Remove the named parameter. void MapOptions::remove(const string& name) { // Remove named entry. iterator it = find(name); if (it != end()) erase(it); } /// Parse named tokens defined by argv (see the detailed class description). /// If keep_all_filenames is false (default value), non-existing files will be deleted from 'files' group. bool MapOptions::parse(int argc, char* argv[], bool keep_all_filenames) { // Just to allow using main() parameters directly without // any stupid warnings. return parse(argc, (const char**)argv, keep_all_filenames); } /// Parse named tokens defined by a. bool MapOptions::parse(const char* a) { const char* argv[] = {a}; return parse(1, argv); } /// Return true iff all characters of s before separator (" \t,;])" or 0) represents a number /// (using integer, float or exponential notation). bool MapOptions::isNumber(const char* s) { // I'll be damned -- parsing a number is not so easy. int nss = 0, ndd = 0, nee = 0; int n = 0; do { int ns = s[n] == '-' || s[n] == '+'; // Signs are either first chars or after exponent. if (ns && n && s[n-1] != 'e' && s[n-1] != 'E') return false; // Need a digit after the sign. if (ns && !(s[n+1] >= '0' && s[n+1] <= '9')) return false; nss += ns; int nd = s[n] == '.'; // Need either digit or EOS or exponent after the dot. if (nd && !(s[n+1] == 0 || s[n+1] == 'e' || s[n+1] == 'E' || (s[n+1] >= '0' && s[n+1] <= '9'))) return false; // No dots after exponent. if (nd && nee) return false; ndd += nd; // No more than 2 signs and one dot. if (nss > 2 || ndd > 1) return false; int ne = s[n] == 'e' || s[n] == 'E'; nee += ne; // Only one exponent; could not be the first char. if (nee > 2 || (ne && !n)) return false; if (ne) { n++; if (s[n] == 0 || strchr(" \t,;])", s[n])) return false; continue; } if (!((s[n] >= '0' && s[n] <= '9') || ns || nd)) return false; n++; } while (s[n] && !strchr(" \t,;])", s[n])); return true; } /// Parse named tokens defined by argv (see the detailed class description). /// If keep_all_filenames is false (default value), non-existing files will be deleted from 'files' group. bool MapOptions::parse(int argc, const char* argv[], bool keep_all_filenames) { const char* name = 0; const char* ptr; int added = 1; int namelen; for (int count = 0; count < argc; count++) { const char* arg = argv[count]; if (isNumber(arg)) { if (!name) { printf("Unnamed number: %s\n", arg); return false; // report failure } goto parse_parameters; } if (arg[0] == '-' || arg[0] == '+') { // It is named parameter. if (name && !added) { // If the previous parameter does not have any value, just add it with the default value of "". add(name, ""); } bool accumulate = arg[0] == '+'; // Get name of the current parameter. name = arg + 1; while (*name == '-') name++; // take care of --parname added = 0; namelen = strcspn(name, "="); if (!accumulate) { // Delete all previous name entries to allow overloading parameters with latter values. remove(string(name, namelen)); } if (namelen == strlen(name)) continue; // fused name=value arg = name + namelen + 1; arg += strspn(arg, " \t"); goto parse_parameters; } else if (added && (ptr = strrchr(arg, '.'))) { // This is not a parameter or number or parameter's name; assume that // it is a file and check if file exists. // This block is executed only if previous parameter was finalized // (i.e. have non-trivial value). #ifdef _WIN32 // Replace Linux delimiters. char* parg = (char*)arg; while (parg = strchr(parg, '/')) *parg = '\\'; #endif if (keep_all_filenames == false && access(arg, 0) == -1) { printf("File %s does not exist.\n", arg); return false; // file do not exist; report failure } // It is a filename. Check if it contains parameters (*.ini). if (strcasecmp(ptr + 1, "ini") == 0) { if (parse_file(arg) == false) return false; } else { // It is a model file; include it into "files". add("files", arg); } name = 0; // need a new name } else if (name) { parse_parameters: // Add named parameter. Vectors are allowed, like // -camera.pos 1.0 2.0 3.0 char term[80]; // Remove prefixed separators if they exist (commas, =, or brackets). bool remove_separator = *arg == '=' || *arg == '(' || *arg == '[' || *arg == ',' || *arg == ';'; strncpy(term, arg + (remove_separator ? 1 : 0), sizeof(term)); int remain = strlen(term); char* pterm = term; // Take apart fused expressions like 1,2,3 and convert them to a vector. unfuse: int term_end = strcspn(pterm, ",;])"); pterm[term_end] = 0; if (*pterm == 0) continue; ++added; add(string(name, namelen), pterm); pterm += term_end + 1; remain -= term_end + 1; if (remain > 0) goto unfuse; } else { return false; // wrong (unnamed) parameter; report failure } } if (name && !added) { // If the last parameter does not have any value, just add it with the default value of "". add(name, ""); } return true; } /// Parse all named tokens in file filename (see the detailed class description). bool MapOptions::parse_file(const char* filename) { FILE* fs = fopen(filename, "rt"); if (fs == 0) { printf("File %s does not exist.\n", filename); return false; } char buf[300]; char prefix[80]; prefix[0] = 0; // ============================================================================== // Parse lines like // pname = pvalue // or // pname = [v1, v2, v3] or similar. // ============================================================================== while (fgets(buf, sizeof(buf), fs)) { trimEnd(buf); char* pname = buf + strspn(buf, " \t\n"); // skip blank chars if (*pname == 0 || (pname[0] == '/' && pname[1] == '/')) continue; // commented or empty line // Skip comments. if (*pname == '#') continue; if (!strncmp(pname, "exit", 4)) break; if (*pname == '[') { // [section] will be prepended to all following parameters. strncpy(prefix, pname + 1, sizeof(prefix)); int prefixend = strcspn(prefix, "] \t"); prefix[prefixend] = 0; continue; } if (pname[0] == '-' || pname[0] == '+') { // command-line style trimEnd(pname); split_multiple_tokens_into_groups: int nameend = strcspn(pname, " \t"); int namelen = strlen(pname); if (nameend < namelen) pname[nameend] = '='; char* nextpname = pname; next_token: unsigned int postoken = strcspn(++nextpname, "-+"); if (postoken < strlen(nextpname)) { nextpname += postoken; if (nextpname[-1] == ' ' || nextpname[-1] == '\t') { if (nextpname[1] >= '0' && nextpname[1] <= '9') { // It is a number, continue looking for next token. goto next_token; } else { // It is bona fide parameter name (or so I think), split the line before it. nextpname[-1] = 0; } } else { goto next_token; } } else { nextpname = NULL; } parse(pname); if (!nextpname) continue; pname = nextpname; goto split_multiple_tokens_into_groups; } else if (strrchr(pname, '.') && !strrchr(pname, '=')) { // filename (not a float number) if (access(pname, 0) == -1) { // File do not exist -- try to append the directory of the current ini file. const string fnini(filename); const string fullfn = fnini.substr(0, pathLength(fnini)) + string(pname); const char* pname = fullfn.c_str(); if (access(pname, 0) != -1) { // load/parse the existing file parse(pname); } else { // Better kill it now than be sorry latter... FATAL(string("Cannot open file ") + string(pname)); } } else { // load/parse the existing file parse(pname); } continue; } // The line in the form of // name = value bool accumulate = *pname == '+'; if (accumulate) pname++; int name_end = strcspn(pname, "= \t"); pname[name_end] = 0; char* pvalue = pname + name_end + 1; bool first_token = true; string token_name = *prefix ? string(prefix) + string(".") + string(pname) : string(pname); if (!accumulate) { // Delete all previous name entries to allow overloading parameters with latter values. remove(token_name); } // Loop over multiple values (in vector). next_value: pvalue += strspn(pvalue, "=,;[( \t\n"); if (*pvalue == 0) continue; int value_end; if (*pvalue == '\"') { // "value inside" value_end = strcspn(++pvalue, "\"\n"); } else { // look for separators value_end = strcspn(pvalue, ",;]) \t\n"); } pvalue[value_end] = 0; if (first_token) { if (strcasecmp(pname, "include") == 0 || strcasecmp(pname, "#include") == 0) { // Parse nested file. if (!parse_file(pvalue)) { return false; } continue; } if (*pname == '#') continue; // skip comments other than #include first_token = false; } add(token_name, pvalue); // Look for the next value (for vectors) if it exists. pvalue += value_end + 1; goto next_value; } fclose(fs); return true; } /// const version. const vector_of_strings* MapOptions::operator[](const string& name) const { const_iterator it = find(name); if (it == end()) return 0; return it->second; } /// Return either pointer to the vector_of_strings defined by the name or pointer to the newly created empty vector. vector_of_strings* MapOptions::operator[](const string& name) { vector_of_strings* entry; iterator it = find(name); if (it == end()) { entry = new vector_of_strings; insert(value_type(name, entry)); m_used_entries.insert(map<void*, bool>::value_type(entry, false)); } else { entry = it->second; } return entry; } /// Overload find operation to allow component names (like "nt; nthread; nthreads"). /// This function will also check m_used_entries. /// \note Order of items in component name is important (first one is checked first, etc). MapOptions::iterator MapOptions::find(const string& name) { iterator it; const char* ns = name.c_str(); const char* del = ",; \t|"; if (strcspn(ns, del) == strlen(ns)) { it = map_strings_to_vector_of_strings::find(name); } else { // Name includes multiple terms: check for each one individually. const char* pname = ns; do { int sep = strcspn(pname, del); it = find(pname, sep); if (it != end()) break; pname += sep; pname += strspn(pname, del); } while (*pname && *pname != '\n'); } if (it != end()) { map<void*, bool>::iterator itused = m_used_entries.find(it->second); assert(itused != m_used_entries.end()); itused->second = true; } return it; } MapOptions::const_iterator MapOptions::find(const string& name) const { // Find through double cast to un-const member. return (const_iterator)((MapOptions*)this)->find(name); } MapOptions::iterator MapOptions::find(const char* name, int len) { return find(string(name, len)); } MapOptions::const_iterator MapOptions::find(const char* name, int len) const { return (const_iterator)find(string(name, len)); } };
true
96a8b3fa7a5cfb124301c819c46299e7ec50031c
C++
tomjn/ntai
/AI/NTai/Helpers/CWorkerThread.h
UTF-8
7,669
2.71875
3
[]
no_license
#ifndef CWORKERTHREAD_H_INCLUDED #define CWORKERTHREAD_H_INCLUDED /*class CWorkerThread{// : public IModule{ public: CWorkerThread();//{workerthreads = 0;} ~CWorkerThread(); void NextThread(); bool HasNext(); void operator()(); //void RecieveMessage(CMessage &message){} //bool Init(boost::shared_ptr<IModule> me){ return true;} //static int workerthreads; };*/ //#include <list> //#include <boost/thread/thread.hpp> //#include <boost/thread/condition.hpp> //class ThreadPool //{ //public: // // typedef boost::function0<void> Functor_T; // // ThreadPool() // { // init(); // m_nMaxThreads = m_nQueueSize = 0; // } // // explicit // ThreadPool(size_t nThreads, size_t nQueueSize = 0) // : m_nMaxThreads(nThreads), // m_nQueueSize(nQueueSize) // { // init(); // // //dgassert3(nQueueSize == 0 || nQueueSize >= nThreads, ThreadException, "Queue size must be zero or greater than number of threads") // //dgassert3(nThreads > 0, ThreadException, "Thread pool created with zero threads") // // if (m_nQueueSize == 0) // m_nQueueSize = m_nMaxThreads*2; // } // // void setQueueSize(size_t x) // { // boost::mutex::scoped_lock lock1(m_mutex); // m_nQueueSize = x; // } // // size_t getQueueSize() const // { // return m_nQueueSize; // } // // void setMaxThreads(size_t x) // { // boost::mutex::scoped_lock lock1(m_mutex); // m_nMaxThreads = x; // } // // size_t getMaxThreads() const // { // return m_nMaxThreads; // } // // // Register a function to be called when a new thread is created // void setThreadCreatedListener(const Functor_T &f) // { // m_threadCreated = f; // } // // // Call a function in a separate thread managed by the pool // void invoke(const Functor_T& threadfunc) // { // boost::mutex::scoped_lock lock1(m_mutex); // // //dgassert3(m_nMaxThreads, ThreadException, "Please set the maxThreads property") // //dgassert3(m_nQueueSize >= m_nThreads, ThreadException, "The queue size must be greater or equal to the number of threads") // // for(;;) // { // //dgassert3(!m_bStop, dg::thread::ThreadException, "The thread pool has been stopped and can not longer service requests") // //dgassert3(!m_nGeneralErrors, dg::thread::ThreadException, "An error has occurred in the thread pool and can no longer service requests") // // try // { // if ( m_waitingFunctors.size() < m_nThreads) // { // // Don't create a thread unless it's needed. There // // is a thread available to service this request. // addFunctor(threadfunc); // lock1.unlock(); // break; // } // // bool bAdded = false; // // if (m_waitingFunctors.size() < m_nQueueSize) // { // // Don't create a thread unless you have to // addFunctor(threadfunc); // bAdded = true; // } // // if (m_nThreads < m_nMaxThreads) // { // ++m_nThreads; // // lock1.unlock(); // m_threads.create_thread(beginThreadFunc(*this)); // // if (bAdded) // break; // // // Terris -- if the mutex is unlocked before creating the thread // // this allows m_threadAvailable to be triggered // // before the wait below runs. So run the loop again. // lock1.lock(); // continue; // } // // if (bAdded) // { // lock1.unlock(); // break; // } // // m_threadAvailable.wait(lock1); // } // catch(...) // { // // no idea what the state of lock1 is.. don't need thread safety here // ++m_nGeneralErrors; // throw; // } // } // // m_needThread.notify_all(); // } // // ~ThreadPool() throw() // { // //try // //{ // stop(); // //} // //DG_CATCH_BASIC_LOG_STDERR // } // // // This method is not thread-safe // void stop() // { // // m_bStop must be set to true in a critical section. Otherwise // // it is possible for a thread to miss notify_all and never // // terminate. // boost::mutex::scoped_lock lock1(m_mutex); // m_bStop = true; // lock1.unlock(); // // m_needThread.notify_all(); // m_threads.join_all(); // } // // // This method is not thread-safe // void wait() // { // boost::mutex::scoped_lock lock1(m_mutex); // // while (!m_waitingFunctors.empty()) // { // m_threadAvailable.wait(lock1); // } // } // //private: // // ThreadPool(const ThreadPool&); // ThreadPool& operator = (const ThreadPool&); // // size_t m_nThreads, // m_nMaxThreads, // m_nQueueSize; // // typedef std::list<Functor_T> Container_T; // Container_T m_waitingFunctors; // Container_T::iterator m_nextFunctor; // Functor_T m_threadCreated; // // boost::mutex m_mutex; // boost::condition m_threadAvailable, // triggered when a thread is available // m_needThread; // triggered when a thread is needed // boost::thread_group m_threads; // bool m_bStop; // long m_nGeneralErrors, // m_nFunctorErrors; // // void init() // { // m_nThreads = 0; // m_nGeneralErrors = 0; // m_nFunctorErrors = 0; // m_bStop = false; // m_threadCreated = NoOp(); // m_nextFunctor = m_waitingFunctors.end(); // } // // friend struct beginThreadFunc; // // void addFunctor(const Functor_T& func) // { // bool bAtEnd = false; // // if (m_nextFunctor == m_waitingFunctors.end()) // bAtEnd = true; // // m_waitingFunctors.push_back(func); // if (bAtEnd) // { // --m_nextFunctor; // } // } // // struct NoOp // { // void operator () () const // { // } // }; // // struct beginThreadFunc // { // beginThreadFunc(ThreadPool& impl) // : m_impl(impl) // { // } // // void operator() () // { // m_impl.beginThread(); // } // // ThreadPool &m_impl; // }; // // // Thread entry point. This method runs once per thread. // void beginThread() throw() // { // try // { // m_threadCreated(); // // boost::mutex::scoped_lock lock1(m_mutex); // // for(;;) // { // if (m_bStop) // break; // // if (m_nextFunctor == m_waitingFunctors.end()) // { // // Wait until someone needs a thread // m_needThread.wait(lock1); // } // else // { // // ++m_nThreadsInProcess; // Container_T::iterator iter = m_nextFunctor; // Functor_T &func = (*iter); // m_waitingFunctors.front(); // ++m_nextFunctor; // // lock1.unlock(); // // try // { // (func)(); // } // catch(...) // { // lock1.lock(); // ++m_nFunctorErrors; // //--m_nThreadsInProcess; // m_waitingFunctors.erase(iter); // throw; // } // // lock1.lock(); // m_waitingFunctors.erase(iter); // // --m_nThreadsInProcess; // lock1.unlock(); // // m_threadAvailable.notify_all(); // // lock1.lock(); // } // } // } // catch(...) // { // // This is a real problem. Since this thread is about to die, m_nThreads // // will be out of sync with the actual number of threads. But this should // // not occur except when something really bad happens. // // not thread safe.. who cares // ++m_nGeneralErrors; // // // Log the exception and exit this thread // //try // //{ // // throw; // //} // //DG_CATCH_BASIC_LOG_STDERR // } // } //}; // #endif // CWORKERTHREAD_H_INCLUDED
true
faaef8824d633ec9a563f02f3c4a38457ea6a077
C++
AkasLiu/KoaliEngine
/KoaliEngine/src/KoaliMaterial.cpp
UTF-8
4,034
2.78125
3
[]
no_license
#include "../include/KoaliMaterial.h" KoaliMaterial::~KoaliMaterial(void) { } KoaliMaterial::KoaliMaterial() { // Set a default material (white) ZeroMemory(&m_Material, sizeof(D3DMATERIAL9)); SetDiffuseColor(255, 255, 0); SetAmbientColor(255, 255, 0); //SetSpecularColor(255,255,255); //SetEmissiveColor(0,0,0); //SetPower(10.0f); //ZeroMemory( &m_Material, sizeof(D3DMATERIAL9) ); //m_Material.Diffuse.r = m_Material.Ambient.r = 1.0f; //m_Material.Diffuse.g = m_Material.Ambient.g = 1.0f; //m_Material.Diffuse.b = m_Material.Ambient.b =0.0f; //m_Material.Diffuse.a = m_Material.Ambient.a = 1.0f; } KoaliMaterial::KoaliMaterial(D3DXCOLOR a, D3DXCOLOR d, D3DXCOLOR s, D3DXCOLOR e, float p) { ZeroMemory(&m_Material, sizeof(D3DMATERIAL9)); SetDiffuseColor(d); SetAmbientColor(a); SetSpecularColor(s); SetEmissiveColor(e); SetPower(p); } BOOL KoaliMaterial::SetDiffuseColor(float Red, float Green, float Blue) { m_Material.Diffuse.r = 1.0f / 255.0f * (float)Red; m_Material.Diffuse.g = 1.0f / 255.0f * (float)Green; m_Material.Diffuse.b = 1.0f / 255.0f * (float)Blue; return TRUE; } BOOL KoaliMaterial::GetDiffuseColor(float *Red, float *Green, float *Blue) { if (Red != NULL) *Red = (float)(255.0f * m_Material.Diffuse.r); if (Green != NULL) *Green = (float)(255.0f * m_Material.Diffuse.g); if (Blue != NULL) *Blue = (float)(255.0f * m_Material.Diffuse.b); return TRUE; } BOOL KoaliMaterial::SetAmbientColor(float Red, float Green, float Blue) { float hg = (float)Red; m_Material.Ambient.r = 1.0f / 255.0f * (float)Red; m_Material.Ambient.g = 1.0f / 255.0f * (float)Green; m_Material.Ambient.b = 1.0f / 255.0f * (float)Blue; return TRUE; } BOOL KoaliMaterial::GetAmbientColor(float *Red, float *Green, float *Blue) { if (Red != NULL) *Red = (float)(255.0f * m_Material.Ambient.r); if (Green != NULL) *Green = (float)(255.0f * m_Material.Ambient.g); if (Blue != NULL) *Blue = (float)(255.0f * m_Material.Ambient.b); return TRUE; } BOOL KoaliMaterial::SetSpecularColor(float Red, float Green, float Blue) { m_Material.Specular.r = 1.0f / 255.0f * (float)Red; m_Material.Specular.g = 1.0f / 255.0f * (float)Green; m_Material.Specular.b = 1.0f / 255.0f * (float)Blue; return TRUE; } BOOL KoaliMaterial::GetSpecularColor(float *Red, float *Green, float *Blue) { if (Red != NULL) *Red = (float)(255.0f * m_Material.Specular.r); if (Green != NULL) *Green = (float)(255.0f * m_Material.Specular.g); if (Blue != NULL) *Blue = (float)(255.0f * m_Material.Specular.b); return TRUE; } BOOL KoaliMaterial::SetEmissiveColor(float Red, float Green, float Blue) { m_Material.Emissive.r = 1.0f / 255.0f * (float)Red; m_Material.Emissive.g = 1.0f / 255.0f * (float)Green; m_Material.Emissive.b = 1.0f / 255.0f * (float)Blue; return TRUE; } BOOL KoaliMaterial::GetEmissiveColor(float *Red, float *Green, float *Blue) { if (Red != NULL) *Red = (float)(255.0f * m_Material.Emissive.r); if (Green != NULL) *Green = (float)(255.0f * m_Material.Emissive.g); if (Blue != NULL) *Blue = (float)(255.0f * m_Material.Emissive.b); return TRUE; } BOOL KoaliMaterial::SetDiffuseColor(D3DXCOLOR d) { m_Material.Diffuse = d; return true; } BOOL KoaliMaterial::GetDiffuseColor(D3DXCOLOR *d) { *d = m_Material.Diffuse; return true; } BOOL KoaliMaterial::SetAmbientColor(D3DXCOLOR a) { m_Material.Ambient = a; return true; } BOOL KoaliMaterial::GetAmbientColor(D3DXCOLOR * a) { return 0; } BOOL KoaliMaterial::SetSpecularColor(D3DXCOLOR s) { m_Material.Specular = s; return true; } BOOL KoaliMaterial::GetSpecularColor(D3DXCOLOR * s) { return 0; } BOOL KoaliMaterial::SetEmissiveColor(D3DXCOLOR e) { m_Material.Emissive = e; return true; } BOOL KoaliMaterial::GetEmissiveColor(D3DXCOLOR * e) { return 0; } BOOL KoaliMaterial::SetPower(float Power) { m_Material.Power = Power; return TRUE; } float KoaliMaterial::GetPower(float Power) { return m_Material.Power; } D3DMATERIAL9 *KoaliMaterial::GetMaterial() { return &m_Material; }
true
a6a2ad56c587f7d1a6acdbf327fd9b973c3339be
C++
heavenlybilly/olympiad
/P/acmp/Решение олимпиадных задач/2. Целочисленная арифметика/Числа Смита.cpp
UTF-8
1,265
3.34375
3
[]
no_license
/* * ------------ ЧИСЛА ФИБОНАЧЧИ - 3 ------------ & целые числа ~ факторизация ~ простые_числа ? ничего сложного, просто нужно прочитать внимательно условие и обратить внимание на то, что числом Смита может быть только ? простое число. */ #include <iostream> #include <vector> #include <string> #include <math.h> using namespace std; using line = vector <int>; int digitSum(int p) { int s(0); while (p) { s += p % 10; p /= 10; } return s; } // факторизация с проверкой на простоту int factorizationSum(int p) { double e = sqrt(p + .0) + 1; int i(2); int sum(0); bool isSimple = true; while (i < e) { if (p % i == 0) { sum += digitSum(i); isSimple = false; p /= i; continue; } i++; } if (p > 1 && !isSimple) { sum += digitSum(p); } return sum; } int main() { // ... int p; while (cin >> p) { int f = factorizationSum(p); int d = digitSum(p); cout << (f == d ? 1 : 0); } return 0; }
true
83389ab23f569d8a1f37abd12061a82ee7ef780c
C++
NiveditaRashmi/Programming_Basics
/C++ Basics/Four - Constant&Literals.cpp
UTF-8
530
3.484375
3
[ "MIT" ]
permissive
/* CONSTANTS - Value remains the same throughout the program LITERALS - Value assigned to each constant variable. Constants can be defined in two ways: a) using #define preprocessor directive b) using const keyword. */ #include<iostream> using namespace std; #define val 10 #define charVal 'G' #define floatVal 3.4 int main() { cout << val << " " << charVal << " " << floatVal << endl; // const int var; // var = 5; //this line will give error. const int var = 6; cout << "var = "<< var << endl; return 0; }
true
e969993484c892fac70c1c0049b575bab80da777
C++
zschaefle/CS325_final_project
/EPFleury.cpp
UTF-8
3,849
3.421875
3
[]
no_license
#include "EPFleury.hpp" EPFleury::EPFleury() { count = 0; adjacent = new std::list<int>[0]; path = new std::vector<int>; } EPFleury::EPFleury(int count){ this->count = count; adjacent = new std::list<int>[count]; path = new std::vector<int>; } EPFleury::~EPFleury() { delete[] this->adjacent; delete this->path; } // NOTE: a lot of this code was retrieved/inspired by code at // https://www.geeksforgeeks.org/fleurys-algorithm-for-printing-eulerian-path/ // code was analysed to the point of understanding before being used // "removes" an edge from a to b (and from b to a) // by setting respective storing values to -1 void EPFleury::removeEdge(int a, int b) { std::list<int>::iterator i = std::find(adjacent[a].begin(), adjacent[a].end(), b); *i = -1; i = std::find(adjacent[b].begin(), adjacent[b].end(), a); *i = -1; } // Count the edges that have not yet been visited int EPFleury::DFSCount(int vertex, bool visited[]) { visited[vertex] = true; int count = 1; // iterate through the adjacency lists of the given node // recursively call this on each adjacent node if it hasn't been visited std::list<int>::iterator i; for (i = adjacent[vertex].begin(); i != adjacent[vertex].end(); i++) { if (*i != -1 && !(visited[*i])) { count += DFSCount(*i, visited); } } return count; } // checker to see if a given edge is valid to continue to in generating // the Eulerian Path bool EPFleury::isValidEdge(int a, int b) { int countA = 0; std::list<int>::iterator i; // true if the node has 1 and only 1 edge for (i = adjacent[a].begin(); i != adjacent[a].end(); i++) { if (*i != -1) { countA++; } } if (countA == 1) { return true; } // otherwise, count "accessible" nodes bool visited[count]; std::memset(visited, false, count); countA = DFSCount(a, visited); // count "accessible" nodes if the considered edge is removed removeEdge(a, b); std::memset(visited, false, count); int countB = DFSCount(a, visited); addEdge(a, b); // true if removing the edge does not affect // the overall accessibility, false if it cuts off a section return (countA > countB) ? false : true; } // a function I added for debugging void EPFleury::printAdjacent() { std::list<int>::iterator i; for (int k = 0; k < count; k++) { for (i = adjacent[k].begin(); i != adjacent[k].end(); i++){ std::cout << "k: " << k << "\telement: " << *i << std::endl; } } } // main function to build the path through Fleury's algorithm // determins the start node, then calls a halper function std::vector<int> * EPFleury::buildPath() { int start = 0; for (int i = 0; i < count; i++) { if (adjacent[i].size() % 2 == 1) { start = i; path->push_back(start); break; } } // std::cout << "starting at " << start << std::endl; _build(start); return this->path; } // functino that gets the path std::vector<int> *EPFleury::getPath() { // if the path doesn't contain all the possible nodes, remake it if (path->size() < count) { // std::cout << "need to build before returning path. size = " << path->size() << " count = " << count << std::cout; path->resize(0); buildPath(); } return path; } // helper for the build function void EPFleury::_build(int current) { // for all nodes adjacent to current... std::list<int>::iterator i; for (i = adjacent[current].begin(); i != adjacent[current].end(); i++) { int vertex = *i; // if the edge is valid if (vertex != -1 && isValidEdge(current, vertex)) { // remove it, add it to the path and recurse to the considered vertex removeEdge(current, vertex); path->push_back(vertex); _build(vertex); } } } // function to add edges to the internal edge set // requires externals to set up the edges of the multigraph to consider void EPFleury::addEdge(int a, int b){ adjacent[a].push_back(b); adjacent[b].push_back(a); return; }
true
3ef763fe99f857c5ea44c62f9d2feb0ca942b2c1
C++
ShivamNegi/Coding-Practice
/CodeChef/Easy/adjlistusingstl.cpp
UTF-8
478
3
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int x, y, n; cout<<"How many edges?"; cin>>n; vector< vector< pair<int, int> > > g(n); for(int i = 0; i < n; i++) { cin>>x>>y; g[x].push_back(make_pair(y, 1)); } for(int i = 0; i < g.size(); i++) { for(int j = 0; j < g[i].size(); j++) cout<<i<<"\t"<<g[i][j].first<<"\n"; cout<<endl; } return 0; }
true
3255b33e79a122dc687a297d5dc87cdb2db4cfc4
C++
Lucky2307/DrawLine
/DrawLine/src/Main.cpp
UTF-8
7,960
2.578125
3
[]
no_license
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include "Shader.h" #include "Line.h" #include "vendor/imgui/imgui.h" #include "vendor/imgui/imgui_impl_opengl3.h" #include "vendor/imgui/imgui_impl_glfw.h" void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow* window); void recalculateVertices(unsigned int* VAO, unsigned int* VBO, int pStart[2], int pFinal[2], int* numOfPixels); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; const char* glsl_version = "#version 150"; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // required for apple machine #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Draw Line", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSwapInterval(1); // Enable vsync glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } Shader ourShader("shaders/vertexGLSL.vs", "shaders/fragmentGLSL.fs"); // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // Setup Platform/Renderer backends ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init(glsl_version); // set up buffer(s) // ---------------------------------- unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Our initial state float clear_color[] = { 1.0f, 1.0f, 1.0f, 1.0f }; float line_color[] = { 0.0f, 0.0f, 0.0f, 0.0f }; float point_size = 5.0f; int pStart[2] = { 0, 0 }; int pFinal[2] = { 0, 0 }; int numOfPixels = 0; glEnable(GL_PROGRAM_POINT_SIZE); // enable this to manipulate pixel size // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3]); glClear(GL_COLOR_BUFFER_BIT); // be sure to activate the shader ourShader.use(); // set the customizable attribute with uniform ourShader.setFloat("pointSize", point_size); ourShader.setVec4("lineColor", line_color); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized glDrawArrays(GL_POINTS, 0, numOfPixels); // Start the Dear ImGui frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); // Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. { ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) ImGui::SliderFloat("Point size", &point_size, 0.0f, 50.0f); ImGui::ColorEdit3("Background color", clear_color); // RGB ImGui::ColorEdit4("Line color", line_color); // RGBA ImGui::InputInt2("Starting point", pStart); ImGui::InputInt2("Final point", pFinal); if (ImGui::Button("Draw line")) { recalculateVertices(&VAO, &VBO, pStart, pFinal, &numOfPixels); } ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); } // Rendering ImGui::Render(); int display_w, display_h; glfwGetFramebufferSize(window, &display_w, &display_h); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteProgram(ourShader.ID); // Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwDestroyWindow(window); glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } void recalculateVertices(unsigned int* VAO, unsigned int* VBO, int pStart[2], int pFinal[2], int* numOfPixels) { Line newLine(pStart, pFinal, SCR_WIDTH, SCR_HEIGHT); std::vector<float> points = newLine.createPoints(); // this is 1d vector!! *numOfPixels = points.size() / 3; // each pixel vertex within the std::vector has 3 components float* vertices = &points[0]; // "convert" the std::vector into traditional array // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(*VAO); glBindBuffer(GL_ARRAY_BUFFER, *VBO); glBufferData(GL_ARRAY_BUFFER, points.size() * sizeof(vertices), vertices, GL_DYNAMIC_DRAW); // position attribute (only x, y and z component) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); }
true
7e60b93cb11140f85cc518e0f4bc0a9b219033fb
C++
Rosein/SnakeGameNokia
/ut/TestSnake.cpp
UTF-8
1,572
3.21875
3
[]
no_license
#include <gtest/gtest.h> #include "../include/Snake.hpp" class SnakeTest : public ::testing::Test { protected: // SnakeTest(){} // ~SnakeTest(){} // void SetUp(){} Snake snake{100,100}; }; TEST_F (SnakeTest, newSnakeStartingPosition) { coord p {100, 100}; EXPECT_EQ( p , snake.getHead()); } TEST_F (SnakeTest, check_last_position) { coord p {60, 100}; EXPECT_EQ(p , snake.getBody().back()); } TEST_F (SnakeTest, checkingSnakePositionAfterMovingWithDefaultDirection) { snake.move(); coord headC{ 110, 100}; coord lastC{ 70, 100 }; EXPECT_EQ(headC, snake.getHead()); EXPECT_EQ(lastC, snake.getBody().back()); } TEST_F (SnakeTest, checkingHeadPositionAfterMovingWithInGivenDirection) { coord p {100, 90}; snake.changeDirection(Direction::Up); snake.move(); EXPECT_EQ(p, snake.getHead()); } TEST_F (SnakeTest, checkingHeadPositionAfterMovingBackShouldNoEffect) { coord p {110, 100}; snake.changeDirection(Direction::Left); snake.move(); EXPECT_EQ(p, snake.getHead()); } TEST_F (SnakeTest, checkingLastSegmentPositionAfterGrowing) { coord p {60, 100}; snake.grow(); snake.move(); EXPECT_EQ(p, snake.getBody().back()); } TEST_F (SnakeTest, checkingLastSegmentPositionAfterReverse) { coord p {90, 100}; snake.move(); //110 100 snake.changeDirection(Direction::Up); snake.move(); //110 90 snake.move(); //110 80 snake.grow(); snake.changeDirection(Direction::Left); snake.move(); //100 80 EXPECT_EQ(p, snake.getBody().back()); }
true
2e28e1507247034f403ebfc03615bc04c9b8a35d
C++
Surflyan/Code-Set
/C++/work/main.cpp
GB18030
1,636
2.96875
3
[]
no_license
//Ϊļ飬 #include <iostream> #include <fstream> #include"Curve3D.h" using namespace std; int main() { Point3D p1(1, 2, 3),p2(2, 3, 4), p3(4, 5, 6), p4(5, 6, 7), p5(6, 7, 8), p6(7, 8, 9), p7(8, 9, 10); Curve3D L1(0,0,0); Curve3D L2, L3, L4, L5, L6, L7; cout << "_________________"<<endl; L2 = L1 + p1; //ӵ L2.display_curve(); //Ϣ L2.curve_len(); //㳤 cout << "_________________" << endl; L3 = L2 + p2; L4 = L3 + p4; //֤ĸʼ L5 = L4 + p5; L6 = L5 + p6; L7 = L6 + p7; L7.display_curve(); L7.curve_len(); cout << "_________________" << endl; L3 = L2 - p1; //ɾ L3.display_curve(); L4.curve_len(); cout << "_________________" << endl; L4 = L3; //ߵĸֵ L4.display_curve(); L4.curve_len(); cout << "__________________" << endl; ofstream ascii_file("file.txt"); //дıļ L7.write_txt(ascii_file); ascii_file.close(); ifstream file2("file.txt"); //ȡıļ L1.read_txt(file2); file2.close(); L1.display_curve(); cout << "______________________" << endl; ofstream binary_fiel("binary.bin"); //дļ L7.write_binary(binary_fiel); binary_fiel.close(); ifstream binary_read("binary.bin"); //ȡļ L2.read_binary(binary_read); binary_read.close(); L2.display_curve(); }
true
3ca6838f4c4821d460d191a837be39d7b3a8a390
C++
alexandraback/datacollection
/solutions_5631989306621952_0/C++/x7903/A.cpp
UTF-8
518
2.515625
3
[]
no_license
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <algorithm>' #include <fstream> using namespace std; string s,ans; int t; int main() { ofstream fp("A.out"); scanf("%d",&t); for (int cas=1;cas<=t;++cas) { cin>>s; ans=s[0]; for (int i=1;i<s.size();++i) { if (ans[0]<=s[i]) ans=s[i]+ans; else ans=ans+s[i]; } fp<<"Case #"<<cas<<": "<<ans<<endl; } return 0; }
true
20f4de6f3fedc5b024ad7c1981f5bf65d0b35a2b
C++
Balzu/Parallel-Jacobi
/jacobi_seq.cpp
UTF-8
7,062
2.84375
3
[]
no_license
#include <iostream> #include <vector> #include <string.h> #include <math.h> #include <ff/farm.hpp> using namespace ff; void init_rand_matrix(std::vector<std::vector<float>>& a, int n, int max, bool diag_dominant){ if (diag_dominant == false){ // Build a completely random matrix for (int i=0; i<n ; i++){ for (int j=0; j<n; j++) a[i][j] = ((float) (rand() % max)); } } else { // Else build a random matrix, but diagonally dominant float sum; for (int i=0; i<n ; i++){ sum = 0; for (int j=0; j<n; j++){ a[i][j] = ((float) (rand() % max)); sum += a[i][j]; } a[i][i] = sum; } } } void init_zero_vec(std::vector<float>& x, int n){ for (int i=0; i<n; i++) x[i] = 0.0; } void init_rand_vec(std::vector<float>& b, int n, int max){ for (int i=0; i<n; i++) b[i] = ((float) (rand() % max)); } void print_matrix(std::vector<std::vector<float>>& a, int n){ for (int i=0; i<n ; i++){ for (int j=0; j<n; j++) std::cout << a[i][j] << " "; std::cout << std::endl; } } void print_vec(std::vector<float>& a, int n){ for (int i=0; i<n ; i++) std::cout << a[i] << " " ; } void jacobi(std::vector<std::vector<float>>& a, std::vector<float>& b, std::vector<float>& x, int n, int max_iter, float tollerance){ int k = 0; float epsilon = a[0][0]; // initialization of epsilon is arbitrary float acc; std::vector<float> x_new(n); while (k < max_iter && epsilon > tollerance){ std::cout << "\nIteration " << k << std::endl; for(int i=0; i< n; i++){ acc = 0; for (int j=0; j<n; j++){ if (i != j) acc += a[i][j] * x[j]; } x_new[i] = (1.0/a[i][i]) * (b[i] - acc); } k++; //x contains the elements previously assigned to x_new. x_new instead contains the elements previously assigned to x, //but this does not matter, since they will be overwritten. The cost of swap() is constant :). x.swap(x_new); print_vec(x,n); float max_diff = 0.0; // Store the max difference btw corrispondent items btw iterations k and k-one float abs_value; for (int i=0; i<n; i++){ abs_value = fabs(x_new[i] - x[i]); if(abs_value > max_diff) max_diff = abs_value; // max_diff must take the maximum } if (epsilon > max_diff) epsilon = max_diff; // epsilon must take the minimum } } struct Emitter: ff_node_t<float> { Emitter( ff_loadbalancer *const lb, int max_iter, float tollerance, std::vector<float>& x, std::vector<float>& x_new, int pd, int n): lb(lb),max_iter(max_iter), tollerance(tollerance), pd(pd), x(x), x_new(x_new), n(n) {} ff_loadbalancer *const lb; int max_iter, pd, n; int k = 0, received = 0; float tollerance; std::vector<float>& x; std::vector<float>& x_new; // max_diff holds the maximum difference btw 2 corresponding items (x[i] and x_new[i]) at a given iteration float epsilon = 10.0, max_diff= 0.0; // initialization of epsilon is arbitrary float *svc(float * task){ int channel = lb -> get_channel_id(); if (channel >= 0){ //std::cout << "Task received from worker " << channel << std::endl; const float& partial_diff = *task; //std:: cout << partial_diff << std::endl; received++; if (partial_diff > max_diff) max_diff=partial_diff; if (received == pd){ // One iteration is ended //print_vec(x,n); //print_vec(x_new,n); received = 0; if (epsilon < max_diff) epsilon = max_diff; max_diff = 0.0; k++; x.swap(x_new); std::cout << "\nIteration " << k << std::endl; print_vec(x,n); if (k < max_iter && epsilon > tollerance) lb -> broadcast_task((float *) GO_ON); else lb -> broadcast_task((float *) EOS); } } else { std::cout << "Task received from channel" << channel << std::endl; lb -> broadcast_task(GO_ON); //TODO: GO_ON is not propagated, but if inside this method it is? return GO_ON; //TODO: ok or useless this line? } return GO_ON; } }; struct Worker: ff_node_t<float> { Worker(std::vector<std::vector<float>>& a, std::vector<float>& b, std::vector<float>& x, std::vector<float>& x_new,int n, int start, int nrows):a(a),b(b),x(x),start(start),nrows(nrows),n(n),x_new(x_new) {} std::vector<std::vector<float>>& a; std::vector<float>& b; std::vector<float>& x; std::vector<float>& x_new; int start, nrows, n; int acc = 0; float *svc(float *){ /*std::vector<float>& tmp = x_new; x_new = x; x = tmp;*/ std::cout << "\n Worker: X = \n"; print_vec(x,n); for(int i=start; i<start+nrows; i++){ acc = 0; for (int j=0; j<n; j++){ if (i != j) acc += a[i][j] * x[j]; } x_new[i] = (1.0/a[i][i]) * (b[i] - acc); } std::cout << "\n Worker: X_new = \n"; print_vec(x_new,n); //std::cout << "Worker " << get_my_id() << " executed" << std::endl; //x.swap(x_new); //print_vec(x,n); return (new float (compute_difference())); } float compute_difference(){ float max_diff = 0.0; // Store the max difference btw corrispondent items btw iterations k and k-one float abs_value; for (int i=start; i<start+nrows; i++){ abs_value = fabs(x_new[i] - x[i]); max_diff = (abs_value > max_diff) ? abs_value : max_diff; } return max_diff; } }; int main(int argc, char *argv[]){ if (argc < 2){ std::cout << "Usage: " << argv[0] << " <matrix_dimension> <PAR_DEGREE> <diag_dominant> <iterations> <tollerance> \n" << std::endl; return -1; } int n = atoi(argv[1]); int pd = atoi(argv[2]); bool sequential = (pd <= 1) ? true : false; // TODO: can run also parallel program with just one worker bool dd = (strcmp(argv[3], "true") == 0) ? true : false; int iter = atoi(argv[4]); float tollerance = atof(argv[5]); int seed = 123; int max = 16; std::vector<std::vector<float>> a(n, std::vector<float>(n)); std::vector<float> x(n); std::vector<float> b(n); init_rand_matrix(a, n, max, dd); init_zero_vec(x,n); init_rand_vec(b,n, max); std::cout << "Printing A: " << std::endl; print_matrix(a,n); std::cout << "Printing X: " << std::endl; print_vec(x,n); std::cout << "\nPrinting B: " << std::endl; print_vec(b,n); if (true /*sequential*/) //TODO jacobi(a,b,x,n,iter,tollerance); else { std::vector<float> x_new(n); init_zero_vec(x_new,n); int base = n/pd; int remainder = n - (base * pd); int start = 0; int rows[pd]; std::vector<std::unique_ptr<ff_node>> Workers; for(int i=0; i<pd; i++){ rows[i] = base; if (remainder != 0){ //load balance the remaining rows rows[i]++; remainder--; } Workers.push_back(make_unique<Worker>(a,b,x,x_new,n,start,rows[i])); start += rows[i]; } /*for (int i=0; i<pd; i++) Workers.push_back(make_unique<Worker>(a,b,x,x_new,n,0,0)); //TODO: subst actual values to 0 */ ff_Farm<> farm(std::move(Workers)); Emitter E(farm.getlb(), iter, tollerance, x, x_new, pd, n); farm.add_emitter(E); farm.remove_collector(); farm.wrap_around(); if (farm.run_and_wait_end() < 0) return -1; } std::cout << "\n\nAfter computing Jacobi:\n" << std::endl; std::cout << "Printing X:\n " << std::endl; print_vec(x,n); return 0; }
true
252291eb0732b08eecc72d3390e421f98f3066ca
C++
lriki/Lumino.Core
/include/Lumino/IO/File.h
UTF-8
2,850
3.203125
3
[ "Zlib", "MIT" ]
permissive
/** @file File.h */ #pragma once #include "../Base/RefObject.h" #include "../Base/String.h" #include "PathName.h" #include "FileStream.h" LN_NAMESPACE_BEGIN /** @brief ファイル操作を行うクラスです。 */ class File : public Stream { public: /** @brief ファイル名を指定してインスタンスを初期化します。 @details このコンストラクタは、実際にファイルストリームを開きません。 開いていない状態では Stream クラスの機能を使用することはできません。 開くには、Open() を使用します。 */ File(const String& filePath); /** @brief ファイル名を指定してインスタンスを初期化します。 @details このコンストラクタは、実際にファイルストリームを開きません。 開いていない状態では Stream クラスの機能を使用することはできません。 開くには、Open() を使用します。 */ //explicit File(const PathName& filePath); virtual ~File(); public: /** @brief コンストラクタで指定されたファイルパスを使用してファイルストリームを開きます。 @param[in] mode : ファイルを開く方法 @param openMode : ファイルを開く方法 (FileOpenMode のフラグの組み合わせ) */ void Open(FileOpenMode openMode); /** @brief 開いているファイルストリームを閉じます。 @details デストラクタからも呼び出されます。 */ void Close(); /** @brief ファイルの絶対パスを取得します。 */ PathName GetFilePath() const; /** @brief 拡張子を含むファイルの名前を取得します。 @code File f("C:\ConsoleApplication1\Program.cs"); f.GetFileName(); // => "Program.cs" @endcode */ String GetFileName() const; /** @brief 現在のファイルサイズをバイト単位で取得します。 */ //uint64_t GetLength() const; public: // override Stream virtual bool CanRead() const; virtual bool CanWrite() const; virtual int64_t GetLength() const; virtual int64_t GetPosition() const; virtual size_t Read(void* buffer, size_t byteCount); virtual void Write(const void* data, size_t byteCount); virtual void Seek(int64_t offset, SeekOrigin origin); virtual void Flush(); private: PathName m_filePath; FileStreamPtr m_fileStream; }; class TemporaryFile : public File { public: TemporaryFile(); ~TemporaryFile(); void Open(); /** デストラクタで一時ファイルを自動削除するかを指定します。*/ void SetAutoRemove(bool enabled) { m_autoRemove = enabled; } /** デストラクタで一時ファイルを自動削除するかを確認します。*/ bool IsAutoRemove() const { return m_autoRemove; } private: bool m_autoRemove; }; LN_NAMESPACE_END
true
1c26d3d1764badcb403ace0e8608bc4f7938a346
C++
dream-overflow/o3d
/include/o3d/core/radixsort.h
UTF-8
2,288
2.671875
3
[]
no_license
/** * @file radixsort.h * @brief Thanks to Pierre Terdiman for its revisited RadixSort. * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2002-03-04 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #ifndef _O3D_RADIXSORT_H #define _O3D_RADIXSORT_H #include "memorydbg.h" #include "base.h" #define O3D_RADIX_LOCAL_RAM namespace o3d { //--------------------------------------------------------------------------------------- //! @class RadixSort //------------------------------------------------------------------------------------- //! Class for sort value (float,int), signed or unsigned, in growing order. //! Sort by radix. Used frequently for sort when the speed is crucial. //! (ie: Alpha blended surface). It use temporal coherence for test if sort is needed. //! Thanks to Pierre Terdiman for its revisited RadixSort. //--------------------------------------------------------------------------------------- class O3D_API RadixSort { private: Int32 m_counter; UInt32* m_pIndices; //!< Two lists, swapped each pass UInt32* m_pIndices2; UInt32 m_CurrentSize; //!< Current size of the indices list UInt32 m_PrevSize; //!< Size involved in previous call UInt32 m_TotalCalls; UInt32 m_NbHits; Bool resize(UInt32 size); void resetIndices(); #ifndef O3D_RADIX_LOCAL_RAM UInt32* m_pHistogram; //!< Counters for each byte UInt32* m_pOffset; //!< Counters for each byte #endif public: //! default constructor RadixSort(); ~RadixSort(); //! sort methods RadixSort& sort(const UInt32* input,UInt32 nbelt,Bool signedvalues=True); RadixSort& sort(const Float* input2,UInt32 nbelt); //! Access to results. mIndices is a list of indices in sorted order, i.e. in the order you may further process your data inline UInt32* getIndices()const { return m_pIndices; } //! mIndices2 gets trashed on calling the sort routine, but otherwise you can recycle it the way you want. inline UInt32* getRecyclabe()const { return m_pIndices2; } //! Stats UInt32 getUsedRam()const; inline UInt32 getNumTotalCalls()const { return m_TotalCalls; } //! Returns the number of premature exits due to temporal coherence. inline UInt32 getNumHits()const { return m_NbHits; } }; } // namespace o3d #endif // _O3D_RADIXSORT_H
true
4063585f7333cc9f26250b981a5bbe52cd62ab13
C++
dotdecimal/open-cradle
/cradle/tests/geometry/angle.cpp
UTF-8
992
2.71875
3
[ "MIT" ]
permissive
#include <boost/assign/std/vector.hpp> #include <cradle/geometry/angle.hpp> #define BOOST_TEST_MODULE angle #include <cradle/test.hpp> using namespace cradle; using namespace boost::assign; BOOST_AUTO_TEST_CASE(angle_test) { angle<double,radians> r(7 * pi / 2); angle<double,degrees> d(r); d.normalize(); CRADLE_CHECK_ALMOST_EQUAL(d.get(), -90.); d = -1000; d.normalize(); CRADLE_CHECK_ALMOST_EQUAL(d.get(), 80.); d = -180; d.normalize(); CRADLE_CHECK_ALMOST_EQUAL(d.get(), 180.); CRADLE_CHECK_ALMOST_EQUAL((angle<double,radians>(d).get()), pi); d = d + d; d.normalize(); CRADLE_CHECK_ALMOST_EQUAL(d.get(), 0.); CRADLE_CHECK_ALMOST_EQUAL(sin(d), 0.); CRADLE_CHECK_ALMOST_EQUAL(cos(d), 1.); d = d + angle<double,degrees>(1); CRADLE_CHECK_ALMOST_EQUAL(d.get(), 1.); CRADLE_CHECK_ALMOST_EQUAL(sin(d), 0.017452406437283512819418978516316); CRADLE_CHECK_ALMOST_EQUAL(cos(d), 0.99984769515639123915701155881391); }
true
8e6b0d3ffa3e2b9548a2590395079a03aad95e11
C++
jonathan-j-lee/pie-central-fork
/smart-devices/SmartDevice/src/Hub.hpp
UTF-8
2,480
3.25
3
[]
no_license
#ifndef HUB_H_ #define HUB_H_ #include <stdint.h> #include "message.hpp" #include "SmartDevice.hpp" typedef uint8_t pin_t; template <typename T> class Spoke { protected: pin_t pin; T value; public: Spoke(pin_t pin) { this->pin = pin; } void setup(void) { pinMode(this->pin, INPUT); } void get_parameter(message::Parameter *param) { param->base = &this->value; param->size = sizeof(this->value); } virtual bool read(void) = 0; bool write(void) { /* Default implementation of a sensor with no writeable parameters. */ return false; } void disable(void) { /* Default implementation of a sensor with no writeable parameters. */ } }; /** * A hub Smart Device is a special Smart Device that controls multiple * identical sensors or actuators (the "spokes"). Each spoke measures or acts * on a single scalar value and is placed on a single pin. * * Because each sensor is so simple, it is more economical to have each * microcontroller monitor more than just one. */ template <typename T, size_t N> class HubSmartDevice: public SmartDevice { Spoke<T> *spokes; public: HubSmartDevice(Spoke<T> *spokes) { this->spokes = spokes; } void setup(void) override { for (size_t i = 0; i < N; i++) { this->spokes[i].setup(); } } size_t get_parameters(message::Parameter *params) override { for (size_t i = 0; i < N; i++) { this->spokes[i].get_parameter(&params[i]); } return N; } message::param_map_t read(message::param_map_t params) override { message::param_map_t params_read = message::Message::NO_PARAMETERS; for (size_t i = 0; i < min(N, MAX_PARAMETERS); i++) { if (get_bit(params, i) && this->spokes[i].read()) { set_bit(params_read, i); } } return params_read; } message::param_map_t write(message::param_map_t params) override { message::param_map_t params_written = message::Message::NO_PARAMETERS; for (size_t i = 0; i < min(N, MAX_PARAMETERS); i++) { if (get_bit(params, i) && this->spokes[i].write()) { set_bit(params_written, i); } } return params_written; } void disable(void) override { for (size_t i = 0; i < N; i++) { this->spokes[i].disable(); } } }; #endif
true
afe6e772c878d9fa7a94437bbea545fe4c15c1a0
C++
perfcv/LearnAndTry
/leetcode/sword/链表-从尾到头打印链表.cpp
UTF-8
1,179
3.28125
3
[]
no_license
//page 58 #include <iostream> #include <vector> #include <stack> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; // vector<int> printListFromTailToHead(ListNode *head) // { // if (head != nullptr) // { // if (head->next!=nullptr) // { // printListFromTailToHead(head->next); // } // return head->val; // } // } // vector<int> printListFromTailToHead(ListNode *head) // { // vector<int> v; // stack<ListNode *> s; // if(head==nullptr) // return v; // while(head!=nullptr) // { // s.push(head); // head=head->next; // } // while(s.size()) // { // v.push_back(s.top()->val); // s.pop(); // } // return v; // } vector<int> v; void printListFromTailToHead_repeat(ListNode *head) { if(head==nullptr) return; printListFromTailToHead_repeat(head->next); v.push_back(head->val); } vector<int> printListFromTailToHead(ListNode *head) { if(head==nullptr) return v; printListFromTailToHead_repeat(head); return v; }
true
1e85866dc32067010373f9adb6beaa8ab715ce90
C++
kyo504/design-pattern
/20160328/20160328/3_casting.cpp
UHC
1,141
3.625
4
[]
no_license
// 3_ij.cpp #include <iostream> using namespace std; // 1. C ij ̴̼. ( ְ ׷ ִ) // 2. ׷ C++ 4 ij Ѵ. // - static_cast: void* -> ٸ Ÿ Ǵ ִ ijø // - reinterpret_cast: ޸ ؼ (÷ ٸ ֱ ؾ Ѵ.) // - const_cast: ü , ֹ߼(volitile) ϴ 뵵θ // - dynamic_cast: RTTI , ٿ ij 뵵 /* volitile ޸ ü ϱ ؼ */ int main() { const int c = 10; int* p = const_cast<int*>(&c); *p = 20; cout << *p << endl; cout << c << endl; } #if 0 int main() { //int *p1 = (int*)malloc(sizeof(100)); int *p1 = static_cast<int*>(malloc(sizeof(100))); int n = 0; // double* p = (double*)&n; // c ŸϷδ ij ޸ ħ Ǵ ߻ ִ. double* p = reinterpret_cast<double*>(&n); *p = 3.14; // ؾ Ѵ } #endif
true