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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b34f2404de87e6b98b5eb19d8c54d13612eaaf0c | C++ | Lukious/2020_Kwangwoon_Univ_CE_DS_Project_3 | /Window/MinHeap.h | UTF-8 | 1,875 | 3.546875 | 4 | [] | no_license | #ifndef MIN_HEAP_H
#define MIN_HEAP_H
#include <utility>
#include <vector>
template<typename TKey, typename TValue>
class MinHeap
{
private:
// array for the elements which should be heap-sorted
std::vector<std::pair<TKey, TValue>> m_vec;
public:
MinHeap() {}
/// <summary>
/// insert key-value pair
/// </summary>
///
/// <param name="key">
/// the key that is used for sorting
/// </param>
///
/// <param name="value">
/// the value that is managed in this heap
/// </param>
void Push(TKey key, TValue value);
/// <summary>
/// remove the minimum element
/// </summary>
void Pop();
/// <summary>
/// get the minimum element
/// </summary>
///
/// <returns>
/// the minimum element
/// </returns>
std::pair<TKey, TValue> Top();
/// <summary>
/// get the key-value pair which the value is the same as the target
/// </summary>
///
/// <returns>
/// the key-value pair which the value is the same as the target
/// </returns>
std::pair<TKey, TValue> Get(TValue target);
/// <summary>
/// check whether this heap is empty or not
/// </summary>
///
/// <returns>
/// true if this heap is empty
/// </returns>
bool IsEmpty();
/// <summary>
/// change the key of the node which the value is the target.<para/>
/// In general, the newKey should be smaller than the old key.<para/>
/// </summary>
///
/// <parma name="target">
/// the target to change the key
/// </param>
///
/// <param name="newKey">
/// new key for the target
/// </param>
void DecKey(TValue target, TKey newKey);
private:
/// <summary>
/// heap-sort, heapify.<para/>
/// this function can be called recursively
/// </summary>
void Heapify(int index);
};
#endif
| true |
f3df787b4bee0058ece2370514b3e01432ed4507 | C++ | SuYuxi/yuxi | /Algorithms/Design/460. LFU Cache.cpp | UTF-8 | 1,618 | 3.5 | 4 | [] | no_license | //Least Frequently Used Cache
using namespace std;
class LFUCache {
public:
LFUCache(int _capacity) : capacity(_capacity)
, size(0)
, minFreq(0)
{}
int get(int key) {
if(hash.count(key) == 0) return -1;
int value = hash[key].first;
int freq = hash[key].second++;
hashList[freq].erase(hashIter[key]);
hashList[freq + 1].emplace_front(key);
hashIter[key] = hashList[freq + 1].begin();
if(hashList[minFreq].empty())
{
minFreq += 1;
}
return value;
}
void put(int key, int value) {
if(capacity <= 0) return; //important
if(hash.count(key) != 0)
{
int freq = hash[key].second++;
hashList[freq].erase(hashIter[key]);
hashList[freq + 1].emplace_front(key);
hashIter[key] = hashList[freq + 1].begin();
hash[key].first = value;
if(hashList[minFreq].empty())
{
minFreq += 1;
}
return;
}
if(size == capacity)
{
int k = hashList[minFreq].back();
hashList[minFreq].pop_back();
hash.erase(k);
hashIter.erase(k);
size -= 1;
}
minFreq = 1;
hash[key] = {value, minFreq};
hashList[minFreq].emplace_front(key);
hashIter[key] = hashList[minFreq].begin();
size += 1;
}
private:
unordered_map<int, pair<int, int>> hash; //key to value and frequency
unordered_map<int, list<int>::iterator> hashIter; //key to iter
unordered_map<int, list<int>> hashList;//frequency to list
int capacity;
int size;
int minFreq;
};
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache* obj = new LFUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
| true |
5c39818727ce5e290f3a443bc79e9cf87fbd5d31 | C++ | ag2400036/GrambergsAdam_CIS5_40652 | /Hmwk/Assignment_3/Gaddis_8thEd_Ch4_Problem4_AreasOfRectangles/main.cpp | UTF-8 | 750 | 3.734375 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Adam Grambergs
* Created on January 17, 2018, 7:50 PM
* Purpose: Determine if the date is magic based on day * month = year.
*/
//System Libraries
#include<iostream>
using namespace std;
int main()
{
int L1, W1, L2, W2;
cout << "Enter the lengths and widths of two rectangles: ";
cout << "Length one: ";
cin >> L1;
cout << "Width one: ";
cin >> W1;
cout << "Length two: ";
cin >> L2;
cout << "Width two: ";
cin >> W2;
if ( ( L1 * W1 ) > ( L2 * W2 ) )
cout << "The first rectangle has a larger area. ";
else if ( ( L2 * W2 ) > ( L1 * W1 ) )
cout << "The second rectangle has a larger area. ";
else
cout << "The rectangles have the same area. ";
return 0;
} | true |
32bbf63b1a92d1c7ecdfdd558df8959bed171d43 | C++ | RandomVar/ACM | /专题合集/数学/Leftmost Digit.cpp | UTF-8 | 510 | 2.546875 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<queue>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int INF=0x3f3f3f3f;
int main(){
int t;cin>>t;
while(t--){
ll n;
cin>>n;
/* double x;
x=n*(log10((double)n));
x-=(ll)x;
x=pow(10,x);
ll ans=(ll)x;*/
ll dig=(ll)n*log10(n);
//cout<<dig<<endl;
double ans=(double)n*log10((double)n)-dig;
//cout<<ans<<endl;
ans=pow(10,ans);
cout<<(ll)ans<<endl;
}
}
| true |
aa755ec667288d7dbb23dd5d0d63959d3087c7b1 | C++ | AradiPatrik/sc2Bot | /GameMap.cpp | UTF-8 | 2,705 | 2.8125 | 3 | [] | no_license | #include "GameMap.h"
#include "Bot.h"
#include <algorithm>
#include <iostream>
#include "Predicates.h"
#include "BaseLocation.h"
#include "Utils.h"
GameMap::GameMap(Bot &bot)
: m_bot(bot)
, m_width(0)
, m_height(0)
{
}
void GameMap::OnStart()
{
// this needs cleaning up
m_width = m_bot.Observation()->GetGameInfo().width;
m_height = m_bot.Observation()->GetGameInfo().height;
// Initialize m_baseLocations
sc2::Units resources = m_bot.Observation()->GetUnits(sc2::Unit::Alliance::Neutral, Predicates::isResource);
std::vector<sc2::Units> resourceClusters = ClusterResources(resources);
for (const auto& cluster : resourceClusters)
{
BaseLocation temp{ cluster, *this };
m_baseLocations.push_back(temp);
}
// DrawPlaceableGrid();
m_bot.Debug()->SendDebug();
}
void GameMap::ReserveTiles(const std::vector<sc2::Point2DI> &tiles)
{
// TODO: check if tile is already reserved
for (const auto& tile : tiles)
{
m_reservedTiles.push_back(tile);
}
}
bool GameMap::IsTileReserved(const sc2::Point2DI &tile)
{
// TODO: test this
for (const auto &reservedTile : m_reservedTiles)
{
if (tile == reservedTile)
return true;
}
return false;
}
bool GameMap::IsTilePlaceable(const sc2::Point2DI &tile)
{
// TODO: test this
return Utils::IsPlaceable(m_bot.Observation()->GetGameInfo(), tile) && !IsTileReserved(tile);
}
void GameMap::DrawPlaceableGrid()
{
for (size_t y{ 0 }; y < m_height; y++)
{
for (size_t x{ 0 }; x < m_width; x++)
{
Utils::DrawSquareAroundPoint
(
*m_bot.Debug(),
sc2::Point3D(x, y, Utils::HeightAtTile(m_bot.Observation()->GetGameInfo(), x, y)),
0.5f
);
}
}
}
std::vector<sc2::Units> GameMap::ClusterResources(sc2::Units resources)
{
// tweak this if something broken about clustering
const float maxSquareDistance = 400;
std::vector<sc2::Units> resourceClusters;
while (!resources.empty())
{
sc2::Units cluster;
auto iterator = resources.begin();
sc2::Point3D relativeTo = iterator->pos;
while (iterator != resources.end())
{
const sc2::Point3D currentPos = iterator->pos;
if (sc2::DistanceSquared3D(currentPos, relativeTo) < maxSquareDistance)
{
cluster.push_back(*iterator);
relativeTo == iterator->pos;
iterator = resources.erase(iterator);
}
else
{
++iterator;
}
}
resourceClusters.push_back(cluster);
}
return resourceClusters;
}
void GameMap::DrawBoxAroundPoint(const sc2::Point3D& point, float radius, sc2::Color color)
{
Utils::DrawSquareAroundPoint(*m_bot.Debug(), point, radius, color);
}
void GameMap::DrawLineBetweenPoints(const sc2::Point3D& first, const sc2::Point3D& second, sc2::Color color)
{
m_bot.Debug()->DebugLineOut(first, second, color);
} | true |
b17e4e9ef9a60e4ffebc4d6b498d5a8fb292ac58 | C++ | JoshuaSledden/Networking-ASIO | /Engine/Network/client.h | UTF-8 | 2,314 | 2.640625 | 3 | [] | no_license | #pragma once
#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include "message.h"
#include "global_frame.h"
using boost::asio::ip::tcp;
typedef std::deque<message> message_queue;
class client
{
public:
client(boost::asio::io_context& io_context,
const tcp::resolver::results_type& endpoints)
: io_context_(io_context),
socket_(io_context) {
// connects to the server and starts the recursive client loop.
do_connect(endpoints);
}
void write(const message& msg) {
boost::asio::post(
io_context_,
[this, msg]() {
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress) {
do_write();
}
}
);
}
void close() {
boost::asio::post(io_context_, [this]() { socket_.close(); });
}
private:
void do_connect(const tcp::resolver::results_type& endpoints) {
GLOBAL_FRAME_LOG("Attempting to connect...");
boost::asio::async_connect(
socket_,
endpoints,
[this](boost::system::error_code ec, tcp::endpoint) {
if (!ec) {
do_read_header();
}
}
);
}
void do_read_header() {
boost::asio::async_read(
socket_,
boost::asio::buffer(read_msg_.data(), message::header_length),
[this](boost::system::error_code ec, std::size_t /*length*/) {
if (!ec && read_msg_.decode_header()) {
do_read_body();
}
else {
socket_.close();
}
}
);
}
void do_read_body() {
boost::asio::async_read(
socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
[this](boost::system::error_code ec, std::size_t /*length*/) {
if (!ec) {
std::string s(read_msg_.body(), read_msg_.body_length());
GLOBAL_FRAME_LOG(s);
do_read_header();
}
else {
socket_.close();
}
}
);
}
void do_write() {
boost::asio::async_write(
socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
[this](boost::system::error_code ec, std::size_t /*length*/) {
if (!ec) {
write_msgs_.pop_front();
if (!write_msgs_.empty()) {
do_write();
}
}
else {
socket_.close();
}
}
);
}
private:
boost::asio::io_context& io_context_;
tcp::socket socket_;
message read_msg_;
message_queue write_msgs_;
};
| true |
3525d062cc36213daedb910a2c2164f3b5d13ac9 | C++ | PaisMariano/UNQ | /ED/C++/LinkedLists/AppendableListsRecorribles/AppendableListsRecorribles.cpp | UTF-8 | 5,948 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <malloc.h>
#include "..\Prelude\Prelude.h"
#include "AppendableListsRecorribles.h"
void consLink(lNode* x, List& xsref);
void snocLink(List& xsref, lNode* x);
/*************************************/
/* Implementacion de las operaciones */
/* */
/* OBS: */
/* mkCons, etc. reciben una */
/* referencia para enfatizar que */
/* que se trata de operaciones */
/* destructivas */
/*************************************/
List Nil() {
/*
PROPOSITO: construye la lista vacia
PRECOND: ninguna, es una operacion total
*/
lHeader* newList = new lHeader;
newList->firstElem = NULL;
newList->lastElem = NULL;
newList->currentElem = NULL;
newList->currentId = 0;
newList->nextId = 1;
return newList;
}
void mkCons(ELEM_TYPE x, List& xs) {
/*
PROPOSITO: agrega el elemento x adelante de la lista xs
PRECOND: ninguna, es una operacion total
OBSERVACIONES:
* modifica xs
* anula el recorrido actual
*/
lNode* newNode = new lNode;
newNode->value = x;
consLink(newNode, xs);
}
void consLink(lNode* newNode, List& xsref) {
/*
PROPOSITO: engancha el nodo dado adelante de la lista xs
PRECOND: ninguna, es una operacion total
OBSERVACIONES:
* modifica xs Y newNode
* anula el recorrido actual
*/
newNode->next = xsref->firstElem;
xsref->firstElem = newNode;
if (xsref->lastElem == NULL) xsref->lastElem = newNode;
xsref->currentId = 0;
}
void mkSnoc(List& xs, ELEM_TYPE x)
/*
PROPOSITO: agrega el elemento x atras de la lista xs
PRECOND: ninguna, es una operacion total
OBSERVACIONES:
* modifica xs
* anula el recorrido actual
*/
{
lNode* newNode = new lNode;
newNode->value = x;
newNode->next = NULL;
snocLink(xs, newNode);
}
void snocLink(List& xsref, lNode* newNode) {
if (xsref->lastElem == NULL)
xsref->firstElem = newNode;
else xsref->lastElem->next = newNode;
xsref->lastElem = newNode;
xsref->currentId = 0;
}
bool isNil(List xs)
/*
PROPOSITO: pregunta si es la lista vacia
PRECOND: ninguna, es una operacion total
*/
{ return (xs->firstElem == NULL); }
ELEM_TYPE splitHead(List& xsref)
/*
PROPOSITO: devuelve el primer elemento de la lista, y modifica la lista para que no
tenga mas primer elemento
PRECOND: xs no es vacia
OBSERVACIONES:
* modifica xs.
* libera memoria
*/
{
lNode* tempNode = xsref->firstElem;
ELEM_TYPE temp = tempNode->value;
xsref->firstElem = tempNode->next;
free(tempNode);
if (xsref->firstElem == NULL) xsref->lastElem = NULL;
xsref->currentId = 0;
return temp;
}
/*************************************/
Handle IniciarRecorrido(List& xsref)
{
xsref->currentId = xsref->nextId++;
xsref->currentElem = xsref->firstElem;
return (xsref->currentId);
}
bool finRecorrido(List xs, Handle h)
{
if (xs->currentId != h) exit(1);
return (xs->currentElem == NULL);
}
ELEM_TYPE elementoActual(List xs, Handle h)
{
if (xs->currentId != h) exit(1);
return (xs->currentElem->value);
}
void PasarAlSiguiente(List& xsref, Handle h)
{
if (xsref->currentId != h) exit(1);
xsref->currentElem = xsref->currentElem->next;
}
void FinalizarRecorrido(List& xsref, Handle h)
{
if (xsref->currentId != h) exit(1);
xsref->currentId = 0;
}
/*************************************/
List copiar(List xs) {
Handle h = IniciarRecorrido(xs);
List newList = Nil();
while (not finRecorrido(xs,h))
{
mkSnoc(newList, elementoActual(xs,h));
PasarAlSiguiente(xs,h);
}
FinalizarRecorrido(xs,h);
return newList;
}
/*************************************/
void mkInsert(int x, List& xsref) {
/*
PROPOSITO: inserta x de manera ordenada en la lista
PRECOND: la lista xs esta ordenada
OBSERVACIONES: es una operacion destructiva
*/
struct lNode* current;
// Se prepara el nodo para x
lNode* newNode = new lNode;
newNode->value = x;
// newNode->next = Nil();
// Se calcula el punto de insercion
if (isNil(xsref) || x <= xsref->firstElem->value)
consLink(newNode, xsref);
else
{
current = xsref->firstElem;
while (not (current->next == NULL) && x > current->next->value)
current = current->next;
// Es casi consLink, pero con otro espacio de memoria
// Capturar esa similitud seria complejo y poco conveniente
newNode->next = current->next;
current->next = newNode;
if (xsref->lastElem == current) xsref->lastElem = newNode;
xsref->currentId = 0;
}
}
void mkAppend(List& xs, List ys){
/*
PROPOSITO: agrega los elementos de ys a xs como un append, pero destruye ys
OBSERVACIONES:
* modifica xs
* NO destruye ys, sino una copia
*/
List ysCopy = copiar(ys);
mkDump(xs,ysCopy);
}
void mkDump(List& xs, List& ys) {
/*
PROPOSITO: agrega los elementos de ys a xs como un append, pero destruye ys
OBSERVACIONES:
* modifica xs
* destruye ys
*/
if (not isNil(ys)) {
snocLink(xs, ys->firstElem);
// OJO con el ultimo elemento de xs!
xs->lastElem = ys->lastElem;
// Corrige el ultimo elemento de xs
}
delete(ys);
}
/*************************************/
void printList(List xs)
/*
PROPOSITO: imprime la lista
PRECOND: ninguna, es una operacion total
*/
{
if (isNil(xs))
{ cout << ("[]"); }
else
{
Handle h = IniciarRecorrido(xs);
cout << ("[ ");
printElemType(elementoActual(xs,h));
PasarAlSiguiente(xs,h);
while (not finRecorrido(xs,h))
{
cout << (", ");
printElemType(elementoActual(xs,h));
PasarAlSiguiente(xs,h);
}
cout << (" ]");
FinalizarRecorrido(xs,h);
}
}
| true |
490ffa5552da0179da88b6521773c1bb25e7de41 | C++ | rlskinner/Dev | /Pixelator/tieDye/trash/zz-old-src/weight.h | UTF-8 | 553 | 2.859375 | 3 | [] | no_license | #ifndef _weight_h_
#define _weight_h_
//
// define a anstract weight class that can change the weight based
// on location (absolute or relative), or history, etc.
//
class weight {
protected:
int isConst;
double constWgt;
virtual double getFunctionalWgt( int nDim, int abs[], int rel[] );
public:
weight() { isConst = 0; }
virtual ~weight();
virtual void init( int nDim, int dims[] );
double getWgt( int nDim, int abs[], int rel[] )
{ return isConst ? constWgt
: getFunctionalWgt( nDim, abs, rel ); }
};
#endif /* _weight_h_ */
| true |
3980d1fb7f8f026890dead8b08008f3ba4597561 | C++ | GreenWizardOg/huskey | /HuskeyServer.cpp | UTF-8 | 4,094 | 2.703125 | 3 | [] | no_license | /*
* HuskeyServer.cpp
*
* Main class for managing tasks, defining options and displaying help
*
* Created on: June 30, 2011
* Author: barryodriscoll
*/
#include "HuskeyServer.hpp"
#include "InfoTask.hpp"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Logger.h"
#include "ApplicationWrapper.hpp"
#include "TaskManagerWrapper.hpp"
#include "LogManager.hpp"
#include "LoggerWrapper.hpp"
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::OptionCallback;
using Poco::Util::HelpFormatter;
using Poco::Logger;
void HuskeyServer::initialize(Application& self)
{
loadConfiguration(); // load default configuration files, if present
ServerApplication::initialize(self);
LogManager logger = getLogger();
logger.log("starting up");
}
void HuskeyServer::uninitialize()
{
getLogger().log("shutting down");
ServerApplication::uninitialize();
}
void HuskeyServer::defineOptions(OptionSet& options)
{
//TODO write an intergration test in bash to make sure this all works
ServerApplication::defineOptions(options);
options.addOption(
Option("help", "h", "display help information on command line arguments, commands: 'info', 'listen', 'start' ")
.required(false)
.repeatable(false)
.callback(OptionCallback<HuskeyServer>(this, &HuskeyServer::handleHelp)));
options.addOption(
Option("info", "i", "get information about your ip address and randomly picked port number.\nNow tell your friend about it...")
.required(false)
.repeatable(false)
.callback(OptionCallback<HuskeyServer>(this, &HuskeyServer::handleInfo)));
options.addOption(
Option("listen", "l", "Listen for an incomming communication from the internet pipes")
.required(false)
.repeatable(false)
.callback(OptionCallback<HuskeyServer>(this, &HuskeyServer::handleListen)));
}
void HuskeyServer::handleHelp(const std::string& name, const std::string& value)
{
_helpRequested = true;
displayHelp();
stopOptionsProcessing();
}
void HuskeyServer::handleInfo(const std::string& name, const std::string& value)
{
//TODO write a unit test for this
HuskeyServer::getLogger().log("Handling an info request...");
_infoRequested = true;
stopOptionsProcessing();
}
void HuskeyServer::handleListen(const std::string& name, const std::string& value)
{
//TODO figure out how to open a raw socket and listen on a particular port
HuskeyServer::getLogger().log("Handling an listen request...");
_listenRequested = true;
stopOptionsProcessing();
}
void HuskeyServer::displayHelp()
{
HelpFormatter helpFormatter(options());
helpFormatter.setCommand(commandName());
helpFormatter.setUsage("OPTIONS");
helpFormatter.setHeader("Huskey, for those conversations you hope no one knows about...");
helpFormatter.setFooter("Remember, this is only a piece of software, it be badly designed/written\nOr the man could have a key logger built into your keyboard...\n\n");
helpFormatter.format(std::cout);
}
int HuskeyServer::main(const std::vector<std::string>& args)
{
//TODO make sure exe can run on unix/windows/mac without any required libs
HuskeyServer::getLogger().log("This will just sit here until you 'ctrl c' it or kill it ");
TaskManagerWrapper taskManagerWrapper;
if (_infoRequested)
{
HuskeyServer::getLogger().log("Handling an info request, some of this code has been written!");
taskManagerWrapper.startTasks(new InfoTask(new ApplicationWrapper, 5));
}
if (_listenRequested)
{
HuskeyServer::getLogger().log("Handling an listen request, pity that code hasn't been written yet");
}
HuskeyServer::getLogger().log("Done with tasks waiting to die...");
waitForTerminationRequest();
HuskeyServer::getLogger().log("Clearning up tasks");
taskManagerWrapper.killAndCleanTasks();
return Application::EXIT_OK;
}
namespace
{
static SingletonLogger singletonLogger(new LoggerWrapper);
}
LogManager& HuskeyServer::getLogger()
{
return *singletonLogger.get();
}
//only for tests
void HuskeyServer::setupMockLogger(ILogger * logger){
singletonLogger.set(logger);
}
| true |
6377b46dc1a12804c57c23377a1579f290a6de41 | C++ | SaartjeCodde/Chip8Emulator | /pdev_saartje.codde/PDevEmulator/Chip8.cpp | WINDOWS-1250 | 14,143 | 2.53125 | 3 | [] | no_license | #include "Chip8.h"
bool Chip8::Initialize(const char *path)
{
for (int i = 0; i < 4096; i++)
{
memoryBuffer[i] = 0;
}
for (int i = 0; i < 16; i++)
{
reg[i] = 0;
stack[i] = 0;
keys[i] = 0;
}
for (int i = 0; i < 2048; i++)
{
display[i] = 0;
}
regI = 0;
regPC = 0x200;
stackPointer = 0;
delayTimer = 0;
soundTimer = 0;
keyPress = 0;
LoadFile(path);
if (file == NULL) return 0;
// - Fixes for two compatibilty problems -
int checkSum = 0;
for (int i = 512; i < (4096 - 512); i++)
{
checkSum += memoryBuffer[i];
}
if (checkSum == 19434) // CONNECT4
{
incrementRegI = false; // The increment should not be there for connect 4 to work
}
if (checkSum == 40068) // BLITZ
{
ignorePixel = true; // Disabled pixel wrapping, pixels should be ignored for blitz to work
}
return 1;
}
void Chip8::LoadFile(const char *path)
{
// FONT
unsigned char chip8_fontset[80] =
{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
for (int i = 0; i < 80; i++)
{
memoryBuffer[i] = chip8_fontset[i];
}
unsigned char SuperFont[160] =
{
0xFF, 0xFF, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF, // 0
0x18, 0x78, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0xFF, // 1
0xFF, 0xFF, 0x03, 0x03, 0xFF, 0xFF, 0xC0, 0xC0, 0xFF, 0xFF, // 2
0xFF, 0xFF, 0x03, 0x03, 0xFF, 0xFF, 0x03, 0x03, 0xFF, 0xFF, // 3
0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF, 0x03, 0x03, 0x03, 0x03, // 4
0xFF, 0xFF, 0xC0, 0xC0, 0xFF, 0xFF, 0x03, 0x03, 0xFF, 0xFF, // 5
0xFF, 0xFF, 0xC0, 0xC0, 0xFF, 0xFF, 0xC3, 0xC3, 0xFF, 0xFF, // 6
0xFF, 0xFF, 0x03, 0x03, 0x06, 0x0C, 0x18, 0x18, 0x18, 0x18, // 7
0xFF, 0xFF, 0xC3, 0xC3, 0xFF, 0xFF, 0xC3, 0xC3, 0xFF, 0xFF, // 8
0xFF, 0xFF, 0xC3, 0xC3, 0xFF, 0xFF, 0x03, 0x03, 0xFF, 0xFF, // 9
0x7E, 0xFF, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF, 0xC3, 0xC3, 0xC3, // A
0xFC, 0xFC, 0xC3, 0xC3, 0xFC, 0xFC, 0xC3, 0xC3, 0xFC, 0xFC, // B
0x3C, 0xFF, 0xC3, 0xC0, 0xC0, 0xC0, 0xC0, 0xC3, 0xFF, 0x3C, // C
0xFC, 0xFE, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xFE, 0xFC, // D
0xFF, 0xFF, 0xC0, 0xC0, 0xFF, 0xFF, 0xC0, 0xC0, 0xFF, 0xFF, // E
0xFF, 0xFF, 0xC0, 0xC0, 0xFF, 0xFF, 0xC0, 0xC0, 0xC0, 0xC0, // F
};
//std::FILE* binaryFile;
errno_t err = fopen_s(&file, path, "r");
if (file != NULL)
{
std::fread(&memoryBuffer[0x200], sizeof U8, 4096, file);
}
}
void Chip8::Tick()
{
opcode = (memoryBuffer[regPC] << 8) | (memoryBuffer[regPC + 1]); // Bitwise shift of 8 bits to the left then OR it with the next byte of memory
U16 address = opcode & 0x0FFF;
regPC += 2; // CHIP-8 commands are 2 bytes
U8 x = (opcode & 0x0F00) >> 8;
U8 y = (opcode & 0x00F0) >> 4;
switch (opcode & 0xF000)
{
case 0x0000:
switch (opcode & 0x00FF)
{
case 0x00C0:
std::cout << "SCHIP-8 /case 0x00CN" << std::endl;
// SCHIP-8; Scroll display N lines down
break;
case 0x00E0:
//std::cout << "case 0x00E0" << std::endl;
// Clear the screen
for (int i = 0; i < 32 * 64; i++)
{
display[i] = 0;
}
break;
case 0x00EE:
//std::cout << "case 0x00EE" << std::endl;
// Return from a subroutine
--stackPointer; // remove the top stack
regPC = stack[stackPointer]; // set regPC to the previous stack
break;
case 0x00FB:
std::cout << "SCHIP-8 /case 0x00FB" << std::endl;
// Scroll display 4 pixels RIGHT
break;
case 0x00FC:
std::cout << "SCHIP-8 /case 0x00FC" << std::endl;
// Scroll display 4 pixels LEFT
break;
case 0x00FD:
std::cout << "SCHIP-8 /case 0x00FD" << std::endl;
// Exit CHIP interpreter
break;
case 0x00FE:
std::cout << "SCHIP-8 /case 0x00FE" << std::endl;
// Disable extended screen mode
break;
case 0x00FF:
std::cout << "SCHIP-8 /case 0x00FF" << std::endl;
// Enable extended screen mode for full-screen graphics
break;
}
break;
case 0x1000:
//std::cout << "case 0x1000" << std::endl;
// Jump to address NNN
regPC = (opcode & 0x0FFF);
break;
case 0x2000:
//std::cout << "case 0x2000" << std::endl;
// Execute subroutine starting at address NNN
stack[stackPointer] = regPC;
++stackPointer;
regPC = (opcode & 0x0FFF);
break;
case 0x3000:
//std::cout << "case 0x3000" << std::endl;
// Skip the following instruction if the value of register VX equals NN
if (reg[x] == (opcode & 0x00FF))
{
regPC += 2;
}
break;
case 0x4000:
//std::cout << "case 0x4000" << std::endl;
// Skip the following instruction if the value of register VX is not equal to NN
if (reg[x] != (opcode & 0x00FF))
{
regPC += 2;
}
break;
case 0x5000:
//std::cout << "case 0x5000" << std::endl;
// Skip the following instruction if the value of register VX is equal to the value of register VY
if (reg[x] == reg[y])
{
regPC += 2;
}
break;
case 0x6000:
//std::cout << "case 0x6000" << std::endl;
// Store number NN in register VX
reg[x] = (opcode & 0x00FF);
break;
case 0x7000:
//std::cout << "case 0x7000" << std::endl;
// Add the value NN to register VX
reg[x] += (opcode & 0x00FF);
break;
case 0x8000:
switch (opcode & 0x000F)
{
case 0x0000:
//std::cout << "case 0x0000" << std::endl;
// Store the value of register VY in register VX
reg[x] = reg[y];
break;
case 0x0001:
//std::cout << "case 0x0001" << std::endl;
// Set VX to VX OR VY
reg[x] |= reg[y];
break;
case 0x0002:
//std::cout << "case 0x0002" << std::endl;
// Set VX to VX AND VY
reg[x] &= reg[y];
break;
case 0x0003:
//std::cout << "case 0x0003" << std::endl;
// Set VX to VX XOR VY
reg[x] ^= reg[y];
break;
case 0x0004:
//std::cout << "case 0x0004" << std::endl;
// Add the value of register VY to register VX
// Set VF to 1 if a carry occurs
// Set VF to 0 if a carry does not occur
if ((reg[x] + reg[y]) > 255)
{
reg[0x000F] = 1;
}
else
{
reg[0x000F] = 0;
}
reg[x] += reg[y];
break;
case 0x0005:
//std::cout << "case 0x0005" << std::endl;
// Subtract the value of register VY from register VX
// Set VF to 0 if a borrow occurs
// Set VF to 1 if a borrow does not occur
if (reg[y] > reg[x])
{
reg[0xF] = 0;
}
else
{
reg[0xF] = 1;
}
reg[x] -= reg[y];
break;
case 0x0006:
//std::cout << "case 0x0006" << std::endl;
// Store the value of register VY shifted right one bit in register VX
// Set register VF to the least significant bit prior to the shift
reg[0xF] = reg[x] & 0x1;
reg[x] >>= 1;
break;
case 0x0007:
//std::cout << "case 0x0007" << std::endl;
// Set register VX to the value of VY minus VX
// Set VF to 0 if a borrow occurs
// Set VF to 1 if a borrow does not occur
if (reg[y] < reg[x])
{
reg[0xF] = 0;
}
else
{
reg[0xF] = 1;
}
reg[x] = reg[y] - reg[x];
break;
case 0x000E:
//std::cout << "case 0x000E" << std::endl;
// Store the value of register VY shifted left one bit in register VX
// Set register VF to the most significant bit prior to the shift
reg[0xF] = reg[x] >> 7;
reg[x] <<= 1;
break;
}
break;
case 0x9000:
//std::cout << "case 0x9000" << std::endl;
// Skip the following instruction if the value of register VX is not equal to the value of register VY
if (reg[x] != reg[y])
{
regPC += 2;
}
break;
case 0xA000:
//std::cout << "case 0xA000" << std::endl;
// Store memory address NNN in register I
regI = address;
break;
case 0xB000:
//std::cout << "case 0xB000" << std::endl;
// Jump to address NNN + V0
regPC = address + reg[0];
break;
case 0xC000:
//std::cout << "case 0xC000" << std::endl;
// Set VX to a random number with a mask of NN
reg[x] = (rand() % 255) & (opcode & 0x00FF);
break;
case 0xD000:
{
//std::cout << "0xD000" << std::endl;
// Draw
U16 X = reg[x];
U16 Y = reg[y];
U16 height = opcode & 0x000F;
U16 pixel;
reg[0xF] = 0; // reset register
for (int yPos = 0; yPos < height; ++yPos) // loop over each row
{
pixel = memoryBuffer[regI + yPos]; // fetch pixel value from memory starting at position regI
for (int xPos = 0; xPos < 8; ++xPos) // loop over 8 bits of one row
{
if ((pixel & (0x80 >> xPos)) != 0) // check if current pixel is set to 1
{
int pixelPosition = (X + xPos) + ((Y + yPos) * 64);
// For fixing problem n2: 0xDXYN can either ignore pixels that fall outside the screen, or wrap around
if (pixelPosition < 0 && !ignorePixel)
{
pixelPosition = 2047; // -> Wraps to the last pixel
}
int index = 1;
if (pixelPosition > 2047 && ignorePixel)
{
continue;
}
while (pixelPosition > 2047)
{
pixelPosition = (X + xPos) + (((Y - index++) + yPos) * 64);
}
if (display[pixelPosition] == 1) // check if pixel on display is set to 0,
{
reg[0xF] = 1; // if it is, register collision by setting register
}
display[pixelPosition] ^= 1; // set pixel value, using xor
}
}
}
}
break;
case 0xE000:
switch (opcode & 0x000F)
{
case 0x000E:
//std::cout << "case 0x000E" << std::endl;
// Skip the following instruction if the key currently stored in register VX is pressed
if (keys[reg[x]] != 0)
{
regPC += 2;
}
break;
case 0x0001:
//std::cout << "case 0x0001" << std::endl;
// Skip the following instruction if the key currently stored in register VX is not pressed
if (keys[reg[x]] == 0)
{
regPC += 2;
}
break;
}
break;
case 0xF000:
switch (opcode & 0x00FF)
{
case 0x0007:
//std::cout << "case 0x0007" << std::endl;
// Store the current value of the delay timer in register VX
reg[x] = delayTimer;
break;
case 0x000A:
//std::cout << "case 0x000A" << std::endl;
// Wait for a keypress and store the result in register VX
keyPress = 0;
for (int i = 0; i < 16; i++)
{
if (keys[i] != 0)
{
reg[x] = i;
keys[i] = 0;
keyPress = 1;
}
}
if (!keyPress)
{
regPC -= 2; // When there's no keypress received, return
}
break;
case 0x0015:
//std::cout << "case 0x0015" << std::endl;
// Set the delay timer to the value of register VX
delayTimer = reg[x];
break;
case 0x0018:
//std::cout << "case 0x0018" << std::endl;
// Set the sound timer to the value of register VX
soundTimer = reg[x];
break;
case 0x001E:
//std::cout << "case 0x001E" << std::endl;
// Add the value stored in register VX to register I
if (regI + reg[x] > 0xFFF) // for the carry
{
reg[0xF] = 1; // ex. 5 + 5, 2 digits, reg[0xF] = 1
}
else
{
reg[0xF] = 0;
}
regI += reg[x];
break;
case 0x0029:
//std::cout << "case 0x0029" << std::endl;
// Set I to the memory address of the sprite data corresponding to the hexadecimal digit stored in register VX
regI = reg[x] * 5;
break;
case 0x0033:
//std::cout << "case 0x0033" << std::endl;
// Store the binary-coded decimal equivalent of the value stored in register VX at addresses I, I + 1, and I + 2
memoryBuffer[regI] = reg[x] / 100;
memoryBuffer[regI + 1] = (reg[x] / 10) % 10;
memoryBuffer[regI + 2] = (reg[x] % 100) % 10;
break;
case 0x0030:
std::cout << "SCHIP-8 /case 0x0030" << std::endl;
// Point to I to 10-byte font sprite for digit VX (0..9)
break;
case 0x0055:
//std::cout << "case 0x0055" << std::endl;
// Store the values of registers V0 to VX inclusive in memory starting at address I
// I is set to I + X + 1 after operation
for (int i = 0; i <= x; i++)
{
memoryBuffer[regI + i] = reg[i];
}
// For fixing problem n1: 0xFX55 and 0xFX65 can either not modify register I, or increment it by X + 1
if (incrementRegI)
{
regI += x + 1;
}
break;
case 0x0065:
//std::cout << "case 0x0065" << std::endl;
// Fill registers V0 to VX inclusive with the values stored in memory starting at address I
// I is set to I + X + 1 after operation
for (int i = 0; i <= x; i++)
{
reg[i] = memoryBuffer[regI + i];
}
// For fixing problem n1: 0xFX55 and 0xFX65 can either not modify register I, or increment it by X + 1
if (incrementRegI)
{
regI += x + 1;
}
break;
case 0x075:
std::cout << "SCHIP-8 /case 0x075" << std::endl;
// STORE V0..VX in RPL user flags (x <= 7)
break;
case 0x085:
std::cout << "SCHIP-8 /case 0x085" << std::endl;
// READ V0..VX in RPL user flags (x <= 7)
break;
}
break;
}
}
void Chip8::Draw()
{
textureVector.clear();
for (int y = 0; y < 32; ++y)
{
for (int x = 0; x < 64; ++x)
{
if (display[x + y * 64] == 1)
{
textureVector.push_back(255);
textureVector.push_back(255);
textureVector.push_back(255);
}
else
{
textureVector.push_back(0);
textureVector.push_back(0);
textureVector.push_back(0);
}
}
}
}
void Chip8::Keypress(U8 k, int action)
{
// Action press = 1; release = 0, repeat = 2
if (action == GLFW_REPEAT) return;
if (k == '1') keys[0x1] = action;
else if (k == '2') keys[0x2] = action;
else if (k == '3') keys[0x3] = action;
else if (k == '4') keys[0xC] = action;
else if (k == 'Q') keys[0x4] = action;
else if (k == 'W') keys[0x5] = action;
else if (k == 'E') keys[0x6] = action;
else if (k == 'R') keys[0xD] = action;
else if (k == 'A') keys[0x7] = action;
else if (k == 'S') keys[0x8] = action;
else if (k == 'D') keys[0x9] = action;
else if (k == 'F') keys[0xE] = action;
else if (k == 'Z') keys[0xA] = action;
else if (k == 'X') keys[0x0] = action;
else if (k == 'C') keys[0xB] = action;
else if (k == 'V') keys[0xF] = action;
}
| true |
6787eb228c711a6c1838063656b1fcdfebeff6f2 | C++ | LamFSangUk/GA_maxcut | /prj1/chromosome.h | UTF-8 | 1,352 | 2.59375 | 3 | [] | no_license | #ifndef __CHROM_H__
#define __CHROM_H__
#include "global.h"
#define NORMALIZE
#define EQUAL_CROSSOVER_THRESHOLD 0.6
#define MUTATION_THRESHOLD 0.01
using namespace std;
class Chromosome{
public:
/* Constructors */
Chromosome();
Chromosome(Graph*);
Chromosome(Graph*, int);
Chromosome(const Chromosome &ch);
/* Getter & Setters */
vector<int> get_gene();
double get_quality();
void set_fitness(double);
double get_fitness();
/* Interface for GA */
static Chromosome* crossover(Chromosome*,Chromosome*);
static Chromosome* mutate(Chromosome*);
static Chromosome* local_search(Chromosome*);
/* Operator overloading */
bool operator<(const Chromosome&);
static bool comp_by_quality(Chromosome*,Chromosome*); // Comparing method
/* print for debug */
void print_chrom();
private:
Graph* m_graph;
vector<int> m_gene;
double m_quality;
double m_fitness;
friend class Population;
/* Genetic Algorithm methods */
void m_normalize();
void m_one_point_crossover(Chromosome*, Chromosome*);
void m_equal_crossover(Chromosome*, Chromosome*);
void m_typical_mutate(double);
int m_variation_moving_vertex(int);
void m_calculate_quality();
};
#endif
| true |
a85ba0e0233503f536740924c83415ba7f3601b0 | C++ | IE-KMITL/Pre-Project-Robot10 | /prepro_final_project/prepro_final_project.ino | UTF-8 | 2,939 | 2.640625 | 3 | [] | no_license | #include <HCSR04.h>
HCSR04 hc(A0,A1);//initialisation class HCSR04 (trig pin , echo pin)
int ma1 = D2; // motor A
int ma2 = D3; // motor A
int mb1 = D4;// motor B
int mb2 = D5;// motor B
int sensor_A = A2; // sensor ตรวจจับสิ่งกีดขวางทาง ขวา
int sensor_B = A4; // sensor ตรวจจับสิ่งกีดขวางทาง ซ้
int sensor_value_A = 0;
int sensor_value_B = 0;
void setup() {
pinMode(ma1, OUTPUT);
pinMode(ma2, OUTPUT);
pinMode(mb1, OUTPUT);
pinMode(mb2, OUTPUT);
pinMode(sensor_A,INPUT);
pinMode(sensor_B,INPUT);
}
void loop() {
testsensor(); // function ตรวจสอบการทำงานของ sensor ซ้าย และ ขวา
if(hc.dist()>=20&&sensor_value_A ==0&&sensor_value_B==0 ){ testforward(); }// function เดินหน้า
else if(hc.dist()<20&&sensor_value_A ==1&&sensor_value_B==0){ testMoveleft(); } // function เคลื่อนที่ไปทางซ้าย
else if(hc.dist()<20&&sensor_value_A ==0&&sensor_value_B==1){ testMoveright(); } // function เคลื่อนที่ไปทาขวา
else if (hc.dist()<20&&sensor_value_A ==1&sensor_value_B==1){ testBreak(); } // function หยุดรถ
else testStop(); // function หยุดรถ
//** function ที่ต้องเพิ่มเติม คือ การไปถึงเส้นแล้วกลับ รถ แล้วเคลื่อนรถกลับไปยังจุด start (ใช้ Sensor ตรวจสอบ สี หรือ Sensor วัดระยะ)
// ** function ตรวจสอบขอบ สนาม
}
void testsensor(){
sensor_value_A = digitalRead(sensor_A);
sensor_value_B =digitalRead(sensor_B);
}
void testforward(){
digitalWrite(ma1, LOW);
analogWrite(ma2, HIGH);
digitalWrite(mb1, LOW);
analogWrite(mb2, HIGH);
}
void testMoveleft(){
digitalWrite(ma1, LOW);
analogWrite(ma2, HIGH);
digitalWrite(mb1, HIGH); // ต้องมีการ test ค่าความเร็ว
analogWrite(mb2, LOW); //ต้องมีการ test ค่าความเร็ว
}
void testMoveright(){
digitalWrite(ma1, LOW);
analogWrite(ma2, HIGH);
digitalWrite(mb1, HIGH); // ต้องมีการ test ค่าความเร็ว
analogWrite(mb2, LOW); //ต้องมีการ test ค่าความเร็ว
}
void testBreak(){
digitalWrite(ma1, HIGH);
analogWrite(ma2, HIGH);
digitalWrite(mb1, HIGH);
analogWrite(mb2, HIGH);
}
void testStop(){
digitalWrite(ma1,LOW);
analogWrite(ma2, LOW);
digitalWrite(mb1, LOW);
analogWrite(mb2, LOW);
}
| true |
64c7a336e8a1b4c86bca6ffb5939f784ede00b79 | C++ | sahil901/BTP200 | /WS03/in-lab/CRA_Account.h | UTF-8 | 721 | 2.671875 | 3 | [] | no_license | /*
Name: Sahil Patel
Seneca Student ID: 159-065-176
Seneca Email: spatel392@myseneca.ca
Date of completion: Summer 2019
Prof Name: Reid Kerr & Nargis Khan
Class Section: NAA
Decleration: I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments.
*/
#ifndef _sict_CRA_ACCOUNT_H
#define _sict_CRA_ACCOUNT_H
namespace sict {
const int max_name_length = 40;
const int min_sin = 100000000;
const int max_sin = 999999999;
class CRA_Account {
char m_familyName[max_name_length];
char m_givenName[max_name_length];
int m_sin;
public:
void set(const char* familyName, const char* givenName, int sin);
bool isEmpty() const;
void display() const;
};
}
#endif | true |
926bb89de28edd3fc6ab3251ad4295665620fa03 | C++ | valentineoradiegwu/HelloWorld | /functions.cpp | WINDOWS-1252 | 36,497 | 3.15625 | 3 | [] | no_license | #include "functions.h"
#include <map>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <limits.h>
#include <algorithm>
#include <typeinfo>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <sstream>
#include <memory>
#include <functional>
std::vector<int> LeetTwoSum(const std::vector<int>& numbers, int target)
{
std::vector<int> res{};
for (int i = 0; i < numbers.size(); ++i)
{
for (int j = i + 1; j < numbers.size(); ++j)
{
if ((numbers[i] + numbers[j]) == target)
{
//why not return at this point?
return res = { i, j };
}
}
}
return res;
}
std::vector<int> LeetTwoSum2(const std::vector<int>& numbers, int target)
{
std::map<int, int> entries;
std::map<int, int>::iterator item;
std::vector<int> res{};
for (int i = 0; i < numbers.size(); ++i)
{
auto diff = target - numbers[i];
item = entries.find(diff);
if (item != entries.end())
{
return res = { item->second, i};
}
entries.insert({ numbers[i], i});
}
return res;
}
std::vector<int> LeetTwoSumSorted(const std::vector<int>& numbers, int target)
{
int low = 0;
int high = numbers.size() - 1;
std::vector<int> res{};
while (low < high)
{
int sum = numbers[low] + numbers[high];
if (sum > target)
--high;
else if (sum < target)
++low;
else
return {low, high};
}
return res;
}
//The solution makes allowance for overflow in the 2 operations
int LeetReverseInt(int input)
{
int res = 0;
int a, b, c;
while (input)
{
a = (res * 10);
if (a / 10 != res)
return 0;
//std::cout << "res = " << res << ". multiple = " << a << std::endl;
b = (input % 10);
c = a + b;
if ((c - a) != b)
return 0;
res = a + b;
input /= 10;
}
return res;
}
int LeetAtoi(const std::string& input)
{
int res = 0;
for (auto i = input.begin(); i != input.end(); ++i)
{
res = res * 10 + (*i - '0');
}
return res;
}
bool LeetIsPalindrome(int x)
{
int copy = x;
int reversed = 0;
int rhs, lhs;
while (copy)
{
rhs = reversed * 10;
if (rhs / 10 != reversed)
return false;
lhs = copy % 10;
reversed = rhs + lhs;
if (reversed - rhs != lhs)
return false;
copy = copy / 10;
}
return x == reversed;
}
bool LeetIsPalindrome(const std::string& in)
{
auto start = in.begin();
auto end = in.end() - 1;
while (start < end)
{
if (*start != *end)
return false;
++start;
--end;
}
return true;
}
int LeetLongestSubstring(const std::string& s)
{
int i = 0;
int j = 0;
int max = 0;
std::set<char> unique{};
/*
1. Keep i and walk with j until u find a char u have seen before and add to set as u go along
2. If u find a repeating char, increment i, remove i from set.
*/
while (j < s.size())
{
if (unique.find(s[j]) == unique.end())
{
unique.insert(s[j]);
++j;
max = std::max(max, j - i);
}
else
{
//Need to move i until we get to just beyond the repeating char.
unique.erase(s[i]);
++i;
}
}
return max;
}
int FindMaxLengthValidParenthesis(const std::string& input)
{
std::stack<int> stk{};
stk.push(-1);
int res = 0;
for (int i = 0; i < input.size(); ++i)
{
if (input[i] == '(')
stk.push(i);
else
{
stk.pop();
if (!stk.empty())
res = std::max(res, i - stk.top());
else
stk.push(i);
}
}
return res;
}
int firstRepeatingInteger(const std::vector<int>& input)
{
std::unordered_set<int> unique{};
for (auto i : input)
{
auto result = unique.insert(i);
if (!result.second)
return i;
}
assert(false);
}
/*
You are given a pointer/reference to a node to be deleted in a linked list of size N. The task is to delete the node. Pointer/reference to head node is not given.
You may assume that the node to be deleted is not the last node.
*/
void deleteNode(ListNode *node)
{
ListNode* next = node->next;
node->data = next->data;
node->next = next->next;
delete next;
}
/*
Number of subsequences of the form a^i b^j c^k
Given a string, count number of subsequences of the form aibjck, i.e., it consists of i a characters, followed by j b characters, followed by k c characters where i >= 1, j >=1 and k >= 1.
Note: Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.
Expected Time Complexity : O(n)
*/
int countSubsequences(const std::string& input)
{
int acount = 0, bcount = 0, ccount = 0;
for (auto eachchar : input)
{
if (eachchar == 'a')
acount = 1 + (2 * acount);
if (eachchar == 'b')
bcount = acount + (2 * bcount);
if (eachchar == 'c')
ccount = bcount + (2 * ccount);
}
return ccount;
}
/*
1. To rotate an array by an offset, you want to start from the offset and wrap around
2. You probably want to add an optimization. If the offset to rotate by a multiple of the size,
just bail out.
*/
std::vector<int> rotateArray(const std::vector<int>& input, int step) {
if (step % input.size() == 0)
return input;
std::vector<int> ret;
ret.reserve(input.size());
for (int i = 0; i < input.size(); i++)
ret.push_back(input[(i + step) % input.size()]);
return ret;
}
//What will be your base case bruv?
int searchNumOccurrenceR(const std::vector<int>& input, int k, int start, int end)
{
if (start > end) return 0;
int mid = start + (end - start) / 2;
if (input[mid] < k) return searchNumOccurrenceR(input, k, mid + 1, end);
else if (input[mid] > k) return searchNumOccurrenceR(input, k, start, mid - 1);
else return searchNumOccurrenceR(input, k, start, mid - 1) + 1 + searchNumOccurrenceR(input, k, mid + 1, end);
}
//In place?
//An optimisation would be to check the last value. if it is less than than 9
//add 1 to it and return.
void addOneToVector(std::vector<int>& input)
{
if (input.empty())
return;
auto nonZero = input.begin();
for (auto i = input.begin(); i != input.end(); ++i)
{
if (*i != 0)
{
nonZero = i;
break;
}
}
if (nonZero != input.begin())
input.erase(input.begin(), nonZero);
int carry = 0;
int add = 1;
auto last = input.rbegin();
if (*last < 9)
{
*last += add;
return;
}
for (auto i = input.rbegin(); i != input.rend(); ++i)
{
int sum = *i + add + carry;
carry = sum / 10;
*i = sum % 10;
add = 0;
}
if (carry)
input.insert(input.begin(), carry);
return;
}
int coverPoints(const std::vector<int>& A, const std::vector<int>& B) {
int count = 0;
if (A.empty() || B.empty())
return count;
int currX = A[0];
int currY = B[0];
for (int i = 1; i < A.size(); ++i)
{
int nextX = A[i];
int nextY = B[i];
count += std::max(std::abs(nextX - currX), std::abs(nextY - currY));
currX = nextX;
currY = nextY;
}
return count;
}
//{ -1, 0, 1, 2, -1, -4 }
std::vector<std::vector<int> > LeetThreeSum(std::vector<int>& nums)
{
std::vector<std::vector<int> > res{};
if (nums.size() < 3)
return res;
std::sort(nums.begin(), nums.end());
auto const size = nums.size();
for (int i = 0; i < nums.size() - 2; ++i)
{
if (i > 0 && nums[i] == nums[i - 1])
continue;
auto low = i + 1;
auto high = size - 1;
auto two_sum_target = 0 - nums[i];
while (low < high)
{
auto sum = nums[low] + nums[high];
if (sum == two_sum_target)
{
std::vector<int> aResult{ nums[i], nums[low], nums[high] };
res.push_back(aResult);
++low;
--high;
while (low < high && nums[low] == nums[low - 1])
++low;
while (low < high && nums[high] == nums[high + 1])
--high;
}
else if (sum < two_sum_target)
++low;
else
--high;
}
}
return res;
}
//right appears redundant. Can be substituted by i
std::pair<int, int> FindLargestIncreasingSubSequence(const std::vector<int>& input)
{
if (input.empty())
return{ 0, 0 };
int left = 0;
int right = 0;
int leftMax = 0;
int rightMax = 0;
for (auto i = 1; i < input.size(); ++i)
{
if (input[i] > input[i - 1])
{
right = i;
if ((right - left + 1) > (rightMax - leftMax + 1))
{
leftMax = left;
rightMax = right;
}
}
else
{
left = i;
}
}
return { leftMax, rightMax };
}
std::vector<std::pair<int, int>> twoSumSortedAllMatches(const std::vector<int>& nums, int target)
{
std::vector<std::pair<int, int>> res{};
if (nums.empty())
return res;
auto low = 0;
auto high = nums.size() - 1;
while (low < high)
{
//Take care of non-uniques
//An alternative is to use 2 extra while loops to advance low and high thereby exhausting
//the duplicates
const auto isLowSameAsPrev = low > 0 && nums[low] == nums[low - 1];
const auto isHighSameAsPrev = high < nums.size() - 1 && nums[high] == nums[high + 1];
if (isLowSameAsPrev || isHighSameAsPrev)
{
if (isLowSameAsPrev)
{
++low;
}
if (isHighSameAsPrev)
{
--high;
}
continue;
}
auto sum = nums[low] + nums[high];
if (sum == target)
{
res.push_back({ low, high });
++low;
--high;
}
else if (sum > target)
--high;
else
++low;
}
return res;
}
int LeetsubarraySum(std::vector<int>& nums, int k)
{
auto res = 0;
auto sum = 0;
std::unordered_map<int, int> prevSums;
for (auto i : nums)
{
sum += i;
if (sum == k)
++res;
if (prevSums.find(sum - k) != prevSums.end())
res += prevSums[sum - k];
prevSums[sum]++;
}
return res;
}
/*
There are probably 2 ways to play this.
1. We store the sum at each index against its index in a map. Only store if we are seing for first time since we want the maximum length so the more left the better
2. During each iter we check if the current sum minus k already exists. If it does we have a subarray then move to 3.
3. check the difference btw current index and index stored against its compliment
During
*/
int LeetMaximumSubarraySum(std::vector<int>& nums, int k)
{
auto maxLength = 0;
auto sum = 0;
std::unordered_map<int, int> prevSums;
prevSums.insert({ sum, -1 });
for (auto i = 0; i < nums.size(); ++i)
{
sum += nums[i];
auto complement = prevSums.find(sum - k);
if (complement != prevSums.end())
maxLength = std::max(maxLength, i - complement->second);
prevSums.insert({sum, i});
}
return maxLength;
}
/*
You are given an array A containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct.
You need to find the other two numbers and print them in ascending order.
*/
void PrintDistinctNumbersWithPairs(std::vector<int>& nums)
{
std::map<int, int> freqs;
for (int i : nums)
{
freqs[i]++;
}
for (auto& iter : freqs)
{
if (iter.second == 1)
std::cout << iter.first << std::endl;
}
}
void PrintDistinctNumbersWithPairs1(std::vector<int>& nums)
{
std::sort(nums.begin(), nums.end());
auto begin = nums.begin();
while (begin < nums.end())
{
auto next = begin + 1;
if (next == nums.end() || *begin != *next)
{
//If next is end then begin is the last element
//If next is not equal to current then we are a solitary element.
std::cout << *begin << std::endl;
++begin;
}
else
{
begin += 2;
}
}
}
void reverseFunc(char* input)
{
size_t len = strlen(input);
if (len)
{
char* start = input;
char* end = input + len - 1;
for (; start < end; ++start, --end)
{
char temp = *start;
*start = *end;
*end = temp;
}
}
}
void reverse(char* input, char* end)
{
if (!input)
return;
char* start = input;
for (; start < end; ++start, --end)
{
std::swap(*start, *end);
}
}
void reverseWords(char* input)
{
auto len = strlen(input);
reverse(input, input + len - 1);
char* left = input;
char* right = input;
char* end = input + len;
for (; right <= end; ++right)
{
if (*right == ' ' || *right == '\0')
{
reverse(left, right - 1);
left = right + 1;
}
}
}
int Factorial(int i)
{
if (i == 1)
{
return 1;
}
else
{
return i * Factorial(i - 1);
}
}
size_t CountBitsInInt(int input)
{
size_t count = 0;
while (input > 0)
{
if ((input & 1) == 1) ++count;
input >>= 1;
}
return count;
}
bool unique_chars(const char* input)
{
bool chars[256] = { false };
for (const char* i = input; *i != '\0'; ++i)
{
if (chars[*i])
return false;
chars[*i] = true;
}
return true;
}
bool unique_chars2(const char* input)
{
const char* head = input;
for(const char* i = ++input; *i; ++i)
{
for (const char* j = head; j != i; ++j)
if (*j == *i)
return false;
}
return true;
}
//This doesnt preserve the original ordering
//Basically ensures that the remaining is a set and in a set positioning is irrelevant
void remove_dupes(char* input)
{
size_t len = strlen(input);
char* tail = input + len - 1;
for (char* i = input; i <= tail; ++i)
{
for (char* j = i + 1; j <= tail; )
{
if (*i == *j)
{
*j = *tail;
--tail;
}
else
{
++j;
}
}
}
*(++tail) = '\0';
}
//Having an extra array for the algo means that it basically simplifies to a std::remove_if
void remove_dupes2(char* input)
{
bool seen[256] = { false };
char* tail = input;
for (char* i = input; *i; ++i)
{
if (!seen[*i])
{
*tail = *i;
++tail;
seen[*i] = true;
}
}
*tail = '\0';
}
void remove_dupes3(char* input)
{
char* tail = input + 1;
for (char* i = input + 1; *i; ++i)
{
char* j = input;
for (; j != tail; ++j)
{
if (*j == *i) break;
}
if (j == tail)
{
*tail = *i;
++tail;
}
}
*tail = '\0';
}
/*
ANagrams
1. Sort the 2 strings and compare the strings fr equality. If equal, then they are anagrams.
2. Build a map of chars to occurences in first string. Then decrease the occurences in second string and the map should have all zeros if an anagram.
3. SImilar to (2) but rather than comparing the map of chars to occurences to be all 0's, we can also track a count of chars and that should be 0 at end of second string.
*/
bool are_anagrams(const char* input1, const char* input2)
{
if (strlen(input1) != strlen(input2))
return false;
int letters[256] = { 0 };
int unique_chars = 0;
for (const char* i = input1; *i; ++i)
{
if (!letters[*i])
++unique_chars;
++letters[*i];
}
for (const char* i = input2; *i; ++i)
{
if (letters[*i] == 0)
return false;
--letters[*i];
if (letters[*i] == 0)
--unique_chars;
if (unique_chars == 0)
return *(++i) == '\0';
}
return false;
}
bool are_anagrams2(const std::string& one, const std::string& two)
{
if (one.size() != two.size())
return false;
int map[256] = { 0 };
int unique_chars = 0;
for (char eachChar : one)
{
if (map[eachChar] == 0)
++unique_chars;
map[eachChar]++;
}
for (auto i = 0; i < two.size(); ++i)
{
if (map[two[i]] == 0)
return false;
--map[two[i]];
if (map[two[i]] == 0)
--unique_chars;
if (unique_chars == 0)
return (i == two.size() - 1);
}
return false;
}
/*
Given a dictionary of English words, return the set of all words grouped into
set of words that are anagrams.
*/
std::vector<std::vector<std::string>> Anagrams(const std::vector<std::string>& dictionary)
{
std::unordered_map<std::string, std::vector<std::string>> words{};
std::vector<std::vector<std::string>> res{};
for (const auto& eachWord : dictionary)
{
std::string key{ eachWord };
std::sort(key.begin(), key.end());
words[key].push_back(eachWord);
}
for (const auto& pair : words)
{
if (pair.second.size() > 1)
res.push_back(pair.second);
}
return res;
}
std::vector<std::string> braces(const std::vector<std::string>& input)
{
const auto len = input.size();
std::vector<std::string> result(len, "NO");
for (auto i = 0; i < len; ++i)
if (is_balanced(input[i]))
result[i] = "YES";
return result;
}
bool is_balanced(const std::string& word)
{
std::stack<char> stk{};
for (char bracket : word)
{
switch (bracket)
{
case '{': stk.push('}'); break;
case '[': stk.push(']'); break;
case '(': stk.push(')'); break;
default:
if (stk.empty() || stk.top() != bracket) { return false; }
stk.pop();
}
}
return stk.empty();
}
//if i am terminating brace then
// If stack is empty return false
// if top of stack is not me return false
// else continue to next char.
bool is_balanced_can_contain_nonbraces(const std::string& word)
{
std::stack<char> stk{};
auto is_terminating_brace = [](char c) {return c == '}' || c == ']' || c == ')'; };
for (char eachChar : word)
{
switch (eachChar)
{
case '{': stk.push('}'); break;
case '[': stk.push(']'); break;
case '(': stk.push(')'); break;
default:
if (is_terminating_brace(eachChar))
{
if (stk.empty() || stk.top() != eachChar)
{
return false;
}
stk.pop();
}
}
}
return stk.empty();
}
/*
pattern = 08??840
0804840
0813840
0822840
0831840
0840840
*/
std::vector<std::vector<int>> Permutations(int hrs_outstanding, int day_hours, std::vector<int> index_for_missing_days)
{
int missing_days = index_for_missing_days.size();
//Generate permutations from 0 to day_hours of size missing_days
std::vector<int> range(day_hours + 1);
for (int i = 0; i < range.size(); ++i)
range[i] = i;
std::vector<std::vector<int>> permutations{};
//Some high school permutation computations. I had to look this up on the internet
//as its being quite a while I did it last.
int no_of_permutations = std::pow(range.size(), index_for_missing_days.size());
for (int i = 0; i < no_of_permutations; ++i)
{
std::vector<int> permutation{};
for (int j = 0; j < index_for_missing_days.size(); ++j)
{
int selector = static_cast<int>(i / std::pow(range.size(), j)) % range.size();
permutation.push_back(range[selector]);
}
permutations.push_back(std::move(permutation));
}
//Filter off permutations which do not tally up to the outstanding hours.
permutations.erase(std::remove_if(permutations.begin(),
permutations.end(),
[hrs_outstanding](const std::vector<int>& x) {return std::accumulate(x.begin(), x.end(), 0) != hrs_outstanding; }), permutations.end());
return permutations;
}
std::vector<std::string> findSchedules(int work_hours, int day_hours, const std::string& pattern)
{
int total_hours_in_pattern = 0;
std::vector<int> index_for_missing_days{};
for (int i = 0; i < pattern.size(); ++i)
{
if (pattern[i] == '?')
index_for_missing_days.push_back(i);
else
total_hours_in_pattern += pattern[i] - '0';
}
int hrs_outstanding = work_hours - total_hours_in_pattern;
auto permutations = Permutations(hrs_outstanding, day_hours, index_for_missing_days);
std::vector<std::string> res{};
//We need to interpolate the hrs from the permutation into the ? in schedule
//We know the indexes where the ? are in the schedule since we stored them in index_for_missing_days
for (const auto & permutation : permutations)
{
std::string schedule{ pattern };
for (int i = 0; i < permutation.size(); ++i)
{
int time = permutation[i];
schedule[index_for_missing_days[i]] = '0' + time;
}
res.push_back(schedule);
}
//Is there a way to ensure the algo in Permutations guarantees its results in sorted order
//and therefore make the nlogn sort unnecessary?
std::sort(res.begin(), res.end());
return res;
}
std::map<int, int> coinChange(std::vector<int>& denominations, int amount)
{
std::map<int, int> res{};
int pendingAmount = amount;
//The denominations need to be sorted in reverse
//This also has to be a set i.e no dupes
std::sort(denominations.rbegin(), denominations.rend());
for (auto denomination : denominations)
{
if (denomination > pendingAmount)
continue;
//multiples is guaranteed to be at least 1 here
int multiples = pendingAmount / denomination;
res.insert({denomination, multiples});
pendingAmount = pendingAmount - (multiples * denomination);
if (pendingAmount == 0)
return res;
}
throw std::invalid_argument{"Could not find complete change for the amount " + amount};
}
std::string replaceSpaceWithEncoding(char* input)
{
int spaceCount = 0;
for (char* i = input; *i; ++i)
{
if (*i == ' ')
++spaceCount;
}
const int length = strlen(input);
const int newLength = length + (spaceCount * 2);
char* newString = new char [newLength];
//auto newString = std::make_unique<char[]>(newLength);
newString[newLength] = '\0';
char* lastElement = input + (length - 1);
char* lastElementNew = newString + (newLength - 1);
for (char* i = lastElement; i >= input; --i)
{
if (*i == ' ')
{
*lastElementNew = '0';
--lastElementNew;
*lastElementNew = '2';
--lastElementNew;
*lastElementNew = '%';
--lastElementNew;
}
else
{
*lastElementNew = *i;
--lastElementNew;
}
}
auto res = std::string(newString);
//delete[] newString;
return res;
}
/*
1. Traverse the 2 dim array recording every row or column that has a 0.
2. Traverse the 2 dim array again and if a cell falls in a row or column with a zero, set it to 0.
*/
void setZeros(int matrix[4][4])
{
//constexpr int rows = sizeof matrix / sizeof matrix[0];
//constexpr int cols = std::extent<decltype(matrix), 1>::value;
int rows_with_zeros[4] = { 1 };
int columns_with_zeros[4] = { 1 };
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
if (matrix[i][j] == 0)
{
rows_with_zeros[i] = 0;
columns_with_zeros[j] = 0;
}
}
}
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
if (rows_with_zeros[i] == 0 || columns_with_zeros[j] == 0)
{
matrix[i][j] = 0;
}
}
}
}
int myStrCmp(const char* input1, const char* input2)
{
while (*input1)
{
if (!*input2)
return 1;
if (*input2 < *input1)
return 1;
if (*input1 < *input2)
return -1;
++input1;
++input2;
}
if (*input2)
return -1;
return 0;
}
// If the string is boomboomboomd, will your algorithm return true for a substring boomboomd? It does but may be suboptimal.
// The Boyer-Moore string search algo appears to be the fastest theoretically.
bool is_substr(const char* input1, const char* input2)
{
//obviously u should check if the length ofsubstring satisfies a few considerations
//this code may be easier if i used strlen but trying to avoid that cost.
for (const char* i = input2; *i; ++i)
{
if (*i == *input1)
{
const char* sub = input1 + 1;
const char* super = i + 1;
while (*sub)
{
if (!*super)
return false;
if (*sub != *super)
break;
++sub;
++super;
}
if (!*sub)
return true;
}
}
return false;
}
int BinSearchArray(int input[], int length, int key)
{
int low = 0;
int high = length - 1;
while (low <= high)
{
int middle = low + (high - low) / 2;
if (input[middle] == key)
return middle;
else if (input[middle] < key)
low = middle + 1;
else
high = middle - 1;
}
return -1;
}
int BinSearchArrayRecurseImpl(int input[], int low, int high, int key)
{
if (high < low)
return -1;
auto mid = low + (high - low) / 2;
if (input[mid] == key)
return mid;
else if (input[mid] < key)
return BinSearchArrayRecurseImpl(input, mid + 1, high, key);
return BinSearchArrayRecurseImpl(input, low, mid - 1, key);
}
int BinSearchArrayRecurse(int input[], int length, int key)
{
return BinSearchArrayRecurseImpl(input, 0, length - 1, key);
}
//Assume input is unbounded and infinite
//Can be applied to infinite sorted streams
int InterpolatedSearch(int input[], int key)
{
auto low = 0;
auto high = 1;
while (input[high] < key)
{
low = high;
high = low * 2;
}
return BinSearchArrayRecurseImpl(input, low, high, key);
}
// 1. If we find a match at mid and the previous field is not equal to us, then we are the first occurence. Return index.
// 2. If we find a match but the prev field is equal to us, then we treat as if the mid point is greater so we move high left.
// 1, 2, 3, 3, 3, 3, 4
int binSearchFirstOccurence(const std::vector<int>& input, int key)
{
int low = 0;
int high = input.size() - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (input[mid] == key && (mid == 0 || input[mid - 1] != input[mid]))
return mid;
else if (input[mid] >= key)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
int binSearchFirstOccurence2(const std::vector<int>& input, int key)
{
int low = 0;
int high = input.size() - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (input[mid] > key)
high = mid - 1;
else if (input[mid] < key)
low = mid + 1;
else if (low != mid)
high = mid;
else
return low;
}
return - 1;
}
int BinFindFirstLargerThanK(const std::vector<int>& input, int key)
{
int left = 0;
int right = input.size() - 1;
while (left != right)
{
int mid = left + (right - left) / 2;
if (input[mid] <= key)
left = mid + 1;
else
right = mid;
}
return left == input.size() ? -1 : left;
}
int IndexEqualToElement(const std::vector<int>& input)
{
int low = 0;
int high = input.size() - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (input[mid] == mid)
return mid;
else if (input[mid] < mid)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int UtopianTree(int cycles)
{
int height = 1;
for (int i = 1; i <= cycles; ++i)
{
if (i % 2 == 0)
{
height = height + 1;
}
else
{
height = 2 * height;
}
}
return height;
}
std::string MergeStrings(const std::vector<std::string>& iInput)
{
char myArray[26] = { 0 };
for (auto& eachString : iInput)
{
for (auto eachChar : eachString)
{
myArray[eachChar - 'a']++;
}
}
std::string result;
for (int i = 0; i < 26; ++i)
{
if (myArray[i] > 0)
result.append(myArray[i], 'a' + i);
}
return result;
}
bool operator<(const QueueItem & lhs, const QueueItem & rhs)
{
return lhs.value < rhs.value;
}
std::vector<int> mergeKLists(const std::vector<std::vector<int>>& lists)
{
std::priority_queue<QueueItem> queue{};
int total = 0;
for (int i = 0; i < lists.size(); ++i)
{
QueueItem item{ lists[i][0], i, 0 };
queue.push(item);
total += lists[i].size();
}
std::vector<int> results{};
results.reserve(total);
while (!queue.empty())
{
auto top = queue.top();
results.push_back(top.value);
queue.pop();
auto next = top.item_idx + 1;
if (next < lists[top.list_idx].size())
{
QueueItem item{ lists[top.list_idx][next], top.list_idx, next };
queue.push(item);
}
}
return results;
}
int myAtoi(std::string str)
{
int res = 0;
int sign = 1;
bool seen_first_non_whitespace = false;
for (auto character : str)
{
if (character == ' ' && !seen_first_non_whitespace)
{
continue;
}
if (!seen_first_non_whitespace)
{
seen_first_non_whitespace = true;
if (character == '-' || character == '+')
{
if (character == '-')
sign = -1;
continue;
}
}
if (character < '0' || character > '9')
break;
res = (res * 10) + (character - '0');
}
return sign * res;
}
std::vector<std::string> stringToVector(const std::string& input)
{
std::vector<std::string> strings;
std::istringstream f{input};
std::string each_token;
while (getline(f, each_token, ' ')) {
std::cout << each_token << std::endl;
strings.push_back(each_token);
}
return strings;
}
bool IsSentenceInString(const std::string& ransom, const std::string& dictionary)
{
auto ransom_words = stringToVector(ransom);
auto dictionary_words = stringToVector(dictionary);
std::map<const std::string, int> freq;
for (auto& word : dictionary_words)
{
++freq[word];
}
for (auto& word : ransom_words)
{
if (freq.find(word) == freq.end() || freq[word] == 0)
return false;
else
--freq[word];
}
return true;
}
//This is done in a character by character basis rather than a word by word basis as above.
bool IsSentenceInString2(const std::string& letter, const std::string& magazine)
{
int chars[256] = { 0 };
for (auto c : magazine)
++chars[c];
for (auto c : letter)
{
if (chars[c] > 0)
{
--chars[c];
}
else
return false;
}
return true;
}
//You need to know how hash maps work out the index to store a key to understand this solution
//There are a few variations to the problem and one is to find the smallest +ve number. I think we
//will go for that.
int missing_integer(std::vector<int> input)
{
std::vector<int> bitVector(input.size() + 1);
for (auto i : input)
{
if(i > 0)
bitVector[i % (input.size() + 1)] = 1;
}
for (auto i = 0; i < bitVector.size(); ++i)
{
if (bitVector[i] == 0)
return i;
}
return -1;
}
//Runs in linear time
int fib(int n)
{
if (n <= 2)
return 1;
int prev = 1;
int curr = 1;
for (int i = 3; i <= n; ++i)
{
int tmp = prev + curr;
prev = curr;
curr = tmp;
}
return curr;
}
//Runs in exponential time
int fibr(int n)
{
if (n <= 2)
return 1;
return fibr(n - 1) + fibr(n - 2);
}
//Contrived example showing what Dynamic Programming is all about
//cache previously computed solutions to subproblems to use when encountered again
int fibDP(int n)
{
if (n <= 2)
return 1;
std::unordered_map<int, int> memo{};
int res = 0;
for (int i = 1; i <= n; ++i)
{
if (i <= 2)
{
memo[i] = 1;
}
else
{
res = memo[i - 1] + memo[i - 2];
memo[i] = res;
}
}
return res;
}
int squareRoot(int input)
{
int i = 1;
int res = i * i;
while (res <= input)
{
++i;
res = i * i;
}
return i - 1;
}
int squareRoot2(int input)
{
int low = 0;
int high = input;
int res;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (mid * mid == input)
{
return mid;
}
else if (mid * mid > input)
{
high = mid - 1;
}
else
{
low = mid + 1;
res = mid;
}
}
return res;
}
// When subtracting from a size_t, u have to be careful.
// 0 - 1 where 0 is held in size_t results in a very large int and not -1
// Becareful with your use of auto as a variable maybe declared size_t without u knowing.
std::string multiplyStrings(const std::string& first, const std::string& second)
{
const auto sizeFirst = first.size();
const auto sizeSecond = second.size();
std::string result( sizeFirst + sizeSecond , '0');
for (int i = sizeFirst - 1; i >= 0; --i)
{
int carry = 0;
for (int j = sizeSecond - 1; j >= 0; --j)
{
const int idx = i + j + 1;
int mult = (first[i] - '0') * (second[j] - '0') + carry + (result[idx] - '0');
result[idx] = mult % 10 + '0';
carry = mult / 10;
}
result[i] += carry;
}
const auto startpos = result.find_first_not_of("0");
if (std::string::npos != startpos)
return result.substr(startpos);
return "0";
}
/*
Sum(Natural numbers) = Sum(given numbers) - A + B
Sum_squares(Natural numbers) = Sum_squares(given numbers) - A*A + B*B
where :
Sum of n Natural numbers is given by : n(n+1)/2
PROOF:
The sum can be represented in 2 ways
sum = 1 + 2 + 3 + ...+ (n -2) + (n - 1) + (n)
sum = n + (n-1) + (n -2) + ... + 3 + 2 + 1
Adding these 2, we have
2sum = (n + 1) + (n + 1) + (n + 1) + ... + (n + 1) + (n + 1) + (n + 1)
2sum = n(n + 1)
sum = n(n + 1) / 2
Sum of squares of n Natural numbers is given by : n((n+1)/2)((2n+1)/3)
Also note that B^2 - A^2 = (B-A) * (B+A)
*/
std::vector<int> repeatedAndDuplicateNumber(const std::vector<int>& input)
{
std::vector<int> res(2);
if (input.empty())
return res;
int missing_num = 0;
int repeated_num = 0;
long x = input.size();
long sum_of_num = 0;
long sum_of_squares = 0;
long sum_of_num_actual = (x*(x + 1)) / 2;
long sum_of_squares_actual = ((x)*(x + 1)*(2 * x + 1)) / 6;
for (long elem : input)
{
sum_of_num += elem;
sum_of_squares += elem*elem;
}
missing_num = (((sum_of_squares_actual - sum_of_squares) / (sum_of_num_actual - sum_of_num))
+ (sum_of_num_actual - sum_of_num)) / 2;
repeated_num = (((sum_of_squares_actual - sum_of_squares) / (sum_of_num_actual - sum_of_num))
- (sum_of_num_actual - sum_of_num)) / 2;
res[0] = repeated_num;
res[1] = missing_num;
return res;
}
std::vector<std::pair<int, int>> mergeInterval(std::vector<std::pair<int, int>>& intervals)
{
std::vector<std::pair<int, int>> res{};
if (intervals.empty())
return res;
std::sort(intervals.begin(), intervals.end());
res.push_back(intervals.front());
for (int i = 1; i < intervals.size(); ++i)
{
auto& curr_interval = intervals[i];
auto& prev_interval = res.back();
auto are_consecutive_intervals_overlapping = curr_interval.first <= prev_interval.second;
if (are_consecutive_intervals_overlapping)
{
prev_interval.second = std::max(prev_interval.second, curr_interval.second);
}
else
{
res.push_back(curr_interval);
}
}
return res;
}
//Already sorted and non-overlapping
std::vector<std::pair<int, int>> insertAndMergeInterval(std::vector<std::pair<int, int>>& intervals, std::pair<int, int> newInterval)
{
std::vector<std::pair<int, int>> res{};
if (intervals.empty())
{
res.push_back(newInterval);
return res;
}
auto newInserted = false;
int start = 1;
auto use_new_interval = !newInserted && newInterval.first < intervals[0].first;
//could be first or newInterval
if (use_new_interval)
{
start = 0;
res.push_back(newInterval);
newInserted = true;
}
else
res.push_back(intervals.front());
for (int i = start; i < intervals.size(); ++i)
{
//curr could be i or newInterval
use_new_interval = !newInserted && newInterval.first < intervals[i].first;
auto& curr_interval = use_new_interval ? newInterval : intervals[i];
auto& prev_interval = res.back();
auto are_consecutive_intervals_overlapping = curr_interval.first < prev_interval.second;
if (are_consecutive_intervals_overlapping)
prev_interval.second = std::max(prev_interval.second, curr_interval.second);
else
res.push_back(curr_interval);
if (use_new_interval)
{
newInserted = true;
--i;
}
if (!newInserted && ((i + 1) == intervals.size()))
{
intervals.push_back(newInterval);
newInserted = true;
}
}
return res;
}
std::vector<std::pair<int, int>> insertAndMergeInterval2(std::vector<std::pair<int, int>>& intervals, std::pair<int, int> newInterval)
{
std::vector<std::pair<int, int>> res{};
for (auto& interval : intervals)
{
if (interval.second < newInterval.first)
res.push_back(interval);
else if (newInterval.second < interval.first)
{
res.push_back(newInterval);
newInterval = interval;
}
else
{
auto start = std::min(newInterval.first, interval.first);
auto end = std::max(newInterval.second, interval.second);
newInterval = {start, end};
}
}
res.push_back(newInterval);
return res;
}
/*
Given a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1) times.
Find an element which is duplicate without using extra space.
Here we encode the presence of a duplicate into the array it self.
If we use the element as index then a duplicate element will touch the same index more than once
3 4 1 4 1
*/
int repeatedNumberModify(std::vector<int>& input)
{
for (auto elem : input)
{
if (input[abs(elem)] >= 0)
{
input[abs(elem)] = -input[abs(elem)];
}
else
{
return abs(elem);
}
}
return -1;
}
/*
1. A number XORed by itself is 0
2. Any number XORed by 0 yields the number
*/
int findSingleNumber(const std::vector<int>& input)
{
int res = 0;
for (int i : input)
res ^= i;
return res;
}
void partition(std::vector<int>& array)
{
auto pivot = array[array.size() - 1];
auto partition = 0;
for (int i = 0; i < array.size() - 1; ++i)
{
if (array[i] <= pivot)
{
std::swap(array[i], array[partition]);
++partition;
}
}
std::swap(array[partition], array[array.size() - 1]);
}
//https://www.youtube.com/watch?v=E6us4nmXTHs
int LongestIncreasingSubsequence(const std::vector<int>& input)
{
if (input.empty())
return 0;
std::vector<int> result(input.size(), 1);
for (int i = 1; i < input.size(); ++i)
{
int j = 0;
while (j < i)
{
if (input[j] < input[i])
{
result[i] = std::max(result[i], result[j] + 1);
}
++j;
}
}
int max = result[0];
for (auto i : result)
{
if (i > max)
max = i;
}
return max;
}
bool checkEquivalentKeypresses(const std::string& one, const std::string& two)
{
return applyBackspaces(one) == applyBackspaces(two);
}
std::string applyBackspaces(const std::string& input)
{
std::string res;
res.reserve(input.size());
for (auto eachChar : input)
{
if (eachChar == ',') continue;
if (eachChar == '-') continue;
auto is_back_space = false;
if (eachChar == 'B')
{
is_back_space = true;
}
if (!is_back_space)
res.push_back(eachChar);
else
{
if (!res.empty())
res.pop_back();
}
}
return res;
}
template <typename T>
std::string getType(const T& arg)
{
const std::type_info& ti = typeid(arg);
return ti.name();
}
template std::string getType<int>(const int& arg); | true |
8d33ce5ba841052a485434456c23510ef6045d78 | C++ | spoonless/glviewer | /src/sys/src/Duration.cpp | UTF-8 | 735 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <chrono>
#include "Duration.hpp"
namespace
{
using clock = std::chrono::steady_clock;
using milliseconds = std::chrono::duration<unsigned long int, std::milli>;
auto beginningOfTime = clock::now();
inline unsigned long getDuration()
{
return std::chrono::duration_cast<milliseconds>(clock::now() - beginningOfTime).count();
}
}
sys::Duration::Duration() : _start(getDuration())
{
}
sys::Duration::Duration(const Duration &duration)
:_start(duration._start)
{
}
sys::Duration& sys::Duration::operator = (const Duration &duration)
{
if (this != &duration)
{
_start = duration._start;
}
return *this;
}
unsigned long sys::Duration::elapsed() const
{
return getDuration() - _start;
}
| true |
0cf2845ea1d7409e9d690f330fee4ab590a0a016 | C++ | vspinu/VSR | /src/mean.cpp | UTF-8 | 1,918 | 2.625 | 3 | [] | no_license | #include <Rcpp.h>
#include <vector>
// #include <boost/math/special_functions/beta.hpp>
// this doesn't work, added export PKG_CXXFLAGS=-std=c++11 to bash
// [[Rcpp::plugins("cpp11")]]
using namespace Rcpp;
using std::vector;
// from: http://stackoverflow.com/a/12399290/453735
vector<size_t> order(const NumericVector &v) {
// initialize original index locations
vector<size_t> idx(v.length());
for (size_t i = 0; i != idx.size(); ++i) idx[i] = i;
// sort indexes based on comparing values in v
sort(idx.begin(), idx.end(),
[&v](size_t i1, size_t i2) {
return v[i1] < v[i2];
});
return idx;
}
// double w_ibeta(double& p, NumericVector& r) {
// return boost::math::ibeta(r[0], r[1], p);
// }
double w_pow(double& p, NumericVector& r){
if(r.length() > 1){
double H = 1 - pow(1 - p, r[1]);
double L = pow(p, r[0]);
return L*p + H*(1 - p);
} else {
return pow(p, r[0]);
}
}
// [[Rcpp::export]]
NumericVector c_rdmean_pow(NumericVector x, NumericVector w, NumericVector p) {
if (x.length() != w.length()){
Rf_error("Input vectors 'x' and 'w' must be of the same length.");
}
double wsum = std::accumulate(w.begin(), w.end(), 0.0);
std::transform(w.begin(), w.end(), w.begin(),
[&wsum](double x) {return x/wsum;});
double out = 0, hacc = 0, lacc = 0;
double pred = 0;
int done = 0;
auto ix = order(x);
for (auto i : ix ){
// Rprintf("%d:%f \n", i, x[i]);
done = 1;
hacc += w[i];
if(!NumericVector::is_na(x[i])){
// order algorithm roughly preserves orders of NA's
// not sure if this is the right approach
out += x[i]*(w_pow(hacc, p) - w_pow(lacc, p));
}
lacc = hacc;
}
if (!done)
out = NA_REAL;
return NumericVector::create(out);
}
// // [[Rcpp::export]]
// int useAuto() {
// auto val = 42; // val will be of type int
// return val;
// }
| true |
1aa924d563b4d5ddf0bf0a206fdf39f4e53c69ee | C++ | bobekjan/edetect | /src/edetect/cpu/CpuEuclideanNormFilter.cxx | UTF-8 | 1,083 | 2.578125 | 3 | [] | no_license | /** @file
* @brief Definition of class CpuEuclideanNormFilter.
*
* @author Jan Bobek
* @since 19th April 2015
*/
#include "edetect.hxx"
#include "IImage.hxx"
#include "cpu/CpuEuclideanNormFilter.hxx"
/*************************************************************************/
/* CpuEuclideanNormFilter */
/*************************************************************************/
CpuEuclideanNormFilter::CpuEuclideanNormFilter(
IImageFilter* first,
IImageFilter* second
)
: IEuclideanNormFilter( first, second )
{
}
void
CpuEuclideanNormFilter::filter2(
IImage& first,
const IImage& second
)
{
for( unsigned int row = 0; row < first.rows(); ++row )
{
float* const dstp =
(float*)(first.data() + row * first.stride());
const float* const srcp =
(const float*)(second.data() + row * second.stride());
for( unsigned int col = 0; col < first.columns(); ++col )
dstp[col] = std::sqrt( srcp[col] * srcp[col] + dstp[col] * dstp[col] );
}
}
| true |
cb935266a3d1851bdd5025c7a0faba6434ccbb7d | C++ | skzr001/Leetcode | /7. Reverse Integer/lc7.cpp | UTF-8 | 869 | 3.796875 | 4 | [] | no_license | /*
It is specified that the intergers is within the 32-bits signed.
So we don't have to consider big numbers.
The solution is rather straightforward. We extract the last digits of given interger, and multiply it 10 one time and add next digit.
For example.
Input:123.
num=3
num=num*10+2=32
num=num*10+1=321
if num exceed 32 digit, return 0
else return num
Corner case
1. Input overflow.
2. Negative integer.
*/
/*
有一个地方我没有考虑到,要用long long来存最终结果.因为int类型最大是2^32-1. 翻转之后的数字很有可能大于这个范围.
最后做类型判断的时候要考虑正负的最大整形
*/
class Solution {
public:
int reverse(int x) {
long long num=0;
while(x){
int digit=x%10;
x/=10;
num=num*10+digit;
}
return (num>INT_MAX||num<INT_MIN)?0:num;
}
}; | true |
c714ea312ec55a0bc294289566aec8c3a0fbce62 | C++ | Voyager2718/Docs | /CPlusPlus_App/_基础学习代码/类模板/Cpp1.cpp | UTF-8 | 430 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
template <typename T>
class Test{
public:
// Test(T a,T b){
// x=a;y=b;}
T x;T y;
T Max(T x,T y);
T Min(T w,T z){
return (w<z)? w:z;
}
friend a(Test&);
};
void f(){
Test<float> b;
cout<<"___________"<<b.x<<" "<<b.y<<endl;
}
template <class T>
T Test<T>::Max(T x,T y){
return (x>y)? x:y;
}
int main(){
Test <float> a;
float b=35.5;
cout<<a.Max(35,b)<<endl;
f();
return 0;
} | true |
c56e4478963cff8ef8bcba5debb6a66725dc167d | C++ | wkdehdlr/Doo-it | /Algorithm/백준/알고리즘 중급/다이나믹 프로그래밍/다이나믹 프로그래밍/BOJ 2193 이친수.cpp | WINDOWS-1252 | 471 | 2.78125 | 3 | [] | no_license | #pragma warning(disable : 4996)
#include<cstdio>
#include<cstring>
int N;
long long dp[91][3];
long long func(int n,int num)
{
//
if (n == 1) {
if (num)return 1;
else return 0;
}
long long& ret = dp[n][num];
if (ret != -1)return ret;
if (num) {
ret = func(n - 1, 0);
}
else {
ret = func(n - 1, 1) + func(n - 1, 0);
}
return ret;
}
int main()
{
memset(dp, -1, sizeof(dp));
scanf("%d", &N);
printf("%lld\n", func(N, 1) + func(N, 0));
} | true |
0df7ed3452c85d00a11c7596b70621cd203a909c | C++ | GiakoumidisStylianos/Linux-terminal-chess | /src/Rook.cpp | UTF-8 | 891 | 3.3125 | 3 | [
"MIT"
] | permissive | #include "Rook.h"
Rook::Rook(int row, int col, int player) : Piece(row, col, player) {
character = player == 1 ? 'R' : 'r';
}
bool Rook::checkMove(int destRow, int destCol) {
// Cannot go to the same cell.
if (row == destRow && col == destCol)
return false;
if (row == destRow || col == destCol)
return true;
return false;
}
bool Rook::checkMove2(int destRow, int destCol, Board& board) {
// Find the direction of the movement.
int dirX = destCol - col > 0 ? 1 : (destCol - col == 0 ? 0 : -1);
int dirY = destRow - row > 0 ? 1 : (destRow - row == 0 ? 0 : -1);
int r = row + dirY;
int c = col + dirX;
while(1) {
Piece* p = board.getPieceAt(r, c);
if (p != NULL) {
if (p->getPlayer() == player)
return false;
else {
return r == destRow && c == destCol;
}
}
if (r == destRow && c == destCol)
return true;
r += dirY;
c += dirX;
}
} | true |
aa46d71df0cbb13e35a3b511c3b08aebdb859bd3 | C++ | tewalds/pentagod | /agentmcts.h | UTF-8 | 8,702 | 2.875 | 3 | [] | no_license |
#pragma once
//A Monte-Carlo Tree Search based player
#include <cmath>
#include <cassert>
#include "time.h"
#include "types.h"
#include "move.h"
#include "board.h"
#include "depthstats.h"
#include "thread.h"
#include "xorshift.h"
#include "compacttree.h"
#include "log.h"
#include "agent.h"
class AgentMCTS : public Agent{
public:
class ExpPair {
uword s, n;
ExpPair(uword S, uword N) : s(S), n(N) { }
public:
ExpPair() : s(0), n(0) { }
float avg() const { return 0.5f*s/n; }
uword num() const { return n; }
uword sum() const { return s/2; }
void clear() { s = 0; n = 0; }
void addvloss(){ INCR(n); }
void addvtie() { INCR(s); }
void addvwin() { PLUS(s, 2); }
void addv(const ExpPair & a){
if(a.s) PLUS(s, a.s);
if(a.n) PLUS(n, a.n);
}
void addloss(){ n++; }
void addtie() { s++; }
void addwin() { s += 2; }
void add(const ExpPair & a){
s += a.s;
n += a.n;
}
void addwins(uword num) { n += num; s += 2*num; }
void addlosses(uword num){ n += num; }
ExpPair & operator+=(const ExpPair & a){
s += a.s;
n += a.n;
return *this;
}
ExpPair operator + (const ExpPair & a){
return ExpPair(s + a.s, n + a.n);
}
ExpPair & operator*=(uword m){
s *= m;
n *= m;
return *this;
}
ExpPair invert(){ //return it from the other player's perspective
return ExpPair(n*2 - s, n);
}
};
struct Node {
public:
ExpPair exp;
int16_t know;
int8_t outcome;
uint8_t proofdepth;
Move move;
Move bestmove; //if outcome is set, then bestmove is the way to get there
CompactTree<Node>::Children children;
// int padding;
//seems to need padding to multiples of 8 bytes or it segfaults?
//don't forget to update the copy constructor/operator
Node() : know(0), outcome(-3), proofdepth(0) { }
Node(const Move & m, char o = -3) : know(0), outcome( o), proofdepth(0), move(m) { }
Node(const Node & n) { *this = n; }
Node & operator = (const Node & n){
if(this != & n){ //don't copy to self
//don't copy to a node that already has children
assert(children.empty());
exp = n.exp;
know = n.know;
move = n.move;
bestmove = n.bestmove;
outcome = n.outcome;
proofdepth = n.proofdepth;
//children = n.children; ignore the children, they need to be swap_tree'd in
}
return *this;
}
void swap_tree(Node & n){
children.swap(n.children);
}
void print() const {
printf("%s\n", to_s().c_str());
}
string to_s() const {
return "Node: move " + move.to_s() +
", exp " + to_str(exp.avg(), 2) + "/" + to_str(exp.num()) +
", know " + to_str(know) +
", outcome " + to_str((int)outcome) + "/" + to_str((int)proofdepth) +
", best " + bestmove.to_s() +
", children " + to_str(children.num());
}
unsigned int size() const {
unsigned int num = children.num();
if(children.num())
for(Node * i = children.begin(); i != children.end(); i++)
num += i->size();
return num;
}
~Node(){
assert(children.empty());
}
unsigned int alloc(unsigned int num, CompactTree<Node> & ct){
return children.alloc(num, ct);
}
unsigned int dealloc(CompactTree<Node> & ct){
unsigned int num = 0;
if(children.num())
for(Node * i = children.begin(); i != children.end(); i++)
num += i->dealloc(ct);
num += children.dealloc(ct);
return num;
}
float value(bool knowledge, float fpurgency){
float val = fpurgency;
float expnum = exp.num();
if(expnum > 0)
val = exp.avg();
if(knowledge && know != 0){
if(expnum <= 1)
val += 0.01f * know;
else if(expnum < 1000) //knowledge is only useful with little experience
val += 0.01f * know / sqrt(expnum);
}
return val;
}
};
struct MoveList { //intended to be used to track moves for use in rave or similar
ExpPair exp[2]; //aggregated outcomes overall
MoveList() { }
void addtree(const Move & move, char turn){
}
void addrollout(const Move & move, char turn){
}
void reset(Board * b){
exp[0].clear();
exp[1].clear();
}
void finishrollout(int won){
exp[0].addloss();
exp[1].addloss();
if(won == 0){
exp[0].addtie();
exp[1].addtie();
}else{
exp[won-1].addwin();
}
}
void subvlosses(int n){
exp[0].addlosses(-n);
exp[1].addlosses(-n);
}
const ExpPair & getexp(int turn) const {
return exp[turn-1];
}
};
class MCTSThread {
mutable XORShift_uint64 rand64;
mutable XORShift_float unitrand;
Thread thread;
AgentMCTS * player;
bool use_explore; //whether to use exploration for this simulation
MoveList movelist;
int stage; //which of the four MCTS stages is it on
public:
DepthStats treelen, gamelen;
double times[4]; //time spent in each of the stages
Time timestamps[4]; //timestamps for the beginning, before child creation, before rollout, after rollout
MCTSThread(AgentMCTS * p) : rand64(std::rand()), unitrand(std::rand()), player(p) {
reset();
thread(bind(&MCTSThread::run, this));
}
~MCTSThread() { }
void reset(){
treelen.reset();
gamelen.reset();
use_explore = false;
for(int a = 0; a < 4; a++)
times[a] = 0;
}
int join(){ return thread.join(); }
private:
void run(); //thread runner, calls iterate on each iteration
void iterate(); //handles each iteration
void walk_tree(Board & board, Node * node, int depth);
bool create_children(const Board & board, Node * node, int toplay);
void add_knowledge(const Board & board, Node * node, Node * child);
Node * choose_move(const Node * node, int toplay) const;
int rollout(Board & board, Move move, int depth);
// PairMove rollout_choose_move(Board & board, const Move & prev, int & doinstwin, bool checkrings);
};
public:
static const float min_rave;
bool ponder; //think during opponents time?
int numthreads; //number of player threads to run
u64 maxmem; //maximum memory for the tree in bytes
bool profile; //count how long is spent in each stage of MCTS
//tree traversal
bool parentexplore; // whether to multiple exploration by the parents winrate
float explore; //greater than one favours exploration, smaller than one favours exploitation
bool knowledge; //whether to include knowledge
float useexplore; //what probability to use UCT exploration
float fpurgency; //what value to return for a move that hasn't been played yet
int rollouts; //number of rollouts to run after the tree traversal
//tree building
bool keeptree; //reuse the tree from the previous move
int minimax; //solve the minimax tree within the uct tree
uint visitexpand;//number of visits before expanding a node
bool prunesymmetry; //prune symmetric children from the move list, useful for proving but likely not for playing
uint gcsolved; //garbage collect solved nodes or keep them in the tree, assuming they meet the required amount of work
//knowledge
int win_score;
//rollout
int instantwin; //look for instant wins in rollouts
Board rootboard;
Node root;
uword nodes;
int gclimit; //the minimum experience needed to not be garbage collected
uint64_t runs, maxruns;
CompactTree<Node> ctmem;
enum ThreadState {
Thread_Cancelled, //threads should exit
Thread_Wait_Start, //threads are waiting to start
Thread_Wait_Start_Cancelled, //once done waiting, go to cancelled instead of running
Thread_Running, //threads are running
Thread_GC, //one thread is running garbage collection, the rest are waiting
Thread_GC_End, //once done garbage collecting, go to wait_end instead of back to running
Thread_Wait_End, //threads are waiting to end
};
volatile ThreadState threadstate;
vector<MCTSThread *> threads;
Barrier runbarrier, gcbarrier;
double time_used;
AgentMCTS();
~AgentMCTS();
string statestring();
void stop_threads();
void start_threads();
void reset_threads();
void set_memlimit(uint64_t lim) { }; // in bytes
void clear_mem() { };
void set_ponder(bool p);
void set_board(const Board & board, bool clear = true);
void move(const Move & m);
void search(double time, uint64_t maxruns, int verbose);
Move return_move(int verbose) const { return return_move(& root, rootboard.toplay(), verbose); }
double gamelen() const;
vector<Move> get_pv() const;
string move_stats(const vector<Move> moves) const;
void timedout();
protected:
void garbage_collect(Board & board, Node * node); //destroys the board, so pass in a copy
bool do_backup(Node * node, Node * backup, int toplay);
Move return_move(const Node * node, int toplay, int verbose = 0) const;
Node * find_child(const Node * node, const Move & move) const ;
};
| true |
5cea924c2a901cb5e77678ff35de6cbc506e7b59 | C++ | jscrane/Interrupted | /src/watchdog.h | UTF-8 | 580 | 2.75 | 3 | [
"MIT"
] | permissive | #ifndef __WATCHDOG_H__
#define __WATCHDOG_H__
/**
* A Watchdog timer; resolution in seconds.
*/
class Watchdog: public Device {
public:
Watchdog(int id, unsigned secs=1): Device(id), _secs(secs), _left(0) {}
void ready() {
if (_left)
_left = _update_prescaler(_left);
else {
Device::ready();
disable();
}
}
// not enabled by default
bool begin();
void delay(unsigned secs) { _secs = secs; }
protected:
void _enable(bool);
unsigned _sleepmode();
private:
unsigned _update_prescaler(unsigned t);
unsigned _secs;
volatile unsigned _left;
};
#endif
| true |
96300737c432836fb3a8ffda7d2626fce3d21e21 | C++ | hgfeaon/leetcode | /SortList.cpp | UTF-8 | 2,889 | 3.421875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <iostream>
#include <cstdlib>
using namespace std;
class ListNode {
public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *_sortList(ListNode *head) {
if (head == NULL || head->next == NULL) return head;
ListNode *h1 = NULL, *h2 = NULL, *cur = head;
ListNode *tail1 = h1, *tail2 = h2;
int count = 0;
while (cur != NULL) {
if (++count & 0x1) {
if (h1 == NULL) {
tail1 = h1 = cur;
} else {
tail1->next = cur;
tail1 = cur;
}
} else {
if (h2 == NULL) {
tail2 = h2 = cur;
} else {
tail2->next = cur;
tail2 = cur;
}
}
cur = cur->next;
}
if (h1 != NULL) tail1->next = NULL;
if (h2 != NULL) tail2->next = NULL;
h1 = sortList(h1);
h2 = sortList(h2);
return merge(h1, h2);
}
ListNode *sortList(ListNode *head) {
if (head == NULL) return head;
ListNode* cur = head;
int count = 1;
while ((cur = cur->next) != NULL) count++;
return sortListN(head, count);
}
ListNode* sortListN(ListNode *head, int n) {
if (n < 2) return head;
ListNode *h1, *h2, *cur;
int k = n >> 1;
cur = head;
while (--k) cur = cur->next;
h1 = head;
h2 = cur->next;
cur->next = NULL;
h1 = sortListN(h1, n>>1);
h2 = sortListN(h2, n - (n>>1));
return merge(h1, h2);
}
ListNode* merge(ListNode* h1, ListNode* h2) {
ListNode *new_head = NULL, *new_tail = NULL, *cur;
while (h1 != NULL && h2 != NULL) {
if (h1->val < h2->val) {
cur = h1;
h1 = h1->next;
} else {
cur = h2;
h2 = h2->next;
}
if (new_head == NULL) {
new_head = new_tail = cur;
} else {
new_tail->next = cur;
new_tail = cur;
}
}
while (h1 != NULL) {
new_tail->next = h1;
new_tail = h1;
h1 = h1->next;
}
while (h2 != NULL) {
new_tail->next = h2;
new_tail = h2;
h2 = h2->next;
}
return new_head;
}
};
void print_list(ListNode* head) {
while (head != NULL) {
cout<<head->val<<" ";
head = head->next;
}
cout<<endl;
}
int main() {
ListNode na(2), nb(1);
na.next = &nb;
print_list(&na);
Solution s;
ListNode* ret = s.sortList(&na);
print_list(ret);
system("pause");
return 0;
}
| true |
54c14a08b6b595d0fae3df6cea9cbd4ccb472272 | C++ | OOP2019lab/lab3-l181068bilalahmed | /l181068_Lab3_Q1.cpp | UTF-8 | 3,926 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include "gitHubUser.h"
using namespace std;
void readDataFromFile( gitHubUser *&user, string filepath){
ifstream fin("C:\\Users\\Bilal Ahmed\\Desktop\\sample.txt");
if (fin.fail())
cout << "Could not locate" << endl;
//Storing Data whle reading each line
else{
char temp[500];
fin.getline(temp, 500);
int noOfEntries = temp[0] - 48; // Reading User count
user = new gitHubUser[noOfEntries];
for (int i = 0; i < noOfEntries; i++) {
fin.getline(temp, 500);
user[i].firstName = temp;
fin.getline(temp, 500);
user[i].userName = temp;
fin.getline(temp, 500);
user[i].email = temp;
fin.getline(temp, 500);
int noOfFiles = atoi(temp);
user[i].gitHubFolders = new string[noOfFiles];//Since there are more than 1 folder
for (int j = 0; j < noOfFiles; j++) {
fin.getline(temp, 50);
user[i].gitHubFolders[j] = temp;
}
}
}
}
void setEduBckGrnd(gitHubUser &user){
user.qualification_level = new string;
user.institute_name = new string;
//Taking Data from user and storing it on heap using pointers made in stack
cout << user.firstName << " enter your institution name: ";
cin >> *user.institute_name; // De-allocating pointer to store data on heap, where the pointer points
cout << user.firstName << " enter your qualification level: ";
cin >> *user.qualification_level; // De-allocating pointer to store data on heap, where the pointer points
}
void print(gitHubUser &user){
cout << "First Name: " << user.firstName << endl;
cout << "User Name: " << user.userName << endl;
cout << "Email Address: " << user.email << endl;
if (user.qualification_level != nullptr)//Prints data only if the pointer points to something
cout << "Qualification Level: " << *user.qualification_level << endl;
if (user.institute_name != nullptr)//Prints data only if the pointer points to something
cout << "Institute name: " << *user.institute_name << endl;
}
void remove(gitHubUser &user){
if (user.qualification_level != nullptr){
delete[] user.qualification_level;// Removes data from where the pointer points(heap)
user.qualification_level = nullptr;//Pointer now ponts to nothing
}
if (user.institute_name != nullptr){
delete [] user.institute_name;// Removes data from where the pointer points(heap)
user.institute_name = nullptr;//Pointer now ponts to nothing
}
}
void backup(gitHubUser *originalArry, gitHubUser *&backupArry, int userCount){
backupArry = new gitHubUser[userCount];
for (int i = 0; i < userCount ; i++){ //Taking a Deep Copy into a Back Up
backupArry[i].firstName = originalArry[i].firstName;
backupArry[i].userName = originalArry[i].userName;
backupArry[i].email = originalArry[i].email;
*backupArry[i].institute_name = *originalArry[i].institute_name; // Double Defrence while deep copying
*backupArry[i].qualification_level = *originalArry[i].qualification_level;// Double Defrence while deep copying
}
}
void menu(gitHubUser &user){
int key = 0;
string filepath;
//Providing different options
cout << "Press 1 to enter Background Educational Data" << endl;
cout << "Press 2 to Print Data" << endl;
cout << "Press 3 to Remove Background Educational information" << endl;
cout << "Press 4 to take back up of all the data" << endl;
cin >> key;
if (key == 1 ){
setEduBckGrnd(user);
cout << endl;
print(user);
cout << endl;
menu(user);//Re-Calling the 'menu' function
}
else if (key == 2){
print(user);
cout << endl;
menu(user);//Re-Calling the 'menu' function
}
else if (key == 3){
remove(user);
cout << endl;
menu (user);//Re-Calling the 'menu' function
}
}
int main(){
int userCount= 50;
string filepath;
gitHubUser * user;
readDataFromFile(user, filepath);
gitHubUser User;
menu(User);
system("pause");
} | true |
2a89c0c65a99f79bd687ad832de6b634a8371eca | C++ | edison-caldwell/SchoolWork | /CSCI385/assign4/Bucket.cpp | UTF-8 | 3,575 | 3.4375 | 3 | [] | no_license | #include "Bucket.h"
Bucket::Bucket()
{
head = NULL;
tail = NULL;
current = NULL;
}
Bucket::~Bucket()
{
if(head){
Reset();
GetNext(head);
while(head)
{
delete current;
GetNext(head);
GetNext(current);
}
}
return;
}
Bucket::Bucket(const Bucket& other)
{
nodePtr newBucketPtr = NULL;
if(!other.head){
head = NULL;
current = NULL;
previous = NULL;
tail = NULL;
sorted = false;
}
else
{
sorted = other.sorted;
nodePtr toCopy = other.head;
nodePtr prevNode = NULL;
head = new Node(toCopy->value);
head->previous = NULL;
head->next = NULL;
prevNode = head;
newBucketPtr = head;
toCopy = toCopy->next;
while(toCopy!= NULL)
{
newBucketPtr->next = new Node(toCopy->value);
newBucketPtr = newBucketPtr->next;
newBucketPtr->previous = prevNode;
prevNode = newBucketPtr;
newBucketPtr->next = NULL;
toCopy = toCopy->next;
}
}
tail = newBucketPtr;
Reset();
}
Bucket& Bucket::operator=(const Bucket& other)
{
nodePtr newBucketPtr = NULL;
if(!other.head){
head = NULL;
current = NULL;
previous = NULL;
tail = NULL;
}
else
{
nodePtr toCopy = other.head;
nodePtr prevNode = NULL;
head = new Node(toCopy->value);
head->previous = NULL;
head->next = NULL;
prevNode = head;
newBucketPtr = head;
toCopy = toCopy->next;
while(toCopy!= NULL)
{
newBucketPtr->next = new Node(toCopy->value);
newBucketPtr = newBucketPtr->next;
newBucketPtr->previous = prevNode;
prevNode = newBucketPtr;
newBucketPtr->next = NULL;
toCopy = toCopy->next;
}
}
tail = newBucketPtr;
Reset();
}
void Bucket::Insert(int inValue, bool sorted)
{
cout << "Bucket Insert\n";
if(!head){
cout << "If head is null\n";
head = new Node(inValue);
tail = head;
}
else if(sorted){
Reset();
while(current->next && current->next->value > inValue)
GetNext(current);
nodePtr temp = new Node(inValue);
temp->previous = current;
temp->next = current->next;
current->next->previous = temp;
current->next = temp;
if(tail->next)
GetNext(tail);
}
else{
tail->next = new Node(inValue);
tail->next->previous = tail;
GetNext(tail);
}
tail->next = NULL;
}
void Bucket::Remove()
{
nodePtr temp = tail;
GetPrevious(tail);
delete temp;
}
bool Bucket::Find(int search)
{
Reset();
while(current->value != search && current)
{
GetNext(current);
}
if(current->value == search)
return true;
return false;
}
int Bucket::NodeValue() const
{
if(current)
return current->value;
}
void Bucket::GetNext(nodePtr temp)
{
temp = temp->next;
return;
}
void Bucket::GetPrevious(nodePtr temp)
{
temp = temp->previous;
return;
}
void Bucket::Reset()
{
current = head;
return;
}
| true |
001f9153d2f4275ae24a04b8b4b3776ee4f57b37 | C++ | sekheng/SP2 | /MyGraphics/Source/StationScene.cpp | UTF-8 | 7,494 | 2.828125 | 3 | [] | no_license | #include "StationScene.h"
#include "MyMath.h"
#include "Application.h"
/******************************************************************************/
/*!
\brief - a default constructor, with all variables becoming default value
*/
/******************************************************************************/
StationScene::StationScene() : GameObject("Door")
{
}
StationScene::~StationScene()
{
}
/******************************************************************************/
/*!
\brief - init the variable that are needed
*/
/******************************************************************************/
void StationScene::Init(Camera3 &camera_address)
{
cam_pointer = &camera_address;
time = 0;
questActive = false;
card1 = false;
card2 = false;
questComplete = false;
doorOpened = false;
switchLightOn = true;
delay = 0.5f;
}
/******************************************************************************/
/*!
\brief - enable to collect card if is within the boundary
\return - 1 when is taken
\return - 0 if is not taken
*/
/******************************************************************************/
short StationScene::getCard1()
{
if (cam_pointer->position.x > -259 && cam_pointer->position.x < -258 && cam_pointer->position.z > 303 && cam_pointer->position.z < 308 && questActive == true && card1 == false)
{
if (Application::IsKeyPressed('E'))
{
card1 = true;
count++;
}
}
else if (card1 == true)
{
return 1;
}
else
{
return 0;
}
return 0;
}
/******************************************************************************/
/*!
\brief - enable to collect card if is within the boundary
\return - 1 when is taken
\return - 0 if is not taken
*/
/******************************************************************************/
short StationScene::getCard2()
{
if (cam_pointer->position.x > -294 && cam_pointer->position.x < -293 && cam_pointer->position.z > 290 && cam_pointer->position.z < 293 && questActive == true && card2 == false)
{
if (Application::IsKeyPressed('E'))
{
card2 = true;
count++;
}
}
else if (card2 == true)
{
return 1;
}
else
{
return 0;
}
return 0;
}
/******************************************************************************/
/*!
\brief - show text only with the interacting boundary
\return - true if the player is inside it's interacting boundary
\return - false if the player is outside it's interacting boundary
*/
/******************************************************************************/
bool StationScene::getCardText()
{
if (cam_pointer->position.x > -259 && cam_pointer->position.x < -258 && cam_pointer->position.z > 303 && cam_pointer->position.z < 308 && questActive == true && card1 == false)
{
return true;
}
else if (cam_pointer->position.x > -294 && cam_pointer->position.x < -293 && cam_pointer->position.z > 290 && cam_pointer->position.z < 293 && questActive == true && card2 == false)
{
return true;
}
else
{
return false;
}
}
/******************************************************************************/
/*!
\brief - to check to check whether what stage his in to open door
\return - 1 to tell player press E to open the door
\return - 2 to tell player that 2 keycard is needed to open
\return - 3 to spawn the card into the world
*/
/******************************************************************************/
short StationScene::getQuestStage()
{
if (questComplete == false)
{
if (cam_pointer->position.x > -293 && cam_pointer->position.x < -263 && cam_pointer->position.z > 250 && cam_pointer->position.z < 270 && questActive == false)
{
if (Application::IsKeyPressed('E'))
{
questActive = true;
return 0;
}
else
{
return 1;
}
}
else if (cam_pointer->position.x > -293 && cam_pointer->position.x < -263 && cam_pointer->position.z > 250 && cam_pointer->position.z < 270 && questActive == true)
{
return 2;
}
else if (questActive == true)
{
return 3;
}
}
else
{
return 0;
}
return 0;
}
/******************************************************************************/
/*!
\brief - to check whether the player taken 2 card and if 2 card is taken door can now be open after you press E
\return - 1 if the player has not open the door
\return - 2 if the player has open the door
*/
/******************************************************************************/
short StationScene::openSasame()
{
if (card1 == true && card2 == true)
{
questComplete = true;
if(cam_pointer->position.x > -293 && cam_pointer->position.x < -263 && cam_pointer->position.z > 250 && cam_pointer->position.z < 270 && doorOpened == false)
{
if (Application::IsKeyPressed('E'))
{
doorOpened = true;
}
return 1;
}
else if (cam_pointer->position.x > -293 && cam_pointer->position.x < -263 && cam_pointer->position.z > 250 && cam_pointer->position.z < 270 && doorOpened == true)
{
return 2;
}
else
{
return 0;
}
}
return 0;
}
/******************************************************************************/
/*!
\brief - to check whether the player in within it's interacting boundary to toggle the light
\return - true if the player is inside it's interacting boundary and whether E is press switch ON the light
\return - false if the player is inside it's interacting boundary and whether E is press switch off the light
*/
/******************************************************************************/
bool StationScene::roomLight()
{
if (cam_pointer->position.x > -266 && cam_pointer->position.x < -263 && cam_pointer->position.z > 312 && cam_pointer->position.z < 316 && Application::IsKeyPressed('E') && switchLightOn == true && time > delay)
{
time = 0;
switchLightOn = false;
}
else if (cam_pointer->position.x > -266 && cam_pointer->position.x < -263 && cam_pointer->position.z > 312 && cam_pointer->position.z < 316 && Application::IsKeyPressed('E') && switchLightOn == false && time > delay)
{
time = 0;
switchLightOn = true;
}
return switchLightOn;
}
/******************************************************************************/
/*!
\brief - show text only with the interacting boundary
\return - true if the player is inside it's interacting boundary
\return - false if the player is outside it's interacting boundary
*/
/******************************************************************************/
bool StationScene::switchText()
{
if (cam_pointer->position.x > -266 && cam_pointer->position.x < -263 && cam_pointer->position.z > 312 && cam_pointer->position.z < 316 && switchLightOn == true)
{
return true;
}
else if (cam_pointer->position.x > -266 && cam_pointer->position.x < -263 && cam_pointer->position.z > 312 && cam_pointer->position.z < 316 && switchLightOn == false)
{
return true;
}
else
{
return false;
}
}
/******************************************************************************/
/*!
\brief - updating the time
\param dt - frame time
*/
/******************************************************************************/
void StationScene::update(double dt)
{
time += (float)(dt);
}
/******************************************************************************/
/*!
\brief - reset the entire room interaction
*/
/******************************************************************************/
void StationScene::reset()
{
questActive = false;
card1 = false;
card2 = false;
questComplete = false;
doorOpened = false;
switchLightOn = true;
} | true |
5cc459ff339549187b2f06b323eabdf6b9f5ae0f | C++ | Vitor-labs/Trabalhos_ufc | /testes/controles/exceptions.cpp | UTF-8 | 928 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <exception>
using namespace std;
class exceptions : public exception{
protected:
string message;
public:
exceptions(string message){
this->message = message;}
virtual string what(){
return this->message;}
};
int fat(int n){
if (n < 0){
throw exceptions("Numero Negtivo");}
if (n == 0 || n == 1 ){
return 1;}
return n * fat(n-1);}
double div(double n, double n2){
if (n2 == 0){
throw exceptions("Divisao por 0");}
return n/n2;}
int main(int argc, char const *argv[]){
try{
cout << fat(5) << endl;
//cout << fat(-4) << endl;
cout << div(5.8, 6.1) << endl;
cout << div(6.0, 0.0) << endl;}
catch(exceptions e){
cerr << "error: " << e.what() << '\n';}
catch(...){
cerr << "Erro inesperado !" << endl;};
return 0;} | true |
7e21224ca80f0f2b2ac0414666ca40d285fbddc9 | C++ | ruiwenhe-10/Data-structure-Implementation-and-Practice-CPP | /Data Structure(C++)/Binary Search Tree/test.cpp | UTF-8 | 571 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <queue>
#include <list>
#include <fstream>
#include <string>
using namespace std;
int main() {
list<int> c;
c.push_back(1);
c.push_back(2);
c.push_back(3);
c.push_back(4);
c.push_back(5);
for (list<int>::iterator it = c.begin(); it != c.end(); ++it) {
if ((*it) == 3) {
it = c.erase(it);
}
}
for (list<int>::iterator it = c.begin(); it != c.end(); ++it) {
cout << ' ' << *it;
}
return 0;
} | true |
d1710e2ef332351a9648f4e985d778406864495b | C++ | IkhyeonJo/New_C_Quizs | /Quiz5/Quiz5/main.cpp | UTF-8 | 332 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
int main(void) {
int a[3][4] = { { 0,1,2,3 },{ 4,5,6,7 },{ 8,9,10,11 } };
int count[2];
for (count[0] = 0; count[0]<3; count[0]++) {
for (count[1] = 0; count[1]<4; count[1]++) {
a[count[0]][count[1]] += a[count[0]][count[1]];
printf("%d ", a[count[0]][count[1]]);
}
printf("\n");
}
return 0;
}
| true |
a7be7806a1048e80904453ae999c4703aad4b16b | C++ | ufocombat/clock-d1 | /clock-d1.ino | UTF-8 | 2,502 | 2.703125 | 3 | [] | no_license | #include "Arduino.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
#include "AlarmLib.h"
#define PIR_PIN D2 // Пир датчик
RTC_DS1307 rtc;
LiquidCrystal_I2C lcd(0x3F,16,2); // 1-Выяснить адрес дисплея
/* Плата D1
* SCL - дисплея и часов
* SDA - дисплея и часов - подкючаются параллельно
* Bluetooth
* Tx->Rx D1
* Rx->Tx D0
*/
boolean disp_light = true;
int lSec = 0;
unsigned long time;
int alarms[] = {
11*60,
13*60,
18*60,
19*60,
20*60,
};
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);//Off for D1
pinMode(PIR_PIN, INPUT);
Serial.begin(9600);
delay(100);
// if (! rtc.begin()) {
// Serial.println("Couldn't find RTC");
// while (1);
// }
Serial.print("Today: ");
Serial.println(Date2StrFull(rtc.now()));
Serial.println();
lcd.init();
lcd.backlight();
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); //Установить часы как Дата Компиляции Скетча
// January 21, 2014 at 3alarms you would call:
// rtc.adjust(DateTime(2017, 1, 31, 14, 17, 0));
}
boolean FindNextAlarm(DateTime date, Alarm& alarm)
{
int nnn = date.minute()+date.hour()*60;
boolean a = false;
int i;
for (i=0; i < (sizeof(alarms)/sizeof(int)); i++){
if (alarms[i]>nnn)
{
a=true;
break;
}
}
alarm = Alarm(alarms[i]);
return a;
}
boolean _colon = true;
void loop() {
DateTime n = rtc.now();
Alarm alarm;
if (Serial.available())
{
alarm = Alarm(Serial.readString());
alarms[0] = alarm.minutes();
Serial.println("Alarm on: "+alarm.ToStr());
Serial.println("Now: "+Date2StrFull(n));
}
if (lSec!=n.second())
{
lcd.setCursor(0, 0);
lcd.print(Time2StrHHMM(n,_colon));
_colon=!_colon;
if (FindNextAlarm(n,alarm))
{
lcd.print(" "+alarm.ToStr());
int delta = alarm.minutes()-Date_minutes(n);
if (delta>=600)
{
int w = delta/60;
lcd.print(" "+(String)w+"h ");//+
}
else
{
String w = Min2hMM(delta);
lcd.print(" "+(w.length()<=5?w:" "));
}
}
lcd.setCursor(0, 1);
lcd.print(Date2StrWeek(n));
lSec=n.second();
}
else delay(300);
if (digitalRead(PIR_PIN)==1) time = millis();
if (disp_light= millis()-time<20000) lcd.backlight(); else lcd.noBacklight();
}
| true |
7c430c6fed9f27bfca608cd0fa761c64c713babd | C++ | spectaclelabs/elvin | /elvin/basic_event.h | UTF-8 | 463 | 2.640625 | 3 | [] | no_license | #ifndef ELVIN_BASIC_EVENT_H
#define ELVIN_BASIC_EVENT_H
#include <memory>
#include "time_data.h"
#include "event.h"
namespace elvin {
class BasicEvent : public Event {
public:
BasicEvent(uint32_t time, void(*callback)()) :
Event(time), callback(callback) {}
virtual bool process(const TimeData &time) {
callback();
return false;
}
void(*callback)();
};
typedef std::unique_ptr<BasicEvent> BasicEventPtr;
}
#endif
| true |
d5f52c017b3ba8fb8911b18af37ecdd206cec175 | C++ | drkvogel/retrasst | /paulst/db/DBConnection.h | UTF-8 | 831 | 3.078125 | 3 | [] | no_license | #ifndef DBCONNECTIONH
#define DBCONNECTIONH
#include <string>
namespace paulstdb
{
class Cursor;
/*
Abstract representation of a connection to a database that
can be queried and updated.
*/
class DBConnection
{
public:
DBConnection();
virtual ~DBConnection();
virtual void close() = 0;
/*
Executes the specified SQL query and returns a Cursor
for reading the results of the query.
Be sure to delete the Cursor when it is no longer needed.
*/
virtual Cursor* executeQuery( const std::string& sql ) = 0;
/*
Executes the specified SQL.
*/
virtual void executeStmt ( const std::string& sql ) = 0;
private:
DBConnection( const DBConnection& );
DBConnection& operator=( const DBConnection& );
};
}
#endif
| true |
18f6338999c257dc391aa568987ce26701415f76 | C++ | alffore/Colonias | /src/ITRF2CCL.cpp | UTF-8 | 2,098 | 2.828125 | 3 | [] | no_license | /*
* File: ITRF2CCL.cpp
* Author: alfonso
*
* Created on July 14, 2013, 2:02 PM
*/
#include "ITRF2CCL.hpp"
ITRF2CCL::ITRF2CCL() {
phy1 = 0.30543262; //17.5 grados en rad
phy2 = 0.51487213; //29.5 grados en rad
phyf = 0.20943951; //12grados en rad
lambdaf = -1.7802358; //102grados oeste en rad
EF = 2.5E6; //este falso
NF = 0; // norte falso
a = 6378137.0; //radio terrestre
f = 1.0 / 298.257222101; //factor
e = 0.0818191910435; //excentricidad
//calculo de m1
m1 = sin(phy1);
m1 *= e;
m1 = pow(m1, 2);
m1 = 1 - m1;
m1 = sqrt(m1);
m1 = 1 / m1;
m1 *= cos(phy1);
//calculo de m2
m2 = 1 - pow(e * sin(phy2), 2);
m2 = 1 / m2;
m2 = sqrt(m2);
m2 *= cos(phy2);
//calculo de t1
t1 = pow((1 - e * sin(phy1)) / (1 + e * sin(phy1)), e / 2);
t1 = 1.0 / t1;
t1 *= tan((M_PI / 4) - (phy1 / 2));
//calculo de t2
t2 = pow((1 - e * sin(phy2)) / (1 + e * sin(phy2)), e / 2);
t2 = 1.0 / t2;
t2 *= tan((M_PI / 4) - (phy2 / 2));
//calculo de tf
tf = pow((1 - e * sin(phyf)) / (1 + e * sin(phyf)), e / 2);
tf = 1.0 / tf;
tf *= tan((M_PI / 4) - (phyf / 2));
//calculo de n
n = (log(m1) - log(m2)) / (log(t1) - log(t2));
//calculo de F
F = m1 / (n * pow(t1, n));
//calculo de rf
rf = a * F * pow(tf, n);
}
void ITRF2CCL::cDeg2PCCL(double latitud, double longitud) {
this->cRad2PCCL(latitud * M_PI / 180.0, longitud * M_PI / 180);
}
void ITRF2CCL::cRad2PCCL(double latitud, double longitud) {
lambda = longitud;
phy = latitud;
//calculo de t
t = pow((1 - e * sin(phy)) / (1 + e * sin(phy)), e / 2);
t = 1.0 / t;
t *= tan((M_PI / 4) - (phy / 2));
//calculo de r
r = a * F * pow(t, n);
//calculo de theta
theta = n * (lambda - lambdaf);
//Calculo de las coordenadas de Lambert
Este = EF + r * sin(theta);
Norte = NF + rf - r * cos(theta);
}
double ITRF2CCL::obtenEste(){
return Este;
}
double ITRF2CCL::obtenNorte(){
return Norte;
}
ITRF2CCL::~ITRF2CCL() {
}
| true |
d1745276e8ca9ba356ee248b69b263ade7096b1c | C++ | Mishkuh/wsu | /wsu/csci/labs/Lab_CPP_Complex/Source.cpp | UTF-8 | 318 | 2.609375 | 3 | [] | no_license | #include "Header.h"
int main(void)
{
Complex number1(10.0, 3.3);
Complex number2(1.1, 2.2);
Complex number3;
number3.setReal(6.9);
number3.setImaginary(1.2);
number2.printComplex();
number2 = number2 + number1;
number2.printComplex();
number2 = number2 - number1;
number2.printComplex();
return 0;
} | true |
9731a73b7cbd81648199520a20ea2fa09069f504 | C++ | neslon/dprep | /src/Discrete.cpp | UTF-8 | 6,709 | 2.546875 | 3 | [] | no_license | #include <R.h>
#include <Rmath.h>
#define MAX 10000
using namespace std;
double mid_point(double n1, double n2);
double entCI(double input[], int cMatrix[], double partition,int nrows, int begin, int end);
double logd(double x);
double ent(double s[], int cs[], int sCount);
double fullent(double s[], int cs[], int begin, int end);
double p(int cls, int cs[], int sCount);
double p(int cls, int cs[], int begin, int end);
void doMaxMinC(int cs[],int sCount, int& maxC, int& minC);
void doMaxMinC(int cs[],int& maxC, int& minC,int begin, int end);
double delta(double input[], int cInput[], double partition, int nrows, int begin, int end);
void do_the_rest(double input[],int cInput[],double t[],double t_sel[],int nrows,int begin,int end,int& index);
int min(double num[], int start, int limit);
double min2(double num[], int start, int limit);
extern "C" {
void discrete(double *mIn, int *cIn, double *t,int *ccsize, double *points, int *nparti)
{
int index=0,d, csize = *ccsize;
double t_sel[MAX];
for(int j=0;j<csize;j++) t_sel[j]=0.0;
do_the_rest(mIn,cIn,t,t_sel,csize,0,csize,index);
for(d=0;d<csize;d++) points[d] = t_sel[d];
*nparti = index + 1;
}
void Points(double *matrix, int *csize, double *tMatrix)
{
int j;
for(j=0;j<*csize-1;j++)
{
if(matrix[j+1]==matrix[j])
{
do
{
tMatrix[j]=0.0;
j++;
} while(matrix[j+1]==matrix[j]);
}
tMatrix[j] = mid_point(matrix[j], matrix[j+1]);
}
tMatrix[(*csize)-1]=0.0;
}
}
double mid_point(double n1, double n2)
{
return ((n1+n2)/2.0);
}
double entCI(double input[], int cMatrix[], double partition, int nrows,int begin, int end)
{
double* s1=new double[nrows];
double* s2=new double[nrows];
double entropy;
int* cs1= new int[nrows];
int* cs2=new int[nrows];
int s1Count=0, s2Count=0, sCount=0;
while(input[begin]<partition)
{
cs1[s1Count]=cMatrix[begin];
s1[s1Count++]=input[begin++];
}
while(begin<end)
{
cs2[s2Count]=cMatrix[begin];
s2[s2Count++]=input[begin++];
}
sCount=s1Count+s2Count;
entropy=(s1Count/double(sCount))*ent(s1,cs1,s1Count)
+(s2Count/double(sCount))*ent(s2,cs2,s2Count);
return entropy;
delete [] s1;
delete [] s2;
delete [] cs1;
delete [] cs2;
}
double ent(double s[], int cs[], int sCount)
{
double sum=0.0;
int maxC, minC;
doMaxMinC(cs, sCount,maxC,minC);
for(int i=minC;i<=maxC;i++)
{
if(p(i,cs,sCount)!=0.0)
{
sum+=(p(i,cs,sCount)*logd(p(i,cs,sCount)));
}
}
if(sum==0.0)
return sum;
sum=-sum;
return sum;
}
double fullent(double s[], int cs[], int begin, int end)
{
double sum=0.0;
int maxC, minC;
doMaxMinC(cs,maxC,minC,begin,end);
for(int i=minC;i<=maxC;i++)
{
if(p(i,cs,begin,end)!=0.0)
{
sum+=(p(i,cs,begin,end)*logd(p(i,cs,begin,end)));
}
}
if(sum==0.0)
return sum;
sum=-sum;
return sum;
}
void doMaxMinC(int cs[],int sCount, int& maxC, int& minC)
{
maxC=minC=cs[0];
for(int i=1;i<sCount;i++)
if(cs[i]>maxC)
maxC=cs[i];
else if(cs[i]<minC)
minC=cs[i];
}
void doMaxMinC(int cs[],int& maxC, int& minC,int begin, int end)
{
maxC=minC=cs[begin];
for(int i=begin+1;i<end;i++)
if(cs[i]>maxC)
maxC=cs[i];
else if(cs[i]<minC)
minC=cs[i];
}
double p(int cls, int cs[], int sCount)
{
int clsCount=0;
for(int i=0;i<sCount;i++)
if(cs[i]==cls)
clsCount++;
if(clsCount==0)
return 0.0;
return (clsCount/double(sCount));
}
double p(int cls, int cs[], int begin, int end)
{
int clsCount=0;
for(int i=begin;i<end;i++)
if(cs[i]==cls)
clsCount++;
if(clsCount==0)
return 0.0;
return (clsCount/double(end-begin));
}
double logd(double x)
{
return (log(x)/log(2.0));
}
double delta(double input[], int cInput[], double partition, int nrows, int begin, int end)
{
int nbegin=begin;
double* s1=new double[nrows];
double* s2=new double[nrows];
double delta;
int* cs1=new int[nrows];
int* cs2=new int[nrows];
int s1Count=0, s2Count=0;
while(input[begin]<partition)
{
cs1[s1Count]=cInput[begin];
s1[s1Count++]=input[begin++];
}
while(begin<end)
{
cs2[s2Count]=cInput[begin];
s2[s2Count++]=input[begin++];
}
int c=0, c1=0, c2=0, maxC[3], minC[3];
doMaxMinC(cInput,maxC[0],minC[0],nbegin,end);
doMaxMinC(cs1,s1Count,maxC[1],minC[1]);
doMaxMinC(cs2,s2Count,maxC[2],minC[2]);
for(int i=0;i<3;i++)
{
for(int j=minC[i];j<=maxC[i];j++)
{
if(i==0 && p(j,cInput,nbegin,end)!=0.0)
c++;
else if(i==1 && p(j,cs1,s1Count)!=0.0)
c1++;
else if(i==2 && p(j,cs2,s2Count)!=0.0)
c2++;
}
}
delta = logd(pow(3.0,double(c))-2)-(c*fullent(input,cInput,nbegin,end)-
c1*ent(s1,cs1,s1Count)-c2*ent(s2,cs2,s2Count));
return delta;
delete [] s1;
delete [] s2;
delete [] cs1;
delete [] cs2;
}
void do_the_rest(double input[],int cInput[],double t[],double t_sel[],int nrows,int begin,int end,int& index)
{
double* entropy=new double [nrows];
for(int i=begin;i<end;i++)
{
if(t[i]==0.0)
{
entropy[i]=0.0;
}
else
{
entropy[i]=entCI(input,cInput,t[i],nrows,begin,end);
}
}
int idxMinEnt = min(entropy,begin,end);
if(idxMinEnt>=0)
{
double gain = fullent(input,cInput,begin,end)-entropy[idxMinEnt];
double right_side = (logd((end-begin)-1)/(end-begin))
+(delta(input,cInput,t[idxMinEnt],nrows,begin,end)/(end-begin));
if(gain>right_side && idxMinEnt>=0)
{
t_sel[index]=t[idxMinEnt];
index++;
int nEnd = idxMinEnt+1;
do_the_rest(input,cInput,t,t_sel,nrows,begin,nEnd,index);
do_the_rest(input,cInput,t,t_sel,nrows,nEnd,end,index);
}
}
else
{
return;
}
delete [] entropy;
}
int min(double num[],int start, int limit)
{
double min;
int i=start;
while(num[i]==0.0)
{
i++;
}
min=num[i];
int result=i;
for(int j=i;j<limit;j++)
{
if(num[j]<min && num[j]!=0.0)
{
min=num[j];
result=j;
}
}
if(result==limit)
return -1;
return (result);
}
double min2(double num[],int start, int limit)
{
double min;
min=num[start];
for(int j=start+1;j<limit;j++)
{
if(num[j]<min)
{
min=num[j];
}
}
return (min);
}
| true |
2f51acb81fc5cdb8abff301a3428b77b35ab046d | C++ | HayeonP/HyundaiSelfDriving_2019 | /Autoware/ros/src/computing/perception/detection/vision_detector/packages/vision_darknet_detect/include/headers/roadsign_class_score.h | UTF-8 | 3,117 | 2.5625 | 3 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | #include <sstream>
#include <string>
namespace Yolo3
{
enum RoadsignClasses//using coco for default cfg and weights
{
SPEED_OTHER, CHILD_PROTECT, NO_LEFT, NO_RIGHT, NO_PARKING, CROSSWALK, NO_UTURN,
ROTATE, SLOW, SPEED_BUST, UNPROTECTED_LEFT, UTURN, NO_STRAIGHT, SPEED_20, SPEED_30,
SPEED_40, SPEED_50, SPEED_60, SPEED_70, SPEED_80, SPEED_90, SPEED_100,
};
}
template<typename _Tp> class RoadsignClassScore
{
public:
_Tp x, y, w, h;
_Tp score;
unsigned int class_type;
bool enabled;
inline std::string toString()
{
std::ostringstream out;
out << class_type << "(x:" << x << ", y:" << y << ", w:" << w << ", h:" << h << ") =" << score;
return out.str();
}
inline std::string GetClassString()
{
switch (class_type)
{
case Yolo3::SPEED_OTHER: return "SPEED_OTHER";
case Yolo3::CHILD_PROTECT: return "CHILD_PROTECT";
case Yolo3::NO_LEFT: return "NO_LEFT";
case Yolo3::NO_RIGHT: return "NO_RIGHT";
case Yolo3::NO_PARKING: return "NO_PARKING";
case Yolo3::CROSSWALK: return "CROSSWALK";
case Yolo3::NO_UTURN: return "NO_UTURN";
case Yolo3::ROTATE: return "ROTATE";
case Yolo3::SLOW: return "SLOW";
case Yolo3::SPEED_BUST: return "SPEED_BUST";
case Yolo3::UNPROTECTED_LEFT: return "UNPROTECTED_LEFT";
case Yolo3::UTURN: return "UTURN";
case Yolo3::NO_STRAIGHT: return "NO_STRAIGHT";
case Yolo3::SPEED_20: return "SPEED_20";
case Yolo3::SPEED_30: return "SPEED_30";
case Yolo3::SPEED_40: return "SPEED_40";
case Yolo3::SPEED_50: return "SPEED_50";
case Yolo3::SPEED_60: return "SPEED_60";
case Yolo3::SPEED_70: return "SPEED_70";
case Yolo3::SPEED_80: return "SPEED_80";
case Yolo3::SPEED_90: return "SPEED_90";
case Yolo3::SPEED_100: return "SPEED_100";
default:return "error";
}
}
inline int GetClassInt()
{
switch (class_type)
{
case Yolo3::SPEED_OTHER: return 0;
case Yolo3::CHILD_PROTECT: return 1;
case Yolo3::NO_LEFT: return 2;
case Yolo3::NO_RIGHT: return 3;
case Yolo3::NO_PARKING: return 4;
case Yolo3::CROSSWALK: return 5;
case Yolo3::NO_UTURN: return 6;
case Yolo3::ROTATE: return 7;
case Yolo3::SLOW: return 8;
case Yolo3::SPEED_BUST: return 9;
case Yolo3::UNPROTECTED_LEFT: return 10;
case Yolo3::UTURN: return 11;
case Yolo3::NO_STRAIGHT: return 12;
case Yolo3::SPEED_20: return 13;
case Yolo3::SPEED_30: return 14;
case Yolo3::SPEED_40: return 15;
case Yolo3::SPEED_50: return 16;
case Yolo3::SPEED_60: return 17;
case Yolo3::SPEED_70: return 18;
case Yolo3::SPEED_80: return 19;
case Yolo3::SPEED_90: return 20;
case Yolo3::SPEED_100: return 21;
default:return 0;
}
}
}; | true |
18ee1e14fbe95b34d153b2181e0d7dce2ee694e7 | C++ | felixqin/pfw | /drv/obj.cpp | GB18030 | 3,816 | 2.8125 | 3 | [] | no_license | #include "precomp.h"
#include "obj.h"
void CObjectTbl::Initialize()
{
m_link = NULL;
KeInitializeSpinLock( &m_guard );
}
void CObjectTbl::Uninitialize()
{
Clear();
}
void CObjectTbl::Clear()
{
KIRQL irql;
KeAcquireSpinLock( &m_guard, &irql );
OBJECT_TABLE_ENTRY *p = m_link, *q;
while ( p )
{
q = p;
p = p->next;
if ( q->handlers ) ExFreePool( q->handlers );
ExFreePool( q );
}
m_link = NULL;
KeReleaseSpinLock( &m_guard, irql );
}
NTSTATUS CObjectTbl::Append( PFILE_OBJECT fileobj, HANDLE pid, ULONG ip, USHORT port )
{
NTSTATUS status;
KIRQL irql;
KeAcquireSpinLock( &m_guard, &irql );
OBJECT_TABLE_ENTRY *ote = find( fileobj ) ;
if ( ote )
{
ote->pid = pid;
ote->ip = ip;
ote->port = port;
status = STATUS_SUCCESS;
}
else
{
ote = (OBJECT_TABLE_ENTRY *)ExAllocatePool( NonPagedPool, sizeof(OBJECT_TABLE_ENTRY) );
if ( NULL == ote )
{
DBGPRINT("Object table append failure! insufficient resources!");
status = STATUS_INSUFFICIENT_RESOURCES;
}
else
{
ote->fileobj = fileobj;
ote->pid = pid;
ote->ip = ip;
ote->port = port;
ote->handlers = NULL;
ote->next = m_link;
m_link = ote;
status = STATUS_SUCCESS;
}
}
KeReleaseSpinLock( &m_guard, irql );
return status;
}
NTSTATUS CObjectTbl::Remove( PFILE_OBJECT fileobj )
{
NTSTATUS status;
KIRQL irql;
KeAcquireSpinLock( &m_guard, &irql );
POBJECT_TABLE_ENTRY p, q;
p = find ( fileobj, &q );
if ( NULL == p )
{
DBGPRINT("File object is not exsited in object table!");
status = STATUS_INVALID_PARAMETER_1;
}
else
{
if ( p != m_link )
{
q->next = p->next;
}
else
{
m_link = p->next;
}
if ( p->handlers ) ExFreePool(p->handlers);
ExFreePool( p );
status = STATUS_SUCCESS;
}
KeReleaseSpinLock( &m_guard, irql );
return status;
}
POBJECT_TABLE_ENTRY CObjectTbl::find( PFILE_OBJECT fileobj, POBJECT_TABLE_ENTRY *pprev )
{
POBJECT_TABLE_ENTRY p = m_link, prev = NULL;
while ( p )
{
if ( p->fileobj == fileobj ) break;
prev = p;
p = p->next;
}
if ( pprev ) *pprev = prev;
return p;
}
NTSTATUS CObjectTbl::GetInfo( PFILE_OBJECT fileobj, PHANDLE ppid, PULONG pip, PUSHORT pport )
{
NTSTATUS status;
KIRQL irql;
KeAcquireSpinLock( &m_guard, &irql );
POBJECT_TABLE_ENTRY ote = find( fileobj );
if ( NULL == ote )
{
DBGPRINT("Cannot search for fileobj in object table!");
status = STATUS_INVALID_PARAMETER_1;
}
else
{
if(ppid) *ppid = ote->pid;
if(pip) *pip = ote->ip;
if(pport) *pport = ote->port;
status = STATUS_SUCCESS;
}
KeReleaseSpinLock( &m_guard, irql );
return status;
}
/*
ļ fileobj
ppid, pip, pport Ϊ NULL, ı
*/
NTSTATUS CObjectTbl::SetInfo( PFILE_OBJECT fileobj, PHANDLE ppid, PULONG pip, PUSHORT pport )
{
NTSTATUS status;
KIRQL irql;
KeAcquireSpinLock( &m_guard, &irql );
POBJECT_TABLE_ENTRY ote = find( fileobj );
if ( NULL == ote )
{
status = STATUS_INVALID_PARAMETER_1;
}
else
{
if (ppid) ote->pid = *ppid;
if (pip) ote->ip = *pip;
if (pport) ote->port = *pport;
status = STATUS_SUCCESS;
}
KeReleaseSpinLock( &m_guard, irql );
return status;
}
PFW_EVENT_CONTEXT * CObjectTbl::GetEventHandlers( PFILE_OBJECT fileobj )
{
PFW_EVENT_CONTEXT *handlers;
KIRQL irql;
KeAcquireSpinLock( &m_guard, &irql );
POBJECT_TABLE_ENTRY ote = find( fileobj );
if ( NULL == ote )
{
handlers = NULL;
}
else if ( ote->handlers != NULL )
{
handlers = ote->handlers;
}
else //Ϊ ote->handlers ռ
{
SIZE_T size = sizeof(PFW_EVENT_CONTEXT) * MAX_EVENT;
ote->handlers = (PFW_EVENT_CONTEXT*) ExAllocatePool( NonPagedPool, size );
if ( ote->handlers != NULL ) //ɹ
{
RtlZeroMemory( ote->handlers, size );
handlers = ote->handlers;
}
}
KeReleaseSpinLock( &m_guard, irql );
return handlers;
}
| true |
cb6178ed6ac70d9d28620e2f0c0e36497ef9d145 | C++ | wangxx2026/universe | /ideas/procpp/mixin_handler/ThreadPool.h | UTF-8 | 536 | 2.875 | 3 | [] | no_license | #pragma once
#include <functional>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
using namespace std;
class IThreadPool
{
public:
using Task = function<void(void)>;
virtual void execute(Task t) = 0;
};
class ThreadPool : public IThreadPool
{
public:
ThreadPool(int n = 0);
virtual void execute(Task t) override;
private:
void run();
Task get_task();
vector<thread> _threads;
queue<Task> _q;
mutex _mutex;
condition_variable _cond;
};
| true |
456497e6f150eeb91d780bcfafd0e0de5124ad2c | C++ | sparshsinha123/competetive-programming | /codesnippets/lazysegtree.cpp | UTF-8 | 3,885 | 2.8125 | 3 | [] | no_license | template<typename segment, typename update>
class segmenttree{
public:
struct node {
segment seg;
update upd;
};
int sz;
vector<node> tree;
segmenttree(){}
segmenttree(int n){
init(n);
}
void init(int n){
sz = 1;
while(sz < n){
sz <<= 1;
}
tree.assign(2 * sz, node());
}
/* push down changes from a particular node */
void push_down(int x, int st, int en){
if(tree[x].upd.is_default()) return;
tree[x].seg.apply(st, en, tree[x].upd);
if(st < en){
tree[2*x+1].upd = tree[2*x+1].upd.combine(tree[x].upd);
tree[2*x+2].upd = tree[2*x+2].upd.combine(tree[x].upd);
}
tree[x].upd.reset();
}
/* query a certain range [ql..qr]*/
void query(int x, int st, int en, int ql, int qr, segment &ans){
if(st > en || en < ql || st > qr) return;
push_down(x, st, en);
if(st >= ql && en <= qr){
ans.merge(tree[x].seg);
return;
}
int m = (st + en) >> 1;
query(2*x+1, st, m, ql, qr, ans);
query(2*x+2, m+1, en, ql, qr, ans);
}
/* apply range update on [ul..ur] */
void range_upd(int x, int st, int en, int ul, int ur, const update &U){
if(st > en || st > ur || en < ul) return;
push_down(x, st, en);
if(st >= ul && en <= ur){
tree[x].upd = tree[x].upd.combine(U);
return;
}
int m = (st + en) >> 1;
range_upd(2*x+1, st, m, ul, ur, U);
range_upd(2*x+2, m+1, en, ul, ur, U);
segment lf = tree[2*x+1].seg;
segment rt = tree[2*x+2].seg;
lf.apply(st, m, tree[2*x+1].upd);
rt.apply(m + 1, en, tree[2*x+2].upd);
lf.merge(rt);
tree[x].seg = lf;
}
/* API : query */
segment get(int L, int R){
segment ans;
if(L > R) return ans;
query(0, 0, sz - 1, L, R, ans);
return ans;
}
/* API : range update */
void modify(int L, int R, const update &U){
range_upd(0, 0, sz - 1, L, R, U);
}
};
struct update{
int bit;
static const int DEFAULT_UPD = -1;
/* default lazy update value */
update(int _bit = DEFAULT_UPD){
bit = _bit;
}
bool is_default() const{
return bit == DEFAULT_UPD;
}
/* reset the values of update to default */
void reset(){
bit = DEFAULT_UPD;
}
/* two successive updates applied */
update combine(const update &other) const{
return update(other.bit);
}
};
struct segment{
int left_most_one;
int right_most_one;
int left_most_zero;
int right_most_zero;
int sum;
static const ll DEFAULT_VAL = 0; /* when segments are created using init */
static const ll NEUTRAL_VAL = 0; /* be careful here */
/* return empty segment -- when the segment tree is created
then this is the default segment value */
segment() {
left_most_one = left_most_zero = INF;
right_most_one = right_most_zero = -INF;
sum = 0;
}
/* apply the update on current range */
void apply(int start, int end, const update &UPD){
if(UPD.is_default()) return;
if(UPD.bit == 0){
right_most_one = -INF;
left_most_one = INF;
left_most_zero = start;
right_most_zero = end;
sum = 0;
} else{
assert(UPD.bit == 1);
left_most_zero = INF;
right_most_zero = -INF;
left_most_one = start;
right_most_one = end;
sum = end - start + 1;
}
}
/* merge `other` segment with this segment */
void merge(const segment &other){
left_most_one = min(left_most_one , other.left_most_one);
right_most_one = max(right_most_one , other.right_most_one);
left_most_zero = min(left_most_zero, other.left_most_zero);
right_most_zero = max(right_most_zero, other.right_most_zero);
sum += other.sum;
}
/* merge two segments */
void merge(const segment &a, const segment &b){
*this = a;
merge(b);
}
}; | true |
969767e208a91b4741cbdb173a8620c58e1d7bb0 | C++ | PaigeG/Comp-Sci-1-2017 | /phonePad.cpp | UTF-8 | 1,415 | 3.234375 | 3 | [] | no_license | //Paige Gadapee
//Oct 12, 2017
//code for string of built in functions
#include <iostream>
using namespace std;
int main ()
{
//varibales
int i, len;
string phone;
char token, rerun;
do
{
//input
cout << " Enter phone (1-800-Flowers) : ";
cin >> phone;
//processing
len = phone.length();
for (i=0; i<len; i++)
{
token = phone.at(i);
switch (token)
{
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
cout << "2";
break;
case 'd':
case 'D':
case 'e':
case 'E':
case 'f':
case 'F':
cout << "3";
break;
case 'g':
case 'G':
case 'h':
case 'H':
case 'i':
case 'I':
cout << "4";
break;
case 'j':
case 'J':
case 'k':
case 'K':
case 'l':
case 'L':
cout << "5";
break;
case 'm':
case 'M':
case 'n':
case 'N':
case 'o':
case 'O':
cout << "6";
break;
case 'p':
case 'P':
case 'q':
case 'Q':
case 'r':
case 'R':
case 's':
case 'S':
cout << "7";
break;
case 't':
case 'T':
case 'u':
case 'U':
case 'v':
case 'V':
cout << "8";
break;
case 'w':
case 'W':
case 'x':
case 'X':
case 'y':
case 'Y':
case 'z':
case 'Z':
cout << "9";
break;
default:
cout << token;
break;
}
}
cout << endl;
cout << "Would you like to enter another number (y=yes, n=no) : ";
cin >> rerun;
} while (rerun == 'y' || rerun == 'Y');
return 0;
}
| true |
d217c38e4b3c097106aa95bf05861bf3d446448f | C++ | dushibaiyu/DsbyLiteProjects | /AES/main.cpp | UTF-8 | 2,010 | 2.5625 | 3 | [] | no_license | #include <QString>
#include <iostream>
#include "aes.h"
#include "aeshelper.h"
#include <fstream>
int main(int argc, char *argv[])
{
/* char mingwen[] = "123456";
char miwen_hex[1024];
//char miwen_hex[] = "8FEEEFE524F8B68DC1FCA2899AC1A6B82E636F6D";
char result[1024];
unsigned char key[] = "maomao123456";
AES aes(key);
aes.Cipher(mingwen, miwen_hex);
std::cout << miwen_hex<<std::endl;
aes.InvCipher(miwen_hex, result);
std::cout<<result<<std::endl;*/
std::fstream file;
file.open("aa.txt");
QString tmp("123456");
AesHelper aess;
tmp = aess.aesEncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp = aess.aesUncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp= "localhost";
tmp = aess.aesEncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp = aess.aesUncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp= "postgres";
tmp = aess.aesEncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp = aess.aesUncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;;
tmp= "cms";
tmp = aess.aesEncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp = aess.aesUncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp= "123789";
tmp = aess.aesEncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
tmp = aess.aesUncrypt(tmp);
std::cout << tmp.toStdString() << std::endl;
file << tmp.toStdString() << std::endl;
return 0;
}
| true |
fe49624d2cd96ef3f907b5bde89aca205fc3ff27 | C++ | chenhongqiao/USACO | /P3669/P3669.cpp | UTF-8 | 663 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <algorithm>
using namespace std;
struct cow
{
int num, milk;
} c[100005];
bool cmp(const cow &a, const cow &b)
{
return a.milk < b.milk;
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> c[i].num >> c[i].milk;
}
sort(c, c + n, cmp);
int h = 0, t = n - 1;
int ans = 0;
while (h <= t)
{
ans = max(ans, c[h].milk + c[t].milk);
int tmp = min(c[h].num, c[t].num);
c[h].num -= tmp;
c[t].num -= tmp;
if (c[h].num <= 0)
h++;
if (c[t].num <= 0)
t--;
}
cout << ans << endl;
return 0;
} | true |
53418c5ee09e7484daf61a93c858730d074ac214 | C++ | arafathali122333/Accident-Avoidance-Detection-System | /Code/Accident Avoidance/Using_Ultrasonic.ino | UTF-8 | 828 | 2.546875 | 3 | [] | no_license | #define trigPin 2
#define echoPin 3
#define motor 10
#define motor2 12
void setup(){
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motor, OUTPUT);
pinMode(motor2, OUTPUT);
}
void loop(){
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 10){
digitalWrite(motor,LOW);
digitalWrite(motor2,HIGH);
delay(4000);
digitalWrite(motor,LOW);
digitalWrite(motor2,LOW);
exit(0);
}
else {
digitalWrite(motor,HIGH);
digitalWrite(motor2,LOW);
}
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
| true |
89b5d19f9c7c7dcf86f6fcf88ec9e0c8f80efc1e | C++ | shlomog12/Systems_Programming_Course_b | /ThePandemicGame/partB/sources/FieldDoctor.cpp | UTF-8 | 720 | 2.578125 | 3 | [] | no_license | #include "FieldDoctor.hpp"
namespace pandemic{
Player& FieldDoctor::treat(City city){
if (this->current_location!=city && !this->board.is_nei(current_location,city)){
throw std::out_of_range("It is not possible to remove an illness from a city where you are not");
}
if(this->board.get_level(city)==0){
throw std::out_of_range("It is not possible to lower a disease cube below 0");
}
Color color=this->board.get_color(city);
if (this->board.get_cure(color)){
this->board.get_level(city)=0;
}else{
this->board.get_level(city)--;
}
return *this;
}
} | true |
3b42c13a822590a64dabd522a6186d2493a86c5e | C++ | cooper-zhzhang/engine | /tools/util_func.cpp | UTF-8 | 553 | 2.640625 | 3 | [] | no_license |
#include "../public/auto_mem.h"
#include "../public/var_list.h"
#include "util_func.h"
#include <string>
#include <math.h>
#include <time.h>
#include <vector>
#include <algorithm>
float util_normalize_angle(float angle)
{
float value = ::fmod(angle, PI2);
if (value < 0)
{
value = value + PI2;
}
if (value < FLT_EPSILON && ::fabs(angle) > PI)
{
value = PI2;
}
return value;
}
float util_dot_distance(float x1, float y1, float x2, float y2)
{
float sx = x1 - x2;
float sy = y1 - y2;
return ::sqrt(sx * sx + sy * sy);
}
| true |
63c8dde3a04a46110841e084652b8fd49a53d011 | C++ | iximiuz/DifferentialWheeledRobot | /src/engine/renderer.cpp | UTF-8 | 2,812 | 2.6875 | 3 | [] | no_license | #include "engine/renderer.hpp"
#include <exception>
#include <string>
#include <SDL.h>
static void SDL_OK(int code) {
if (code != 0) {
throw std::runtime_error(
"SDL call failed with code " + std::to_string(code) + ": "
+ std::string(SDL_GetError()));
}
}
Texture::Texture(SDL_Renderer *renderer,
int x, int y,
int width, int height,
double angle)
: x_(x), y_(y), width_(width), height_(height), angle_(angle) {
sdl_texture_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_TARGET, width_, height_);
SDL_OK(sdl_texture_ == nullptr ? -1 : 0);
}
Texture::~Texture() {
SDL_DestroyTexture(sdl_texture_);
}
Renderer::Renderer(int width, int height)
: width_(width),
height_(height),
sdl_window_(nullptr),
sdl_renderer_(nullptr) {
SDL_OK(SDL_Init(SDL_INIT_VIDEO));
SDL_OK(SDL_CreateWindowAndRenderer(width_, height_, 0,
&sdl_window_, &sdl_renderer_));
}
Renderer::~Renderer() {
if (sdl_renderer_ != nullptr) {
SDL_DestroyRenderer(sdl_renderer_);
}
if (sdl_window_ != nullptr) {
SDL_DestroyWindow(sdl_window_);
}
SDL_Quit();
}
void Renderer::Render(PTexture texture) {
SDL_Rect dest;
dest.x = texture->GetX();
dest.y = texture->GetY();
dest.w = texture->GetWidth();
dest.h = texture->GetHeight();
SDL_OK(SDL_RenderCopyEx(sdl_renderer_,
texture->sdl_texture_,
nullptr,
&dest,
texture->GetAngle(),
nullptr,
SDL_FLIP_NONE));
SDL_RenderPresent(sdl_renderer_);
}
PTexture Renderer::CreateRobotTexture() const {
PTexture texture(new Texture(sdl_renderer_, width_/2, height_/2, 32, 32, 45.0));
RenderingContext _ctx(sdl_renderer_, texture->sdl_texture_);
SDL_OK(SDL_SetTextureBlendMode(texture->sdl_texture_, SDL_BLENDMODE_BLEND));
SDL_OK(SDL_SetRenderDrawBlendMode(sdl_renderer_, SDL_BLENDMODE_NONE));
SDL_OK(SDL_SetRenderDrawColor(sdl_renderer_, 255, 0, 0, 0));
SDL_OK(SDL_RenderClear(sdl_renderer_));
// SDL_RenderDrawRect(renderer, &r);
// SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0x00);
// SDL_RenderFillRect(renderer, &r);
return texture;
}
RenderingContext::RenderingContext(SDL_Renderer *renderer, SDL_Texture *target)
: sdl_renderer_(renderer) {
saved_target_ = SDL_GetRenderTarget(sdl_renderer_);
SDL_OK(SDL_SetRenderTarget(sdl_renderer_, target));
}
RenderingContext::~RenderingContext() {
SDL_SetRenderTarget(sdl_renderer_, saved_target_);
}
| true |
1a7c92c314bebe697f969fb32dfb8ba9a9302398 | C++ | fhtw/grafl_mueller | /TWMailer/TWMailer/client.cpp | UTF-8 | 2,331 | 2.828125 | 3 | [] | no_license | /*
client.cpp
BIF 3C1
Alexander Grafl
Philipp Müller
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUF 1024
using namespace std;
int main (int argc, char **argv)
{
int create_socket;
int portNb;
char buffer[BUF];
struct sockaddr_in address;
int size;
if( argc < 2 )
{
printf("Wrong number of Arguments!\nUsage: %s ServerAddress Port\n", argv[0]);
exit(EXIT_FAILURE);
}
portNb = atoi(argv[2]);
if ((create_socket = socket (AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Socket error");
return EXIT_FAILURE;
}
memset(&address,0,sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons (portNb);
inet_aton (argv[1], &address.sin_addr);
if (connect ( create_socket, (struct sockaddr *) &address, sizeof (address)) == 0)
{
printf ("Connection with server (%s) established\n", inet_ntoa (address.sin_addr));
size=recv(create_socket,buffer,BUF-1, 0);
if (size>0)
{
buffer[size]= '\0';
printf("%s",buffer);
}
}
else
{
perror("Connect error - no server available");
return EXIT_FAILURE;
}
do
{
printf ("Send message: ");
fgets (buffer, BUF, stdin);
send(create_socket, buffer, strlen (buffer), 0);
if(strncmp (buffer, "send", 4) == 0);
if(strncmp (buffer, "list", 4) == 0);
if(strncmp (buffer, "read", 4) == 0);
if(strncmp (buffer, "del", 3) == 0)
{
/* Instruction */
size=recv(create_socket,buffer,BUF-1, 0);
printf("%s",buffer);
/* username */
fgets (buffer, BUF, stdin);
size=recv(create_socket,buffer,BUF-1, 0);
printf("%s",buffer);
if (strncmp(buffer,"ERR",3) != 0)
{
/* message id */
fgets (buffer, BUF, stdin);
/* response -- OK or ERR */
size=recv(create_socket,buffer,BUF-1, 0);
printf("%s",buffer);
}
}
}
while (strcmp (buffer, "quit\n") != 0);
close (create_socket);
return EXIT_SUCCESS;
}
| true |
baf107743fb23f672eb0248bbf467726e75b3d42 | C++ | xiaoqixian/Wonderland | /leetcode/garbageCollection.cpp | UTF-8 | 1,081 | 2.828125 | 3 | [] | no_license | /**********************************************
> File Name : garbageCollection.cpp
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Sun Aug 28 11:46:06 2022
> Location : Shanghai
> Copyright@ https://github.com/xiaoqixian
**********************************************/
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
//int dist = 0, m_dist = 0, p_dist = 0, g_dist = 0;
vector<int> dist(4, 0);
int res = garbage[0].size();
for (int i = 1; i < garbage.size(); i++) {
dist[0] += travel[i-1];
for (char c: garbage[i]) {
int index = 0;
switch (c) {
case 'M': index = 1; break;
case 'G': index = 2; break;
case 'P': index = 3; break;
}
res += dist[0] - dist[index] + 1;
dist[index] = dist[0];
}
}
return res;
}
};
| true |
301f25f1146e91c2fdc8cfb4bde9d8e215254473 | C++ | RajalakshmiSomasundaram/ProblemSolving | /RadixSort.cpp | UTF-8 | 3,159 | 3.375 | 3 | [] | no_license | /******************************************************************************
Radix Sort
Sample input
5
77 23 17 5 12
Output
12 23 5 17 7
5 12 17 23 77
*******************************************************************************/
#include <iostream>
#include <cmath>
#include<string>
using namespace std;
#define MAX 100
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int findDigit(int num,int n)
{
int divider=pow(10,(n-1));
if(n==1)
return num%10;
else
{
int digit = (num/divider)%10;
return digit;
}
}
int findLen(int num)
{
int count=0;
do {
count ++;
num = num/10;
}while(num);
return count;
}
int main()
{
int input[MAX];
int num_of_input,maxLen=0;
cin >> num_of_input;
if ( num_of_input <=0 || num_of_input >= MAX)
{
cout << "Invalid range!";
}
else
{
for ( int i=0; i<num_of_input; i++)
{
cin>>input[i];
int len=findLen(input[i]);
if(maxLen<=len)
{
maxLen=len;
}
}
int num[num_of_input][maxLen];
for (int i=0; i<num_of_input; i++)
{
int len=findLen(input[i]);
if (len < maxLen)
{
int pad_count=maxLen-len;
int k=0;
for (;k<pad_count;k++)
{
num[i][k]=0;
}
for (int l=maxLen-1,m=1;l>=k,m<=len;l--,m++)
{
num[i][l]=findDigit(input[i],m);
}
}
else
{
for(int l=maxLen-1,m=1;l>=0,m<=len;l--,m++)
{
num[i][l] = findDigit(input[i],m);
}
}
}
int i, j;
bool swapped;
int le=maxLen-1;
while(le>=0)
{
for (i = 0; i < num_of_input-1; i++)
{
swapped = false;
for (j = 0; j < num_of_input-i-1; j++)
{
if (num[j][le] > num[j+1][le])
{
for(int k=0;k<maxLen;k++)
{
swap(&num[j][k], &num[j+1][k]);
}
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
std::string str[num_of_input];
for (int i=0; i<num_of_input; i++)
{
for(int j=0; j<maxLen; j++)
{
str[i].append(std::to_string(num[i][j]));
}
std::cout << std::stoi(str[i]) << '\t';
}
cout << endl;
le--;
}
}
return 0;
}
| true |
afd816f38c03d3f05d0447fbf6071e10b968601b | C++ | SayedKhaledd/CS316LastTask | /ClientData.cpp | UTF-8 | 2,270 | 3.171875 | 3 | [] | no_license | #include <string>
#include "ClientData.h"
using namespace std;
// default ClientData constructor
ClientData::ClientData(int accountNumberValue, int branchIDValue,const string &lastName, const string &firstName, double balanceValue)
: accountNumber(accountNumberValue), balance(balanceValue),branchID(branchIDValue) {
setLastName(lastName);
setFirstName(firstName);
} // end ClientData constructor
// get account-number value
int ClientData::getAccountNumber() const {
return accountNumber;
} // end function getAccountNumber
// set account-number value
void ClientData::setAccountNumber(int accountNumberValue) {
accountNumber = accountNumberValue; // should validate
} // end function setAccountNumber
int ClientData::getBranchID() const {
return branchID;
} // end function getAccountNumber
// set account-number value
void ClientData::setBranchID(int branchIDValue) {
branchID = branchIDValue; // should validate
} // end function setAccountNumber
// get last-name value
string ClientData::getLastName() const {
return lastName;
} // end function getLastName
// set last-name value
void ClientData::setLastName(const string &lastNameString) {
// copy at most 15 characters from string to lastName
// copy at most 15 characters from string to lastName
int length = lastNameString.size();
length = (length < 15 ? length : 14);
lastNameString.copy(lastName, length);
lastName[ length ] = '\0'; // append null character to lastName
} // end function setLastName
// get first-name value
string ClientData::getFirstName() const {
return firstName;
} // end function getFirstName
// set first-name value
void ClientData::setFirstName(const string &firstNameString) {
// copy at most 10 characters from string to firstName
int length = firstNameString.size();
length = (length < 10 ? length : 9);
firstNameString.copy( firstName, length );
firstName[ length ] = '\0'; // append null character to firstName
} // end function setFirstName
// get balance value
double ClientData::getBalance() const {
return balance;
} // end function getBalance
// set balance value
void ClientData::setBalance(double balanceValue) {
balance = balanceValue;
} // end function setBalance
| true |
6aee59774a4f5c939888135f9eb9d872d7364818 | C++ | LnC-Study/Acmicpc-net | /__19 Summer Coding/1 택시/ckw_cpp.cpp | UTF-8 | 746 | 3.203125 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool desc(int a, int b) {
return a > b;
}
int solution(vector<int> s) {
int answer = 0;
vector<bool> taken = vector<bool>(s.size());
sort(s.begin(),s.end(),desc);
for (int i = 0; i < s.size(); i++) {
if (taken[i])
continue;
int left = 4;
left -= s[i];
taken[i] = true;
if (left == 0)//그룹이 4명일때
{
answer++;
continue;
}
for (int j = i; j < s.size(); j++) {
if (left - s[j] >= 0 && !taken[j]) {
left -= s[j];
taken[j] = true;
if (left == 0)//그룹이 4명일때
{
break;
}
}
}
answer++;
}
return answer;
}
| true |
ea44d4fa2acc0ff8fbae8f27c779832eb01e43f6 | C++ | tbilodea/Unreal-Cpp-TankGame | /TankGame/Source/TankGame/Private/Mortar.cpp | UTF-8 | 746 | 2.546875 | 3 | [] | no_license | // Copyright Bilodeau 2020
#include "Mortar.h"
// Sets default values
AMortar::AMortar()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
}
void AMortar::BeginPlay()
{
Super::BeginPlay();
CurrentHealth = StartingHealth;
}
float AMortar::GetHealthPercentage()
{
return (float)CurrentHealth/(float)StartingHealth;
}
float AMortar::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
int32 IntDamage = FPlatformMath::RoundToInt(Damage);
int32 ClampedDamage = FMath::Clamp(IntDamage, 0, CurrentHealth);
CurrentHealth -= ClampedDamage;
return ClampedDamage;
} | true |
3ff8797e019ac0d16c5ee4b5c6b299e5003a923b | C++ | adityanjr/cb_launchpad | /Class Lectures/Lecture07/sum_subArray.cpp | UTF-8 | 363 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int arr[5] = {5, 6, -7, 8, -9};
int maxsum = INT_MIN;
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
int sum = 0;
for (int k = i; k <= j; k++) {
sum += arr[k];
}
if (sum > maxsum) {
maxsum = sum;
}
}
}
cout << maxsum;
return 0;
}
| true |
702e532167dcb90f8f3f4aeaac745efd20801c9e | C++ | terrymunro/uni-work | /assignment-1/Question_2/RecursiveCalculator/RecursiveCalculator.cpp | UTF-8 | 4,309 | 3.40625 | 3 | [] | no_license | #include "RecursiveCalculator.h"
#include <cmath>
#include <cassert>
#include <iomanip>
#include <iostream>
RecursiveCalculator::RecursiveCalculator(int bufferSize)
{
bufferIndex = 0;
buffer = new char[bufferSize];
assert(buffer != NULL);
for (int i = 0; i < bufferSize; i++)
buffer[i] = 0;
}
RecursiveCalculator::~RecursiveCalculator()
{
delete [] buffer;
}
// - Each level indicates the order of operations from
// the top down. The grammar is as follows:
//
// factor = [+|-] number | ( expression )
// exponent = factor { [^] factor }
// term = exponent { [*|/] exponent }
// expression = [+|-] term { [+|-] term }
// answer = expression
double RecursiveCalculator::calculate(char const* expr)
{
double answer = 0;
input = expr;
symbol = getSymbol();
answer = expression();
expect(End);
return answer;
}
double RecursiveCalculator::expression()
{
double value = term();
while (symbol == Plus || symbol == Minus)
{
bool isPlus = symbol == Plus;
symbol = getSymbol();
if (isPlus) value += term();
else value -= term();
}
return value;
}
double RecursiveCalculator::term()
{
double value = exponent();
while (symbol == Multiply || symbol == Divide)
{
bool isMultiply = symbol == Multiply;
symbol = getSymbol();
if (isMultiply) value *= exponent();
else value /= exponent();
}
return value;
}
double RecursiveCalculator::exponent()
{
double value = factor();
while (symbol == Power)
{
symbol = getSymbol();
value = pow(value, factor());
}
return value;
}
double RecursiveCalculator::factor()
{
double value = 0;
if (accept(Number) || (accept(Plus) && accept(Number)))
{
value = getValueFromBuffer();
}
else if (accept(Minus) && accept(Number))
{
value = -getValueFromBuffer();
}
else if (accept(LParenthesis))
{
value = expression();
expect(RParenthesis);
}
else
{
error("Factor: Syntax error.");
symbol = getSymbol();
}
return value;
}
void RecursiveCalculator::readNumberIntoBuffer()
{
bool hasDecimal = false;
// rewind pointer to re-read first number discovered
--input;
// while still finding numbers add to buffer
while (isdigit(*input) || *input == '.')
{
if (*input == '.')
{
if (hasDecimal)
{
error("Number: Too many decimal marks.");
return;
}
hasDecimal = true;
}
buffer[bufferIndex++] = *input++;
}
}
RecursiveCalculator::Symbol RecursiveCalculator::getSymbol()
{
char sym = *input++;
switch (sym)
{
// accepted symbols
case '\0': return End;
case '+': return Plus;
case '-': return Minus;
case '*': return Multiply;
case '/': return Divide;
case '^': return Power;
case '(': return LParenthesis;
case ')': return RParenthesis;
// whitespace
case ' ': case '\t': case '\n':
case '\v': case '\f': case '\r':
return getSymbol();
// numbers
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
readNumberIntoBuffer();
return Number;
default:
error("Get Symbol: Unknown symbol.");
return Error;
}
}
double RecursiveCalculator::getValueFromBuffer()
{
double value = atof(buffer);
// Reset buffer
while (bufferIndex > 0)
buffer[--bufferIndex] = '\0';
return value;
}
void RecursiveCalculator::error(char const* errmsg)
{
std::cerr << "Error in " << errmsg << std::endl;
}
bool RecursiveCalculator::accept(Symbol s)
{
if (symbol == s)
{
if (symbol != End)
symbol = getSymbol();
return true;
}
return false;
}
bool RecursiveCalculator::expect(Symbol s)
{
bool accepted = accept(s);
if (!accepted)
error("Expect: Unexpected symbol");
return accepted;
} | true |
20ac12108e1f1f8bc19ef708dc1aed7eb4bae9b5 | C++ | alexkats/Code | /School/IOIP-2009/B/Help.cpp | UTF-8 | 1,038 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <time.h>
#include <cassert>
#include <assert.h>
#define DEBUG
#define ASSERT
#define NAME "Help"
using namespace std;
typedef long long LL;
LL n, a [100001];
void swap (LL &a, LL &b)
{
LL t = a;
a = b;
b = t;
}
void QSort (LL l, LL r)
{
LL i = l;
LL j = r;
LL x = a [l + rand () % (r - l)];
while (i <= j)
{
while (a [i] < x)
i++;
while (a [j] > x)
j--;
if (i <= j)
{
swap (a [i], a [j]);
i++;
j--;
}
}
if (l < j)
QSort (l, j);
if (i < r)
QSort (i, r);
}
int main ()
{
freopen (NAME".in", "r", stdin);
freopen (NAME".out", "w", stdout);
cin >> n;
for (LL i = 1, i <= n; i++)
cin >> a [i];
QSort (1, n);
for (LL i = 1; i <= n; i++)
cout << a [i] << " ";
cout << endl;
return 0;
} | true |
5677213b3ecc49c3ed1fb4a8b4920fed9fd31e40 | C++ | 3enceH/cv-algos | /core/src/cudaenv.cpp | UTF-8 | 834 | 2.84375 | 3 | [] | no_license | #include "cudaenv.h"
#include <iostream>
CUDAEnv::CUDAEnv() {
CHECK_CUDA(cudaGetDeviceCount(&_deviceCount));
CHECK(_deviceCount > 0, "No devices");
_deviceProps.resize(_deviceCount);
for (int i = 0; i < _deviceCount; i++)
CHECK_CUDA(cudaGetDeviceProperties(&_deviceProps[i], i));
cudaSetDevice(activeDeviceId);
}
void CUDAMemDeleter::operator()(void* ptr) {
CHECK_CUDA(cudaFree(ptr));
}
CUDAImage::CUDAImage(int width, int height) : width(width), height(height) {
init();
}
void CUDAImage::init(void* hostPtr /*= nullptr*/) {
void* devPtr;
size_t bytes = (size_t)width * height;
CHECK_CUDA(cudaMalloc(&devPtr, bytes));
devBuffer.reset(devPtr);
if (hostPtr != nullptr) {
CHECK_CUDA(cudaMemcpy(devPtr, hostPtr, bytes, cudaMemcpyKind::cudaMemcpyHostToDevice));
}
}
| true |
e074a97ac0d2445d7151e16ccab46bf3e510e68a | C++ | MarkRDavison/AdventOfCode | /test/2020/Day05PuzzleTests.cpp | UTF-8 | 648 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <catch/catch.hpp>
#include <2020/Day05Puzzle.hpp>
namespace TwentyTwenty {
TEST_CASE("Day 5 getSeatInfo works", "[2020][Day05]") {
const auto indexes = Day05Puzzle::getSeatInfo("FBFBBFFRLR");
REQUIRE(44 == indexes.row);
REQUIRE(5 == indexes.column);
REQUIRE(357 == indexes.seatId);
}
TEST_CASE("Day 5 Part 1 Example work", "[2020][Day05]") {
const std::vector<std::string> input = {
"BFFFBBFRRR",
"FFFBBBFRRR",
"BBFFBBFRLL"
};
Day05Puzzle puzzle{};
puzzle.setVerbose(true);
puzzle.setInputLines(input);
auto answers = puzzle.fastSolve();
REQUIRE("820" == answers.first);
}
}
| true |
fae54ba7bd0e5ca5f498310d43b2d8e7ac0975ae | C++ | TAKAYA888/PUTCORE | /ShootingGameFramework/ShootingGame/src/canTouch/GameObject/MainObject/Item/Item.cpp | SHIFT_JIS | 1,444 | 2.765625 | 3 | [] | no_license | #include "ItemScript.h"
ItemScript::ItemScript()
{
}
// t[Ă
void ItemScript::update()
{
// ړ
move();
// ̗͂OȉɂȂ
if (m_hp <= 0)
{
getComponent<SePlayer>().lock()->playSe();
// E
getGameObject().lock()->destroy();
}
}
// ՓˊJnŌĂ
void ItemScript::onCollisionEnter(GameObjectPtr other)
{
// Փˑ̃^OuGAME_OBJECT_TAG_PLAYER_BULLETv
if (other.lock()->getTag() == GAME_OBJECT_TAG_PLAYER_BULLET)
{
// ̗͂-1
m_hp--;
}
}
// Փ˒ŌĂ
void ItemScript::onCollisionStay(GameObjectPtr other)
{
// Փˑ̃^OuGAME_OBJECT_TAG_PLAYERv
if (other.lock()->getTag() == GAME_OBJECT_TAG_PLAYER)
{
// ̗͂-1
m_hp--;
}
}
// ՓˏIŌĂ
void ItemScript::onCollisionExit(GameObjectPtr other)
{
}
void ItemScript::handleMessage(int eventMessageType, SafetyVoidSmartPtr<std::weak_ptr> param)
{
if (eventMessageType == DIE_GAMEPLAY_OBJECT)
{
getGameObject().lock()->destroy();
}
}
// ړ
void ItemScript::move()
{
// g̉]px
float rotationDeg = getComponent<Transform2D>().lock()->getWorldRotationDeg();
// ړx{
auto velocity = Vector2(MathHelper::sin(rotationDeg), -MathHelper::cos(rotationDeg)) * 20.0f;
// ړ
getComponent<InertialMovement2D>().lock()->addForce(velocity);
} | true |
fd719d0c2ce467cd395ea39455d0d68927044354 | C++ | clarkok/parsical | /src/symbol-info.cpp | UTF-8 | 3,241 | 2.609375 | 3 | [] | no_license | #include "report.hpp"
#include "symbol-info.hpp"
#include "token-info.hpp"
using namespace parsical;
void
SymbolInfoVisitor::reportDuplicated(parser::TId *met, parser::TreeNode *prev)
{
Report::getReport().error(
Report::positionedMessage(
met->location,
"duplicated symbol: `" + met->literal + "\'",
"original defined at: " + Report::locationToString(prev->location)
)
);
}
void
SymbolInfoVisitor::reportMissing(parser::TId *met)
{
Report::getReport().error(
Report::positionedMessage(
met->location,
"met undefined symbol: `" + met->literal + "\'"
)
);
}
void
SymbolInfoVisitor::visit(parser::TokenRule_Rule1 *node)
{
if (_symbol_table.find(node->id->literal) != _symbol_table.end()) {
reportDuplicated(node->id.get(), _symbol_table[node->id->literal]);
}
_symbol_name[_symbol_id_counter] = node->id->literal;
_symbol_id[node->id->literal] = _symbol_id_counter++;
_symbol_table[node->id->literal] = node->regex.get();
}
void
SymbolInfoVisitor::visit(parser::TokenRule_Rule2 *node)
{
if (_symbol_table.find(node->id->literal) != _symbol_table.end()) {
reportDuplicated(node->id.get(), _symbol_table[node->id->literal]);
}
_symbol_name[_symbol_id_counter] = node->id->literal;
_symbol_id[node->id->literal] = _symbol_id_counter++;
_symbol_table[node->id->literal] = node->sentence_decl.get();
}
void
SymbolInfoVisitor::visit(parser::TokenRule_Rule3 *node)
{
if (_fragment_table.find(node->id->literal) != _fragment_table.end()) {
reportDuplicated(node->id.get(), _fragment_table[node->id->literal]);
}
if (_symbol_id.find(node->id->literal) == _symbol_id.end()) {
_symbol_name[_symbol_id_counter] = node->id->literal;
_symbol_id[node->id->literal] = _symbol_id_counter++;
}
_fragment_table[node->id->literal] = node->regex.get();
}
void
SymbolInfoVisitor::visit(parser::TokenRule_Rule4 *node)
{
if (_fragment_table.find(node->id->literal) != _fragment_table.end()) {
reportDuplicated(node->id.get(), _fragment_table[node->id->literal]);
}
if (_symbol_id.find(node->id->literal) == _symbol_id.end()) {
_symbol_name[_symbol_id_counter] = node->id->literal;
_symbol_id[node->id->literal] = _symbol_id_counter++;
}
_fragment_table[node->id->literal] = node->sentence_decl.get();
}
void
SymbolInfoVisitor::visit(parser::SentenceRule *node)
{
if (_symbol_table.find(node->id->literal) != _symbol_table.end()) {
reportDuplicated(node->id.get(), _symbol_table[node->id->literal]);
}
_symbol_name[_symbol_id_counter] = node->id->literal;
_symbol_id[node->id->literal] = _symbol_id_counter++;
_symbol_table[node->id->literal] = node->sentence_decl.get();
}
void
SymbolInfoVisitor::visit(parser::TString *node)
{
std::string original = "\"" + TokenInfoVisitorBase::recoverString(node) + "\"";
if (_symbol_table.find(original) != _symbol_table.end()) { return; }
_symbol_name[_symbol_id_counter] = original;
_symbol_id[original] = _symbol_id_counter++;
_symbol_table[original] = node;
}
| true |
33fd797ed66c374e85d6870b2e94aacfad0eeb61 | C++ | rossbishop/slabtop-power-management-system | /adapter.cpp | UTF-8 | 739 | 2.75 | 3 | [] | no_license | #include "adapter.h"
//CONSTANTS
//AC
#define AC_MIN_MILLIVOLTS 18000
#define MAX_CHARGER_CURRENT 14000
//constructor - create a function with same name as the class and no type
// could have some variables set in here
Adapter::Adapter()
{
}
bool Adapter::getStatus(Measure *measureRef)
{
if (getVoltage(measureRef) > AC_MIN_MILLIVOLTS)
{
return true;
}
else
{
return false;
}
}
String Adapter::getStatusString(Measure *measureRef)
{
return getStatus(measureRef) ? "T" : "F";
}
int Adapter::getVoltage(Measure *measureRef)
{
adapterVoltage = measureRef->getPinVoltage(ADAPTER_VOLTAGE_PIN);
return adapterVoltage;
}
int Adapter::getMaxChargerCurrent()
{
return MAX_CHARGER_CURRENT;
}
| true |
492320f0226b1f10d8a451826bebf241f534075b | C++ | plong0/openFrameworks | /addons/ofxImageColourIndexer/src/ofxImageColourIndexer.cpp | UTF-8 | 5,049 | 2.921875 | 3 | [] | no_license | /*
* ofxImageColourIndexer.cpp
* emptyExample
*
* Created by Eli Smiles on 11-03-16.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "ofxImageColourIndexer.h"
ofxImageColourIndexer::ofxImageColourIndexer(ofImage image){
myImage = image;
hasAverage = false;
hasPopular = false;
setPopularAverageCount();
setPopularAveragePercent();
setPopularThreshold();
}
ofxImageColourIndexer::~ofxImageColourIndexer(){
for(int i=0; i < colours.size(); i++){
delete colours[i];
colours[i] = NULL;
}
colours.clear();
}
void ofxImageColourIndexer::draw(float x, float y, float w, float h){
if(w < 0.0) w = myImage.getWidth();
if(h < 0.0) h = myImage.getHeight();
myImage.draw(x, y, w, h);
}
void ofxImageColourIndexer::calculateAverageColour(){
unsigned char* pixels = myImage.getPixels();
int width = myImage.getWidth();
int height = myImage.getHeight();
int bpp = myImage.bpp / 8;
averageColour.r = averageColour.g = averageColour.b = 0.0;
for(int i=0; i<width; i++){
for(int j=0; j<height; j++){
averageColour.r += pixels[ (j*width+i)*bpp + 0];
averageColour.g += pixels[ (j*width+i)*bpp + 1];
averageColour.b += pixels[ (j*width+i)*bpp + 2];
}
}
int pixCount = width*height;
averageColour.r /= (float)pixCount;
averageColour.g /= (float)pixCount;
averageColour.b /= (float)pixCount;
hasAverage = true;
}
void ofxImageColourIndexer::calculatePopularColour(){
unsigned char* pixels = myImage.getPixels();
int width = myImage.getWidth();
int height = myImage.getHeight();
int bpp = myImage.bpp / 8;
map<string,ColourCount*> colourCounts;
for(int i=0; i<width; i++){
for(int j=0; j<height; j++){
ofColor cColor;
cColor.r = pixels[ (j*width+i)*bpp + 0];
cColor.g = pixels[ (j*width+i)*bpp + 1];
cColor.b = pixels[ (j*width+i)*bpp + 2];
float cAvg = (float)(cColor.r + cColor.g + cColor.b) / 3.0;
bool rThresh = (cColor.r >= popularThreshLow && cColor.r <= popularThreshHigh);
bool gThresh = (cColor.g >= popularThreshLow && cColor.g <= popularThreshHigh);
bool bThresh = (cColor.b >= popularThreshLow && cColor.b <= popularThreshHigh);
bool avgThresh = (cAvg >= popularThreshLow && cAvg <= popularThreshHigh);
if(rThresh || gThresh || bThresh || avgThresh){
stringstream nameBuild;
nameBuild << cColor.r << "," << cColor.g << "," << cColor.b;
if(colourCounts.find(nameBuild.str()) == colourCounts.end()){
ColourCount* newOne = new ColourCount;
newOne->colour = cColor;
newOne->count = 1;
colourCounts[nameBuild.str()] = newOne;
colours.push_back(newOne);
}
else{
colourCounts[nameBuild.str()]->count++;
}
}
}
}
if(colours.size() > 0){
ColourCount sorter;
sort(colours.begin(), colours.end(), sorter);
popularColour = colours[0]->colour;
if(popularAveragePercent > 0.0)
popularColour = getPopularAverageColour(popularAveragePercent);
else if(popularAverageCount > 1)
popularColour = getPopularAverageColour(popularAverageCount);
}
hasPopular = true;
}
ofColor ofxImageColourIndexer::getAverageColour(bool doCalculate){
if(!hasAverage && doCalculate)
calculateAverageColour();
return averageColour;
}
ofColor ofxImageColourIndexer::getPopularColour(bool doCalculate){
if(!hasPopular && doCalculate)
calculatePopularColour();
return popularColour;
}
ofColor ofxImageColourIndexer::getPopularAverageColour(int useColours, bool doCalculate){
if(!hasPopular && doCalculate)
calculatePopularColour();
ofColor popularAverage = popularColour;
if(useColours > 0){
popularAverage.r = popularAverage.g = popularAverage.b = 0.0;
int usedColours = 0;
for(int i=0; i < useColours && i < colours.size(); i++){
popularAverage.r += colours[i]->colour.r;
popularAverage.g += colours[i]->colour.g;
popularAverage.b += colours[i]->colour.b;
usedColours++;
}
if(usedColours > 0){
popularAverage.r /= (float)usedColours;
popularAverage.g /= (float)usedColours;
popularAverage.b /= (float)usedColours;
}
}
return popularAverage;
}
ofColor ofxImageColourIndexer::getPopularAverageColour(float usePercent, bool doCalculate){
if(!hasPopular && doCalculate)
calculatePopularColour();
if(usePercent > 1.0) usePercent / 100.0;
int colourCount = (int)((float)colours.size() * usePercent);
return getPopularAverageColour(colourCount, doCalculate);
}
bool ofxImageColourIndexer::isAverageCalculated(){
return hasAverage;
}
bool ofxImageColourIndexer::isPopularCalculated(){
return hasPopular;
}
void ofxImageColourIndexer::setPopularAverageCount(int popularAverageCount){
this->popularAverageCount = popularAverageCount;
}
void ofxImageColourIndexer::setPopularAveragePercent(float popularAveragePercent){
if(popularAveragePercent > 1.0) popularAveragePercent /= 100.0;
this->popularAveragePercent = popularAveragePercent;
}
void ofxImageColourIndexer::setPopularThreshold(float popularThreshLow, float popularThreshHigh){
this->popularThreshLow = popularThreshLow;
this->popularThreshHigh = popularThreshHigh;
}
| true |
de8846c193c4327bfdc7c75e7902dd797ab5c8ba | C++ | TashreefMuhammad/UVA_Problem_Solutions | /UVA_00913.cpp | UTF-8 | 314 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
int main(void)
{
long long n;
while(scanf("%lld", &n) != EOF)
{
if(n == 1)
printf("1\n");
else
{
n = (n+1)>>1;
n *= n;
printf("%lld\n", n*n - (n-3)*(n-3));
}
}
return 0;
}
| true |
3fe818a1ee2a78c201f220b5a86a9f5d81ee5a49 | C++ | Lyd1995/Leetcode | /C++/1281. 整数的各位积和之差.cpp | UTF-8 | 723 | 2.953125 | 3 | [] | no_license | #include<algorithm>
#include<stdio.h>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<math.h>
using namespace std;
class Solution {
public:
int subtractProductAndSum(int n) {
int ans, sum = 0, acc = 1;
vector<int> nums;
helper(n, nums);
for(int i=0; i < nums.size(); i++){
sum += nums[i];
acc *= nums[i];
}
ans = acc - sum;
return ans;
}
void helper(int n, vector<int>& nums){
if(n == 0){
nums.push_back(0);
return;
}
while(n != 0){
nums.push_back(n % 10);
n /= 10;
}
return;
}
}; | true |
9fd8e9d424bc47662e409cf0c6ae32f9e5876a8f | C++ | concatto/sfml-experiments | /SFML/MovementManager.h | UTF-8 | 902 | 2.984375 | 3 | [] | no_license | #ifndef MOVEMENTMANAGER_H
#define MOVEMENTMANAGER_H
#include "Character.h"
#include "Updatable.h"
#include "World.h"
#include <SFML/Graphics.hpp>
class MovementManager : public Updatable
{
const float Gravity = 0.5;
enum Direction {Up, Down, Left, Right};
const World& world;
Character& character;
public:
MovementManager(const World& world, Character& character);
virtual void update() override;
void moveCharacter(Character& character, float distance, Direction direction);
private:
static inline float distance(sf::Vector2i coords, sf::Vector2f tileSize, sf::IntRect box, Direction direction);
static inline sf::Vector2f boundingBoxPoint(sf::IntRect box, float delta, Direction direction);
static inline sf::Vector2i directionOffset(Direction direction);
int calculateDistance(const Character& c, Direction direction);
};
#endif // MOVEMENTMANAGER_H
| true |
4114aaa61448f52ceb70be24790aacf21b7881d8 | C++ | vsuley/Alight | /Mesh.h | UTF-8 | 873 | 2.609375 | 3 | [] | no_license | // Mesh.h: interface for the CMesh class.
//
//////////////////////////////////////////////////////////////////////
# ifndef _MESH_H
# define _MESH_H
# include "Shape.h"
# include "Triangle.h"
class CMesh : public CShape
{
public:
CMesh (CPoint3D pos, CColor col, CPoint3D *pptVertices, CVector *pvecNormals, unsigned int *ppiFaces[3], int iVertexCount, int iFaceCount);
CMesh (CPoint3D pos, CColor col, CPoint3D *pptVertices, unsigned int ppiFaces[][3], int iVertexCount, int iFaceCount);
CMesh (CMesh &mesh1);
// Object interface
CIntersectionInfo GetIntersection (CRay ray);
CVector GetNormalAt (CPoint3D pt);
CColor ShadePoint (CIntersectionInfo hitInfo);
CTexCoords GetTexCoords (CPoint3D ptOfIntersection);
// Destruction
virtual ~CMesh();
protected:
NORMAL_MODE m_eNormalMode;
CTriangle *m_pTriangles;
int m_iTriangleCount;
};
# endif | true |
d5ffd6ca244993a12f4767edf6865ef87195d7c7 | C++ | alexandraback/datacollection | /solutions_5690574640250880_0/C++/nick993/2_1.cpp | UTF-8 | 4,017 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <string.h>
using namespace std;
int posx[9]={-1 ,-1, -1,0,0,0,1,1,1 };
int posy[9]={-1,0,1,-1,1,0,-1,0,1};
int ansBoard[50][50];
bool isValidPos(pair<int,int> loc,int board[50][50],int rows,int cols)
{
if(loc.first<0 || loc.second<0 || loc.first>=rows ||loc.second>=cols)
return false;
if(board[loc.first][loc.second])
return false;
return true;
}
bool isValidPos1(pair<int,int> loc,int board[50][50],int rows,int cols)
{
if(loc.first<0 || loc.second<0 || loc.first>=rows ||loc.second>=cols)
return false;
if(board[loc.first][loc.second]==1)
return true;
return false;
}
int Rec1(int board[50][50],pair<int,int> loc,int rows,int cols,int not_mines,int zeros)
{
if(!isValidPos1(loc,board,rows,cols))
return -1;
int zerosTemp=0;
board[loc.first][loc.second]=2;
/*for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
cout<<board[i][j]<<' ';
cout<<endl;
}*/
for(int i=0;i<9;i++)
{
pair<int,int> locTemp(loc.first+posx[i],loc.second+posy[i]);
if(isValidPos(locTemp,board,rows,cols)){
zerosTemp++;
board[locTemp.first][locTemp.second]=1;
}
}
/* cout<<"After Processing :"<<endl;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
cout<<board[i][j]<<' ';
cout<<endl;
}*/
if(zeros+zerosTemp>not_mines)
return -1;
if(zeros+zerosTemp==not_mines){
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
ansBoard[i][j]=board[i][j];
return not_mines;
}
//cout<<"Zeros Temp :"<<zeros+zerosTemp<<endl;
int num=-1;
for(int i=0;i<9;i++)
{
int boardTemp[50][50];
memset(boardTemp,0,sizeof(boardTemp));
for(int i1=0;i1<rows;i1++)
{
for(int j1=0;j1<cols;j1++)
boardTemp[i1][j1]=board[i1][j1];
}
pair<int,int> locTemp(loc.first+posx[i],loc.second+posy[i]);
num=Rec1(boardTemp,locTemp,rows,cols,not_mines,zeros+zerosTemp);
if(num==not_mines)
return num;
}
return -1;
}
int main()
{
int T;
cin>>T;
int I=0;
int board[50][50];
while(T--)
{
I++;
int R,C,M,K;
cin>>R>>C>>M;
// cout<<"MAT :"<<R<<' '<<C<<' '<<M<<endl;
K=R*C-M;
pair<int,int> startPos;
// memset(board,0,sizeof(board));
memset(ansBoard,0,sizeof(ansBoard));
bool solFound=false;
if(K==1)
{
solFound=true;
startPos.first=0;
startPos.second=0;
}
else{
for(int i=0;i<R;i++)
{
for(int j=0;j<C;j++)
{
// cout<<"For Location : "<<i<<' '<<j<<endl;
memset(board,0,sizeof(board));
pair<int,int> loc(i,j);
board[i][j]=1;
if(Rec1(board,loc,R,C,K,1)!=-1)
{
startPos.first=i;
startPos.second=j;
solFound=true;
break;
}
}
if(solFound)
break;
}
}
cout<<"Case #"<<I<<':'<<endl;
if(solFound){
for(int i=0;i<R;i++)
{
for(int j=0;j<C;j++)
{
if(i==startPos.first && j==startPos.second)
cout<<'c';
else if(ansBoard[i][j]==0)
cout<<'*';
else
cout<<'.';
}
cout<<endl;
}
}
else
cout<<"Impossible"<<endl;
}
}
| true |
01ed8856a3f62867abc9f6161404cf9180642ebf | C++ | Folleas/CCP_plazza_2019 | /src/Encapsulation/ThreadPool.cpp | UTF-8 | 2,784 | 3.0625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2020
** CCP_plazza_2019
** File description:
** ThreadPool
*/
#include "Encapsulation/ThreadPool.hpp"
#include <chrono>
#include <iostream>
Plazza::Encapsulation::ThreadPool::ThreadPool(std::size_t threads) : _workers(),
_taskQueue(),
_taskCount(0u),
_mutex(),
_condition(),
_stop(false)
{
initThreads(threads);
}
Plazza::Encapsulation::ThreadPool::~ThreadPool()
{
_stop = true;
_condition.notify_all();
for (auto &worker: _workers) {
worker.join();
}
}
std::function<std::string()> Plazza::Encapsulation::ThreadPool::assignTask()
{
std::unique_lock<std::mutex> lock(_mutex);
std::function<std::string()> newTask;
_condition.wait(lock, [this]() -> bool { return !_taskQueue.empty() || _stop;});
if (_stop && _taskQueue.empty()) {
newTask = nullptr;
return (newTask);
}
newTask = std::move(_taskQueue.front());
_taskQueue.pop();
return (newTask);
}
std::size_t Plazza::Encapsulation::ThreadPool::resultSize()
{
return (this->_result.size());
}
std::string Plazza::Encapsulation::ThreadPool::popResult()
{
std::unique_lock<std::mutex> lock(_mutex);
std::string tmp;
if (!this->_result.empty()) {
tmp.assign(this->_result.front());
this->_result.pop();
}
else {
tmp = "";
}
return(tmp);
}
void Plazza::Encapsulation::ThreadPool::pushResult(std::string newResult)
{
std::unique_lock<std::mutex> lock(_mutex);
this->_result.push(newResult);
}
void Plazza::Encapsulation::ThreadPool::initThreads(std::size_t threads)
{
for (size_t i = 0; i < threads; i++) {
_workers.emplace_back([this]() -> void {
while (true) {
std::function<std::string()> task = assignTask();
if (task == nullptr)
return;
std::string tmp = (task());
this->pushResult(tmp);
_taskCount--;
}
});
}
}
void Plazza::Encapsulation::ThreadPool::pushTask(const std::function<std::string()>& task)
{
std::unique_lock<std::mutex> lock(_mutex);
_taskQueue.push(task);
}
void Plazza::Encapsulation::ThreadPool::pushOrder(const std::function<std::string()>& task)
{
this->pushTask(task);
_taskCount++;
_condition.notify_one();
}
void Plazza::Encapsulation::ThreadPool::waitTasksEnd() const
{
while (_taskCount != 0u) {
std::this_thread::yield();
}
} | true |
807886a53736a4027859d3decb056ce65a76a9f8 | C++ | x3ent3nte/SimulationProject | /src/Simulator/InsertionSorter.h | UTF-8 | 1,656 | 2.515625 | 3 | [] | no_license | #ifndef INSERTION_SORTER_H
#define INSERTION_SORTER_H
#include <Utils/ShaderFunction.h>
#include <vulkan/vulkan.h>
#include <vector>
class InsertionSorter {
private:
VkPhysicalDevice m_physicalDevice;
VkDevice m_logicalDevice;
VkQueue m_queue;
VkCommandPool m_commandPool;
VkBuffer m_wasSwappedBuffer;
VkBuffer m_wasSwappedBufferHostVisible;
VkBuffer m_numberOfElementsBuffer;
VkBuffer m_numberOfElementsBufferHostVisible;
VkBuffer m_offsetOneBuffer;
VkBuffer m_offsetTwoBuffer;
VkDeviceMemory m_valueAndIndexBufferMemory;
VkDeviceMemory m_wasSwappedBufferMemory;
VkDeviceMemory m_wasSwappedBufferMemoryHostVisible;
VkDeviceMemory m_numberOfElementsBufferMemory;
VkDeviceMemory m_numberOfElementsBufferMemoryHostVisible;
VkDeviceMemory m_offsetOneBufferMemory;
VkDeviceMemory m_offsetTwoBufferMemory;
std::shared_ptr<ShaderLambda> m_lambdaOne;
std::shared_ptr<ShaderLambda> m_lambdaTwo;
VkCommandBuffer m_commandBuffer;
VkCommandBuffer m_setNumberOfElementsCommandBuffer;
VkSemaphore m_semaphore;
VkFence m_fence;
void setNumberOfElements(uint32_t numberOfElements);
void createCommandBuffer(uint32_t numberOfElements);
void setWasSwappedToZero();
uint32_t needsSorting();
uint32_t m_currentNumberOfElements;
public:
VkBuffer m_valueAndIndexBuffer;
InsertionSorter(
VkPhysicalDevice physicalDevice,
VkDevice logicalDevice,
VkQueue queue,
VkCommandPool commandPool,
uint32_t numberOfElements);
virtual ~InsertionSorter();
void run(uint32_t numberOfElements);
};
#endif
| true |
450df17092a94890725c0766fbfe023e3df15f8a | C++ | chinlin0514/CLEOD | /aseparation/Frontend/Scanner.h | UTF-8 | 1,788 | 3.0625 | 3 | [] | no_license | //
// Created by jonwi on 10/7/2019.
//
#ifndef CLEOD_SCANNER_H
#define CLEOD_SCANNER_H
#include <fstream>
#include <sstream>
#include "Token.h"
class Scanner {
private:
// Private variables
int start = 0;
int current = 0;
uint64_t line = 1;
char c; // character in the source file
std::string text; // the substring that is recognized as token = token data
std::string source; // copy of the source file as string
std::vector<Token> tokens; // vector of tokens
std::ifstream src; // Constructor should initialize this.
std::stringstream buffer; // buffer that holds the contents of file
std::unordered_map<std::string, TokenType> keywords = { // mapping keywords to TokenType
{"true", TokenType::TRUE},
{"false", TokenType::FALSE},
{"print", TokenType::PRINT},
{"if", TokenType::IF},
{"else", TokenType::ELSE},
{"for", TokenType::FOR},
{"return", TokenType::RETURN},
{"while", TokenType::WHILE},
{"switch", TokenType::SWITCH},
{"case", TokenType::CASE}
};
// Helper functions:
bool isAtEnd();
void scanToken(); // maps character to appropriate TokenType
char advance(); // advancing character by character
void addToken(TokenType type); // adds token to token vector
bool match(char ch); // checks if next character is ch
char peek();
char peekNext();
void stringFunc(); // recognizing string literal
void numberFunc(); // recognizing number literal
void identifier(); // recognizing identifier
public:
// Constructor for Scanner class
explicit Scanner(const std::string &sourceFileName);
std::vector<Token> scanTokens();
};
#endif //CLEOD_SCANNER_H
| true |
a8e270011937acecb2b57aa00b91a32a09f4c562 | C++ | k-Enterprises/Rohan-codes | /linkedList/deleteNodeRecursively/deleteNodeRecursively.cpp | UTF-8 | 1,020 | 3.9375 | 4 | [] | no_license | #include <iostream>
using namespace std;
#include "Node.cpp"
Node * takeInput() {
int data;
cout << "Enter the data: ";
cin >> data;
Node * head = NULL;
Node * tail = NULL;
while(data != -1) {
Node * newNode = new Node(data);
if(head == NULL) {
head = newNode;
tail = newNode;
} else {
tail -> next = newNode;
tail = newNode;
}
cin >> data;
}
return head;
}
void printList(Node * head) {
Node * temp = head;
while(temp != NULL) {
cout << temp -> data << " ";
temp = temp -> next;
}
cout << endl;
}
Node * deleteNode(Node * head, int index) {
if(head == NULL) {
return head;
}
if(index == 0) {
Node * temp = head;
head = head -> next;
delete temp;
return head;
} else {
Node * x = deleteNode(head -> next, index - 1);
head -> next = x;
return head;
}
}
int main() {
Node * head = takeInput();
printList(head);
int index;
cout << "Enter the index of node you want to delete: ";
cin >> index;
head = deleteNode(head, index);
printList(head);
return 0;
}
| true |
dbfe2d123e4ff18e86676c70beeaef682a6cd625 | C++ | AnthonyG1371/College-Assignments | /Data Structures/Lecture5/01-sorted_ops/main.cpp | UTF-8 | 788 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include "node.h"
#include "node_utils.h"
using namespace std;
int main() {
Node *list = new Node(1, new Node(3, new Node(5)));
//Prints Lists Contents
cout << "Initial List of Nodes 1,3,5" << endl;
Node *templist = list;
while (list) {
cout << *list;
list = list->next;
if (list) cout << " -> ";
}
list = templist;
cout << endl << endl;
insert(list, 2);
cout << "Testing Insertion of 2: " << endl;
while (list) {
cout << *list;
list = list->next;
if (list) cout << " -> ";
}
list = templist;
newremove(list, 5);
cout << endl << endl;
cout << "Testing Removal of 5:" << endl;
while (list) {
cout << *list;
list = list->next;
if (list) cout << " -> ";
}
cout << endl << endl;
system("pause");
return 0;
}
| true |
dfbb8500048565364f80ad1afdcb73ec32b08601 | C++ | VitKad/Pac-man | /Curs/Player.cpp | WINDOWS-1251 | 3,041 | 3 | 3 | [] | no_license | #include "stdafx.h"
#include "Player.h"
using namespace sf;
Player::Player(Image &image, float X, float Y, int W, int H) :Entity(image, X, Y, W, H)
{
playerScore = 0;
dir = 1;
sprite.setTextureRect(IntRect(0, 0, w, h));
}
int Player::getScore()
{
return(playerScore);
}
void Player::setScore(int score)
{
playerScore = score;
}
void Player::control()
{ // ,
if (Keyboard::isKeyPressed(Keyboard::Left))
{
dx = -0.1;
}
if (Keyboard::isKeyPressed(Keyboard::Right))
{
dx = 0.1;
}
if (Keyboard::isKeyPressed(Keyboard::Up))
{
dy = -0.1;
}
if (Keyboard::isKeyPressed(Keyboard::Down))
{
dy = 0.1;
}
}
void Player::checkCollisionWithMap(float Dx, float Dy)
{
for (int i = y / 32; i < (y + h) / 32; i++)//
for (int j = x / 32; j<(x + w) / 32; j++)
{
if (mp.TileMap[i][j] == '0')//
{
if ((Dy > 0) && (dir == 2)) { y = i * 32 - h; dy = 0; }//
if ((Dy < 0) && (dir == 2)){ y = i * 32 + 32; dy = 0; }//
if ((Dx > 0) && (dir == 1)) { x = j * 32 - w; dx = 0; }//
if ((Dx < 0) && (dir == 1)) { x = j * 32 + 32; dx = 0; }//
}
if (mp.TileMap[i][j] == 's')
{
setScore(++playerScore); //
mp.TileMap[i][j] = ' ';
}
}
}
void Player::update(float time)// .
{
if (life)
{//,
control();
x += dx*time; // X
dir = 1;
checkCollisionWithMap(dx, 0);//
y += dy*time; // Y
dir = 2;
checkCollisionWithMap(0, dy);// Y
if (dx > 0) {//
dx = speed;
dy = 0;
CurrentFrame += 0.005*time;
if (CurrentFrame > 3) CurrentFrame -= 3;
sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 0, 32, 32));
}
if (dx < 0)
{//
dx = -speed;
dy = 0;
CurrentFrame += 0.005*time;
if (CurrentFrame > 3) CurrentFrame -= 3;
sprite.setTextureRect(IntRect(32 * int(CurrentFrame) + 32, 0, -32, 32));
}
if (dy < 0)
{//
dy = -speed;
dx = 0;
CurrentFrame += 0.005*time;
if (CurrentFrame > 3) CurrentFrame -= 3;
sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 32, 32, 32));
}
if (dy > 0)
{//
dy = speed;
dx = 0;
CurrentFrame += 0.005*time;
if (CurrentFrame > 3) CurrentFrame -= 3;
sprite.setTextureRect(IntRect(32 * int(CurrentFrame), 64, 32, 32));
}
}
sprite.setPosition(x, y); // (x, y).
} | true |
d85fd1c3e47691b6cbd597bcffef1894d1486035 | C++ | zalandemeter12/Barkochba | /binarytree.h | UTF-8 | 3,599 | 3.171875 | 3 | [] | no_license | #ifndef BARKOCHBA_BINARYTREE_H
#define BARKOCHBA_BINARYTREE_H
/// \file binarytree.h
#include <string>
/// Bináris fa elemet megvalósító osztály.
/// Dinamikus példányai keletkeznek, amik a
/// BinárisFa osztály destruktorában szabadulnak fel.
class BinaryTreeElement{
protected:
std::string text; ///< A kérdés vagy dolog szövegét tárolja el
BinaryTreeElement* parent; ///< Szülőre mutató pointer
public:
/// Konstruktor, alapértelmezetten a szülőpointert nullptr-el inicializálja.
/// @param _text - a kérdés szövege, vagy a dolog neve
/// @param _parent - szülőpointer
explicit BinaryTreeElement(const std::string& _text, BinaryTreeElement* _parent = nullptr) : text(_text), parent(_parent) {}
/// Virtuális destruktor.
virtual ~BinaryTreeElement() {}
/// A kérdés, vagy dolog szövegét adja vissza.
std::string getText() const { return text; }
/// A szülőpointert adja vissza.
BinaryTreeElement* getParent() const { return parent; }
/// A baloldali igaz irány következő elemére mutató pointert adja vissza.
virtual BinaryTreeElement* getLeftTrue() const = 0;
/// A jobboldali hamis irány következő elemére mutató pointert adja vissza.
virtual BinaryTreeElement* getRightFalse() const = 0;
/// A kérdés, vagy dolog szövegét állítja be.
/// @param _text - beállítandó szöveg
void setText(const std::string& _text) { text = _text; }
/// A szülő pointert állítja be.
/// @param _parent - beállítandó pointer
void setParent(BinaryTreeElement* _parent) { parent = _parent; }
/// A baloldali igaz irányú pointert állítja be.
/// @param _parent - beállítandó pointer
virtual void setLeftTrue(BinaryTreeElement* _left) {}
/// A jobboldali hamis irányú pointert állítja be.
/// @param _parent - beállítandó pointer
virtual void setRightFalse(BinaryTreeElement* _right) {}
/// Felteszi a kérdést, vagy rákérdez a dologra.
virtual void askQuestion() = 0 ;
/// Hozzáad egy új kérdést az adatbázishoz.
void addQuestion();
/// Sztringgé alakítja az adatbázist.
std::string serialize() const;
};
/// Bináris fát megvalósító osztály.
class BinaryTree {
private:
BinaryTreeElement* root; ///< a fa gyökerére mutató pointer
public:
/// Konstruktor, alapértelmezetten a gyökérpointert nullptr-el inicializálja.
BinaryTree() : root(nullptr) {}
/// A bináris fa felszabadítását végző rekurzív függvény.
/// @param _root - a felszabadítandó fa gyökerére mutató pointer
void freeBinaryTree (BinaryTreeElement* _root);
/// Destruktor
~BinaryTree() { freeBinaryTree(root); };
/// A gyökérpointert adja vissza.
BinaryTreeElement* getRoot(){ return root; }
//// A gyökérpointert állítja be.
/// @param _root - beállítandó pointer
void setRoot(BinaryTreeElement* _root) { root = _root; };
/// Elindít egy új játékot.
void newGame();
/// Elmenti az adatbázist.
void save(const std::string& file) const;
/// Betölti az adatbázist.
void load(const std::string& file);
/// Az adatbázis sztringből való visszatöltését segítő rekurzív függvény.
/// @param is - beolvasni kívánt adatfolyam
/// @param parent - létrehozott példány szülöpointere
BinaryTreeElement* deserialize(std::istream& is, BinaryTreeElement* parent = nullptr);
};
#endif //BARKOCHBA_BINARYTREE_H
| true |
8fb8f581c5ac7358a94e9c43f5f7ca4b56a24c62 | C++ | geo000/clustering-1 | /src/kmeans.h | UTF-8 | 1,642 | 2.84375 | 3 | [] | no_license | #ifndef __KMEANS_H__
#define __KMEANS_H__
#include<limits>
template <typename S, typename T>
void kmeans(const Matrix<S> &pts, const u32 nclusters, Vec<u8> &labels, Matrix<T> &clusters) {
bool change;
double mind, d;
u8 minl;
Vec<S> pt;
Vec<float> mean;
u32 dim = pts.cols();
u32 npts = pts.rows();
u32 count;
// check nclusters
if (nclusters <= 0)
throw Exception("kmeans must have nclusters > 0");
// assign each pts to a random label
labels.init(npts);
for(u32 i = 0; i < labels.len(); i++) labels[i] = i % nclusters;
// kmeans algo loop
mean.init(dim);
clusters.init(nclusters, dim);
do {
// assume perfect labeling
change = false;
// compute means of each cluster
for(u32 i = 0; i < nclusters; i++) {
mean.zero();
count = 0;
for(u32 j = 0; j < npts; j++) {
if (labels[j] == i) {
mean += pts.getrow(j); // add point to mean
count++;
}
}
// put mean in cluster matrix
mean /= (double)count;
clusters.setrow(i, mean);
}
// update labels for each pt to nearest cluster, flag if any change
for(u32 i = 0; i < npts; i++) {
pt = pts.getrow(i);
mind = std::numeric_limits<double>::max();
for(u32 j = 0; j < nclusters; j++) {
d = (pt - clusters.getrow(j)).norm();
if (d < mind) {
mind = d;
minl = j;
}
}
if (minl != labels[i]) {
change = true;
labels[i] = minl;
}
}
} while (change);
}
#endif // __KMEANS_H__
| true |
095817cbe0c56668873ba4d13c89215d204035f5 | C++ | unbgames/Lucity | /game/src/TileSet.cpp | UTF-8 | 757 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "TileSet.h"
TileSet::TileSet(GameObject& associated, std::string file, int tileWidth, int tileHeight) : tileSet(associated, file) {
TileSet::tileWidth = tileWidth;
TileSet::tileHeight = tileHeight;
rows = tileSet.GetHeight()/tileHeight;
columns = tileSet.GetWidth()/tileWidth;
}
TileSet::~TileSet() {
}
void TileSet::SetTileSet(std::string file) {
tileSet.Open(file);
}
void TileSet::RenderTile(int index, int x, int y) {
if(index > -1 && index < rows*columns) {
int clipX = tileWidth*(index%columns);
int clipY = tileHeight*(index/columns);
tileSet.SetClip(clipX, clipY, tileWidth, tileHeight);
tileSet.Render(x, y);
}
}
int TileSet::GetTileWidth() {
return tileWidth;
}
int TileSet::GetTileHeight() {
return tileHeight;
}
| true |
b2d5d525620180faae4091d4ab8464353047fb81 | C++ | zakaryael/Projet-cpp | /validation1.cpp | UTF-8 | 1,499 | 3.296875 | 3 | [] | no_license | #include "Vecteur.h"
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char const *argv[]) {
/* code */
//1 creation et affichage de u et v:
float u_t[3] = {1, 1, 1};
Vecteur u(3, u_t);
cout << "Affichage du vecteur u: \n";
u.affiche();
float v_t[4] = {3, 4, 0, 0};
Vecteur v(4, v_t);
cout << "\nAffichage du vecteur v: \n";
v.affiche();
//2.copie du vecteur u dans t:
Vecteur t(u);
cout << "\n \nAffichage du vecteur t: \n";
t.affiche();
//3.modification de u et affichage de u et t:
u[2] = 0;
cout << "\n \nAffichage du vecteur u modifié: \n";
u.affiche();
cout << "\nAffichage du vecteur t après modification de u: \n \n";
t.affiche();
//4.Calcul du produit scalair v'v:
float produit = v.dot(v);
cout << "le produit vTv: " << produit << endl;
float norm_v = v.norm();
//5.calcul et affichage de v / norm(v):
float alpha = 1 / norm_v;
Vecteur unit = v * alpha;
cout << "\n \n Affichage de v / norm(v): \n";
unit.affiche();
assert(unit.norm() == 1); // s'assurer que u est un vecteur unitair
//6.clacul de w et affichage de v et w:
Vecteur w = v.subvec(1,3);
cout << "\n \n Affichage de v: \n";
v.affiche();
cout << "\n \n Affichage de w: \n";
w.affiche();
//7. calcul et affichage de u+w et u-w
Vecteur uplusw = u + w;
Vecteur umoinsw = u - w;
cout << "\n \n Affichage de u+w: \n";
uplusw.affiche();
cout << "\n \n Affichage de u-w: \n";
umoinsw.affiche();
return 0;
}
| true |
716b6f385657ff6047263920f9fb2be6c92b9361 | C++ | kiranmuddam/leetcode | /google-online-assessment/394347.cpp | UTF-8 | 1,768 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class wateringPlants {
public:
static int findTotalRefills(vector<long long int> plantWeights, int capacity1, int capacity2) {
long long int currCapacity1 = 0;
long long int currcapacity2 = 0;
int totalRefills = 0;
if (plantWeights.size() == 1) {
cout << 1 << endl;
return 1;
}
for (int i = 0; i < plantWeights.size() / 2; i++) {
if (plantWeights[i] > currCapacity1) {
currCapacity1 = capacity1;
totalRefills++;
}
currCapacity1 = currCapacity1 - plantWeights[i];
long long int currWeight = plantWeights[plantWeights.size() - 1 - i];
if (currWeight > currcapacity2) {
currcapacity2 = capacity2;
totalRefills++;
}
currcapacity2 = currcapacity2 - currWeight;
//cout << "curr1 : " << currCapacity1 << endl;
//cout << "curr2 : " << currcapacity2 << endl;
}
if (plantWeights.size() % 2 == 1) {
if (currCapacity1 + currcapacity2 < plantWeights[(plantWeights.size() / 2) + 1]) {
totalRefills++;
}
}
cout << totalRefills << endl;
return totalRefills;
}
};
int main(int argv, char *argc[]) {
vector<long long int> inputArray = {2};
wateringPlants::findTotalRefills(inputArray, 2, 2);
inputArray = {2, 4, 5, 1, 2};
wateringPlants::findTotalRefills(inputArray, 5, 7);
inputArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1};
wateringPlants::findTotalRefills(inputArray, 9, 9);
} | true |
4de1674c667f01fc4fef432e5c52340bdb431123 | C++ | nnshi-s/TTMPPreviewer | /TTMPFile/inc/DxtUtil.h | UTF-8 | 2,093 | 2.671875 | 3 | [] | no_license | //#pragma once
//#include <cstdint>
//#include <memory>
//
//namespace Tt
//{
// // adopted from https://stackoverflow.com/questions/19016099/lookup-table-with-constexpr
// template <int AnyNumber>
// struct LookupTables
// {
// constexpr LookupTables() : rb5To8(), g5To8()
// {
// for (unsigned i = 0; i != 32; ++i)
// rb5To8[i] = static_cast<uint8_t>(i * 255.0 / 31.0 + 0.5);
// for (unsigned i = 0; i != 64; ++i)
// g5To8[i] = static_cast<uint8_t>(i * 255.0 / 63.0 + 0.5);
// }
//
// uint8_t rb5To8[32];
// uint8_t g5To8[64];
// };
//
// // adopted from xivModdingFramework.Helpers.DxtUtil
// class DxtUtil
// {
// public:
// static std::unique_ptr<char[]> decompressDxt1(const char *pSrc, int32_t width, int32_t height);
// static DxtUtil& getSingleton();
//
// static void convertRgb565ToRgb888(uint16_t color, uint8_t &r, uint8_t &g, uint8_t &b)
// {
// // RGB565 format uses 16 bits to store rgb color
// // 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
// // R R R R R G G G G G G B B B B B
// // RGB888 format use 24 bits to store rgb color
// // 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
// // B B B B B B B B G G G G G G G G R R R R R R R R
// // However, color value in rgb565 has only 32 different values for r & b, 64 different values for g.
// // so we need to scale r & b by 255/31, scale g by 255/63.
// // we use a lookup table to speed this up.
//
// r = color >> 11;
// g = (color & 0x07E0) >> 5;
// b = color & 0x001F;
// r = LOOKUP_TABLE.rb5To8[r];
// g = LOOKUP_TABLE.g5To8[g];
// b = LOOKUP_TABLE.rb5To8[b];
// }
//
// // static void convertRgb565ToRgb888Dynamic(uint16_t color, uint8_t &r, uint8_t &g, uint8_t &b);
// static constexpr auto LOOKUP_TABLE = LookupTables<1>();
// private:
// DxtUtil() = default;
// ~DxtUtil() = default;
// public:
// DxtUtil(const DxtUtil &) = delete;
// DxtUtil(DxtUtil &&) = delete;
// DxtUtil& operator=(const DxtUtil &) = delete;
// DxtUtil& operator=(DxtUtil &&) = delete;
// };
//}
| true |
56ed4700418a7bd8cf461ba14ca03fd23927caed | C++ | geakw/ServerSocket | /src/Server.cpp | GB18030 | 1,466 | 2.859375 | 3 | [] | no_license | #include <stdio.h>
#include <winsock2.h>
#include <iostream>
int main(int argc, char* argv[])
{
//ʼWSA
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(sockVersion, &wsaData) != 0)
{
return 0;
}
//
SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (slisten == INVALID_SOCKET)
{
printf("socket error !");
return 0;
}
//IPͶ˿
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(slisten, (SOCKADDR *)&sin, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
printf("bind error !");
}
//ʼ
if (listen(slisten, 5) == SOCKET_ERROR)
{
printf("listen error !");
return 0;
}
//ѭ
SOCKET sClient;
SOCKADDR_IN buffptr;;
int nAddrlen = sizeof(SOCKADDR);
char revData[255];
std::cout << "Wait for connections...\n";
sClient = accept(slisten, (SOCKADDR *)&buffptr, &nAddrlen);
if (sClient == INVALID_SOCKET)
{
std::cout << "accept error !";
}
std::cout << "Received one connection\n";
while (true)
{
//
int ret = recv(sClient, revData, 255, 0);
if (ret > 0)
{
revData[ret] = 0x00;
std::cout << revData;
std::cout << "\n";
}
//
// char * sendData = "Hello, this is TCP Server\n";
// send(sClient, sendData, strlen(sendData), 0);
// closesocket(sClient);
}
closesocket(slisten);
WSACleanup();
return 0;
}
| true |
d1388e0e750c9ebff515ab4f1f8cb79774086955 | C++ | heinemann9/CppPractice | /STLPractice/SetClassIterating/SetClassIterating.cpp | UTF-8 | 1,188 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <set>
#include <string>
using namespace std;
template <typename T>
void print_set(set<T>& s)
{
for (typename set<T>::iterator it = s.begin(); it != s.end(); ++it)
{
cout << *it << endl;
}
}
class Todo
{
int priority;
string job_desc;
public:
Todo(int priority, string job_desc)
: priority(priority), job_desc(job_desc) { }
bool operator<(const Todo& t) const
{
if (priority == t.priority)
{
return job_desc < t.job_desc;
}
return priority > t.priority;
}
friend ostream& operator<<(ostream& o, const Todo& td);
};
ostream& operator<<(ostream& o, const Todo& td)
{
o << "[ 중요도: " << td.priority << "] " << td.job_desc;
return o;
}
int main()
{
set<Todo> todos;
todos.insert(Todo(1, "BasketBall"));
todos.insert(Todo(2, "Math"));
todos.insert(Todo(1, "Programming"));
todos.insert(Todo(3, "Meet Friend"));
todos.insert(Todo(2, "Watch Movie"));
print_set(todos);
cout << "---------" << endl;
cout << "if done your homework" << endl;
todos.erase(todos.find(Todo(2, "Math")));
print_set(todos);
}
| true |
bdac3768877bb7a40318860f7d30d8769d0a9b2f | C++ | jjzhang166/RTP-19 | /odita/src/ofApp.cpp | UTF-8 | 4,056 | 2.609375 | 3 | [] | no_license | #include "ofApp.h"
bool sortDescending(int i, int j) { return (j < i); }
//--------------------------------------------------------------
void ofApp::setup(){
ofSetWindowShape(1280, 720);
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
float w = ofGetWidth()/2;
float h = ofGetHeight();
int numb = 20;
int numbColors = 5;
vector < ofColor > colors;
ofColor c1, c2, c3, c4, c5, c6, c7, c8;
c1.setHex(0x956FA6); c2.setHex(0x405045); c3.setHex(0xBF863F); c4.setHex(0xBF5934);
c5.setHex(0xBF3434); c6.setHex(0x8295B3); c7.setHex(0x526182); c8.setHex(0xD6B75D);
colors.push_back(c1); colors.push_back(c2); colors.push_back(c3); colors.push_back(c4);
colors.push_back(c5); colors.push_back(c6); colors.push_back(c7); colors.push_back(c8);
vector < float > aLeft;
vector < float > aRight;
vector < float > bLeft;
vector < float > bRight;
ofSeedRandom(1);
for (int i = 0; i < numb; i++) {
float randomNumber = ofRandomHeight();
aLeft.push_back(randomNumber);
aLeft.push_back(h);
}
ofSeedRandom(4);
for (int i = 0; i < numb; i++) {
float randomNumber = ofRandomHeight();
aRight.push_back(randomNumber);
aRight.push_back(h);
}
ofSeedRandom(3);
for (int i = 0; i < numb; i++) {
float randomNumber = ofRandomHeight();
bLeft.push_back(randomNumber);
bLeft.push_back(h);
}
ofSeedRandom(6);
for (int i = 0; i < numb; i++) {
float randomNumber = ofRandomHeight();
bRight.push_back(randomNumber);
bRight.push_back(h);
}
ofSort(aLeft, sortDescending);
ofSort(aRight, sortDescending);
ofSort(bLeft, sortDescending);
ofSort(bRight, sortDescending);
ofSeedRandom(0);
ofRandomize(colors);
for (int i = 0; i < aLeft.size(); i++) {
float adder = 100 * ofRandom(1);
float offsetLeft = sin(ofGetElapsedTimef() * 0.5);
float offsetRight = sin(ofGetElapsedTimef() * 0.8);
ofVec3f p1(0, aLeft[i] + adder * offsetLeft);
ofVec3f p2(w, aRight[i] + adder * offsetRight);
ofVec3f p3(0, 0);
ofVec3f p4(w, 0);
ofPath aLine;
aLine.lineTo(p1);
aLine.lineTo(p2);
aLine.lineTo(p4);
aLine.lineTo(p3);
aLine.lineTo(p1);
aLine.setFillColor(colors[i % colors.size()]);
aLine.draw();
}
ofRandomize(colors);
for (int i = 0; i < bLeft.size(); i++) {
float adder = 100 * ofRandom(1);
float offsetLeft = sin(ofGetElapsedTimef() * 0.3);
float offsetRight = sin(ofGetElapsedTimef() * 0.7);
ofVec3f p1(w, bLeft[i] + adder * offsetLeft);
ofVec3f p2(w * 2, bRight[i] + adder * offsetRight);
ofVec3f p3(w, 0);
ofVec3f p4(w*2, 0);
ofPath bLine;
bLine.lineTo(p1);
bLine.lineTo(p2);
bLine.lineTo(p4);
bLine.lineTo(p3);
bLine.lineTo(p1);
bLine.setFillColor(colors[i % colors.size()]);
bLine.draw();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
8139db25eb5996a781543bc4a15497406513375e | C++ | KumpelStachu/ZadaniaSCI | /main.cpp | UTF-8 | 389 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
int main()
{
const int rozmiar = 7;
int tablica[rozmiar] = { -1, 10, -102, 4, 6, 0, -1 };
int a = 5;
float b = 7.7f;
std::cout << cube(a) << std::endl;
// ...
multiply(tablica, rozmiar, a);
std::string temp = "";
for(int i = 0; i < rozmiar; i++)
temp += std::to_string(tablica[i]) + " ";
std::cout << temp;
// ...
getchar();
return 0;
}
| true |
a86762a884111d49d9af5d8bbeaed6d91d5a079a | C++ | snwfdhmp/neural-networks | /simpleBitRecognition/recognizer.cpp | UTF-8 | 504 | 2.671875 | 3 | [] | no_license | #include <fann.h>
#include <time.h>
#include <math.h>
#define NUMBERS_TO_GEN 2
#define MAX 500
int main(int argc, char const *argv[])
{
srand(time(NULL));
struct fann *ann = fann_create_from_file("trained.net");
int i;
float numbers[NUMBERS_TO_GEN];
printf("Nombres testés : \n");
for (i = 0; i < NUMBERS_TO_GEN; ++i)
{
numbers[i] = rand() % MAX;
printf("%f ", numbers[i]);
}
float *output = fann_run(ann, numbers);
printf("\na>b : %f\na <=b : %f\n", output[0], output[1]);
return 0;
} | true |
004d46f02b854436696839de0fdc12c6f51cfbb4 | C++ | jkl0727/algorithm | /Jungol/3220.cpp | UTF-8 | 1,989 | 2.5625 | 3 | [] | no_license | #include <stdio.h>
struct puzzle {
int id , same;
int num[4];
};
int N, M, T, S, NN;
int p_i = 0;
int check[2510] = { 0, };
int p_idx[51][51];
int wrong_piece[5];
puzzle piece[2510];
int encode(char *str) {
int ret = 0, temp;
for (int i = 1; i < M - 1; ++i) {
if (str[i] == '0') temp = 1;
else if (str[i] == 'M') temp = 2;
else temp = 0;
ret = ret * 3 + temp;
}
return ret;
}
void input(void) {
int i, j, k;
char str[20];
scanf("%d %d %d", &N, &M, &T);
NN = N * N;
for (i = 1, S = 1; i < M - 1; i++) S *= 3;
for (int k = 0; k < NN + T; ++k) {
piece[k].id = k;
piece[k].same = 0;
for (int i = 0; i < 4; ++i) {
scanf("%s", str);
int en = encode(str);
if (i < 2) {
piece[k].num[i] = en;
}
else
piece[k].num[i] = S - en - 1;
}
}
}
int arrange_piece(int layer) {
if (layer >= NN)
return 1;
int row = layer / N; int col = layer % N;
for (int i = 0; i < NN + T; ++i) {
if (check[i])
continue;
if (row && piece[i].num[3] != piece[p_idx[row - 1][col]].num[1])
continue;
if (col && piece[i].num[2] != piece[p_idx[row][col - 1]].num[0])
continue;
p_idx[row][col] = i;
check[i] = 1;
if (arrange_piece(layer + 1))
return 1;
check[i] = 0;
}
return 0;
}
int main(void) {
input();
int i, k;
for (i = 0; i < NN + T; ++i) {
for (k = 0; k < NN + T; ++k) {
if (piece[i].num[2] == piece[k].num[0])
piece[i].same++;
if (piece[i].num[3] == piece[k].num[1])
piece[i].same++;
}
}
for (int t = 0; t <= T; ++t) {
for (i = 0; i < NN + T; ++i) {
if (piece[i].same == t)
{
p_idx[0][0] = i;
check[i] = 1;
if(arrange_piece(1)) break;
check[i] = 0;
}
}
if (i < NN + T) break;
}
int r, c;
scanf("%d %d", &r, &c);
printf("%d\n", p_idx[r][c]);
for (i = 0; i < NN + T; ++i)
if(check[i] == 0)
printf("%d ", piece[i].id);
return 0;
} | true |
90fd1e94a2e412434081a3705535322eec2f6bcd | C++ | jbomyso1/ablScouting | /pitcher.h | UTF-8 | 1,151 | 2.828125 | 3 | [] | no_license | #ifndef PITCHER_H_
#define PITCHER_H_
struct pitcherNum
{
unsigned short rIF;
unsigned short rOF;
unsigned short efCF;
unsigned short rg1;
unsigned short gcf;
unsigned short efOF;
unsigned short rg2;
unsigned short sg;
unsigned short hbp;
unsigned short sgl;
unsigned short dbl;
unsigned short deep;
unsigned short efTired;
unsigned short ko;
unsigned short koTired;
unsigned short bb;
unsigned short dp;
};
struct pitcher
{
std::string name;
std::string team;
//if true, throws right handed, if false, throws left handed
bool righty;
//bool array to determine if starter, long reliever, short reliever, or closer (or combination of the options)
bool position[4];
unsigned short stamina;
//array represents [range, error rating, hold, steal, pick off, balk, wild pitch]
//steal value can be 0 or negative, which is better than positive numbers.
short defense[7];
//symbols will be true if the pitcher possesses them. [0] = B, [1] = R, [2] = L, [3] = F, [4] = H
bool symbols[5];
//this is to represent the pitcher's numbers against left and right handed hitting
pitcherNum left;
pitcherNum right;
};
#endif
| true |
0a9e0308650b487ea071cb29f531b207b9ffe810 | C++ | twestura/yarn-cloth-sim | /src/Simulator/Headers/Clock.h | UTF-8 | 1,749 | 3.328125 | 3 | [] | no_license | //
// Clock.h
// Visualizer
//
// Created by eschweickart on 2/24/14.
//
//
#ifndef Visualizer_Clock_h
#define Visualizer_Clock_h
#include "Constants.h"
/// A class that controls the passage of time within a simulation. Decides and keeps track of the
/// timestep, and records how much time has passed since the simulation began.
class Clock
{
private:
/// Current time of the simulation in seconds.
real t = 0.0;
/// Default (maximum) timestep for this clock.
real defaultTimestep;
/// Timestep of the model for the next step.
real h;
/// Number of times the clock has been incremented.
std::size_t ticks = 0;
public:
Clock(real defaultTimestep = constants::INITIAL_TIMESTEP) : defaultTimestep(defaultTimestep),
h(defaultTimestep) { }
/// The timestep will not decrease beyond this value.
const real minTimestep = 1.0e-6;
/// Get the current time of the simulation in seconds.
const real inline time() const { return t; }
/// Get the size of the next timestep.
const real inline timestep() const { return h; }
/// Get the number of times the clock has been incremented.
const std::size_t inline getTicks() const { return ticks; }
/// Suggest the size of the next timestep. If larger than the current timestep, the request
/// will be ignored. The size of the timestep will not decrease beyond the minimum timestep.
void inline suggestTimestep(real s) { h = std::max(minTimestep, std::min(h, s)); }
/// Increment the timer by its current timestep.
void inline increment() {
if (h <= 0.0) throw;
t += h;
h = defaultTimestep;
ticks++;
}
/// Returns true if the timestep can be made smaller.
bool inline canDecreaseTimestep() const { return h > minTimestep; }
};
#endif
| true |
53239d2e3fe0f5ffe142e8fded4a8e0196049e7f | C++ | JimmyCarter5417/leetcode | /cpp/0784. Letter Case Permutation.cpp | UTF-8 | 1,395 | 3.828125 | 4 | [] | no_license | // Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
// Examples:
// Input: S = "a1b2"
// Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
// Input: S = "3z4"
// Output: ["3z4", "3Z4"]
// Input: S = "12345"
// Output: ["12345"]
// Note:
// S will be a string with length at most 12.
// S will consist only of letters or digits.
class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> res;
dfs(S, 0, res, "");
return res;
}
void dfs(const string& src, int pos, vector<string>& res, string out)
{
if (pos >= src.size())
{
res.push_back(out);
return;
}
char ch = src[pos];
// 大小写互转
if (islower(ch))
{
dfs(src, pos + 1, res, out + (char)toupper(ch));// 字母转换后继续递归
}
else if (isupper(ch))
{
dfs(src, pos + 1, res, out + (char)tolower(ch));// 字母转换后继续递归
}
else
{
// 其他字符不处理
}
dfs(src, pos + 1, res, out + ch);// 不改变当前字符 从下一位置递归
return;
}
};
| true |
47ffba0a904d66c928572e28f06c6bceb08e2547 | C++ | gitguuddd/Learncpp-examples | /IntArray_Class/IntArray.h | UTF-8 | 849 | 3.140625 | 3 | [] | no_license | //
// Created by Mindaugas K on 7/23/2019.
//
#ifndef INTARRAY_CLASS_INTARRAY_H
#define INTARRAY_CLASS_INTARRAY_H
#include <cassert>
#include <iostream>
class IntArray {
private:
int m_length=0;
int* m_array= nullptr;
public:
IntArray(int length):m_length(length){
assert(m_length>0&&"array length should be a positive integer");
m_array=new int[m_length]{0};
}
IntArray(const IntArray &array):m_length(array.m_length){
m_array=new int[m_length];
for (int count=0;count<array.m_length;count++)
m_array[count]=array.m_array[count];
}
~IntArray(){
delete[] m_array;
}
int& operator[](int index);
friend std::ostream& operator<<(std::ostream& out, const IntArray &array);
IntArray& operator=(const IntArray &array);
};
#endif //INTARRAY_CLASS_INTARRAY_H
| true |
33b8e357717b7fdb6dd2f71dfddf04c0fa2f1a3d | C++ | epics-extensions/ChannelArchiver | /LibIO/MultiArchive.h | UTF-8 | 5,350 | 2.53125 | 3 | [] | no_license | // -*- c++ -*-
// --------------------------------------------------------
// $Id$
//
// Please refer to NOTICE.txt,
// included as part of this distribution,
// for legal information.
//
// Kay-Uwe Kasemir, kasemir@lanl.gov
// --------------------------------------------------------
#ifndef __MULTI_ARCHIVEI_H__
#define __MULTI_ARCHIVEI_H__
#include "ArchiveI.h"
#include "epicsTimeHelper.h"
//#define DEBUG_MULTIARCHIVE
class MultiChannelIterator;
class MultiValueIterator;
//CLASS MultiArchive
// The MultiArchive class implements a CLASS ArchiveI interface
// for accessing more than one archive.
// <P>
// The MultiArchive is configured via a "master" archive file,
// an ASCII file with the following format:
//
// <UL>
// <LI>Comments (starting with a number-sign) and empty lines are ignored
// <LI>The very first line must be<BR>
// <PRE>master_version=1</PRE>
// There must be no comments preceding this line!
// <LI>All remaining lines list one archive name per line
// </UL>
// <H2>Example</H2>
// <PRE>
// master_version=1
// # First check the "fast" archive
// /archives/fast/dir
// # Then check the "main" archive
// /archives/main/2001_05/dir
// /archives/main/2001_04/dir
// /archives/main/2001_03/dir
// /archives/main/2001_02/dir
// /archives/main/2001/dir
// </PRE>
// <P>
// The most recent sub-archive has to be listed first,
// followed by the next one back in time and so on
// to the oldest sub-archive.
// <P>
// This type of archive is read-only!
// <P>
// For now, each individual archive is in the binary data format
// (CLASS BinArchive).
// Later, it might be necessary to specify the type together with the name
// for each archive. The master_version will then be incremented.
// <BR>
// If the "master" file is invalid, it is considered an ordinary BinArchive
// directory file,
// i.e. Tools based on the MultiArchive should work just like BinArchive-based
// Tools when operating on a single archive.
//
// <H2>Details</H2>
// No sophisticated merging technique is used.
// Given a channel and point in time,
// the MultiArchive will try to read this from the
// first archive in the multi archive list,
// then the next archive and so on until it succeeds.
//
// When combining archives with disjunct channel sets,
// a read request for a channel will yield data
// from the single archive that holds that channel.
//
// When channels are present in multiple archives,
// a read request for a given point in time will
// return values from the <I>first archive listed</I> in the master file
// that has values for that channel and point in time.
//
// Consequently, one should avoid archives with overlapping time ranges.
// If this cannot be avoided, the "most important" archive should be
// listed first.
class MultiArchive : public ArchiveI
{
public:
class ChannelInfo
{
public:
stdString _name; // name of the channel
epicsTime _first_time; // Time stamp of first value
epicsTime _last_time; // Time stamp of last value
};
//* Open a MultiArchive for the given master file
MultiArchive(const stdString &master_file,
const epicsTime &from = nullTime,
const epicsTime &to = nullTime);
//* All virtuals from CLASS ArchiveI are implemented,
// except that the "write" routines fail for this read-only archive type.
virtual ChannelIteratorI *newChannelIterator() const;
virtual ValueIteratorI *newValueIterator() const;
virtual ValueI *newValue(DbrType type, DbrCount count);
virtual bool findFirstChannel(ChannelIteratorI *channel);
virtual bool findChannelByName(const stdString &name,
ChannelIteratorI *channel);
virtual bool findChannelByPattern(const stdString ®ular_expression,
ChannelIteratorI *channel);
virtual bool addChannel(const stdString &name, ChannelIteratorI *channel);
// debugging only
void log() const;
// For given channel, set value_iterator to value at-or-after time.
// For result=false, value_iterator could not be set.
// These routines will not clear() the value_iterator
// to allow stepping back when used from within next()/prev()!
bool getValueAfterTime(MultiChannelIterator &channel_iterator,
const epicsTime &time,
MultiValueIterator &value_iterator) const;
bool getValueAtOrBeforeTime(MultiChannelIterator &channel_iterator,
const epicsTime &time, bool exact_time_ok,
MultiValueIterator &value_iterator) const;
bool getValueNearTime(MultiChannelIterator &channel_iterator,
const epicsTime &time,
MultiValueIterator &value_iterator) const;
private:
friend class MultiChannelIterator;
friend class MultiChannel;
bool parseMasterFile(const stdString &master_file,
const epicsTime &from, const epicsTime &to);
// Fill _channels from _archives
void queryAllArchives();
// Get/insert ChannelInfo for given name
size_t getChannelInfoIndex(const stdString &name);
stdList<stdString> _archives; // names of archives
bool _queriedAllArchives;
stdVector<ChannelInfo> _channels; // summarized over all archives
};
#endif
| true |
8799785e59bd4f036987bde7e7225a98dd229aaf | C++ | Lilybon/leetcode | /src/909. Snakes and Ladders.cpp | UTF-8 | 1,035 | 2.546875 | 3 | [] | no_license | class Solution {
public:
int snakesAndLadders(vector<vector<int>>& board) {
const int n = board.size(),
CELL_VISITED = -2;
queue<pair<int, int>> q;
q.push({1, 0});
board[n - 1][0] = CELL_VISITED;
while (!q.empty()) {
auto [curr, moves] = q.front();
q.pop();
if (curr == n * n) {
return moves;
}
for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) {
int index = n * n - next,
row = index / n,
col = (n - 1 - row) % 2 ? index % n : n - 1 - index % n;
if (board[row][col] == CELL_VISITED) {
continue;
} else if (board[row][col] > 0) {
q.push({board[row][col], moves + 1});
} else {
q.push({next, moves + 1});
}
board[row][col] = CELL_VISITED;
}
}
return -1;
}
}; | true |
19ede297a6f987d091a147cab3aa9195219e3719 | C++ | skapin/AirPrinterController | /tempcontroller.cpp | UTF-8 | 2,469 | 2.71875 | 3 | [] | no_license | #include "tempcontroller.h"
int TempController::MAX_TEMP_LIST=60*60*24;
TempController::TempController(QObject *parent) :
QObject(parent)
{
}
int TempController::openDevice(string path) {
_device.setPortName( path );
return ( _device.openDevice() );
}
Uart* TempController::getDevice() {
return &_device;
}
void TempController::closeDevice() {
_device.closeDevice();
}
void TempController::parseData(string data) {
QRegExp reg("(\\c*)\\s*(\\S*)\\s*(\\d*)");
QString d( data.c_str() ) ;
string action, variable;
int pos = 0;
while ( (pos=reg.indexIn( d , pos )) != -1 ) {
pos += reg.matchedLength();
action = reg.cap(1).toStdString();
if ( action.compare("set") == 0) {
variable = reg.cap(2).toStdString();
if ( variable.compare("kp") == 0) {
_kp = reg.cap(3).toDouble();
}
else if ( variable.compare("ki") == 0) {
_ki = reg.cap(3).toDouble();
}
else if ( variable.compare("kd") == 0) {
_kd = reg.cap(3).toDouble();
}
else if ( variable.compare("maxtemp") == 0) {
_kp = reg.cap(3).toInt();
}
else if ( variable.compare("temp") == 0) {
addTemp( (double)(reg.cap(3).toInt()) );
}
}
else if ( action.compare("get") == 0 ) {
variable = reg.cap(2).toStdString();
string value_to_send;
if ( variable.compare("kp") == 0) {
value_to_send = QString::number(_kp).toStdString();
}
else if ( variable.compare("ki") == 0) {
value_to_send = QString::number(_ki).toStdString();
}
else if ( variable.compare("kd") == 0) {
value_to_send = QString::number(_kd).toStdString();
}
else if ( variable.compare("maxtemp") == 0) {
value_to_send = QString::number(_maxtemp).toStdString();
}
_device.send("set "+variable+" "+value_to_send) ;
}
else if ( action.compare("off") == 0) {
this->closeDevice();
//emit ??????????
}
}
}
void TempController::addTemp(double temp) {
if ( _tempList.size() > TempController::MAX_TEMP_LIST ) {
_tempList.remove(0,(int)TempController::MAX_TEMP_LIST/100 );
}
_tempList.append( temp );
}
| true |
219e990dc85329e10f2ee335ef4a79e8a117b99e | C++ | vladnoskoff/work | /тесты/Untitled1.cpp | WINDOWS-1251 | 4,703 | 2.59375 | 3 | [] | no_license | #include "Books/TXlib.h"
struct Hero
{
int x, y;
int vx, vy;
HDC photo;
int FrameSizeX;
int FrameSizeY;
int status, oldstatus;
int UP, DOWN, LEFT, RIGHT, STOP;
void Phisica ();
void Logic ();
void KeyState ();
void DrawHero (int t);
void Mouse (int leftm, int rightm);
void Pull (Hero* hero2);
void DeleteHDCDC ();
};
int main ()
{
txCreateWindow (1000, 1000);
HDC player = txLoadImage ("Image/play2/Pacman.bmp");
//HDC Fon = txLoadImage ("Image/fon3.bmp");
//const char* level = txInputBox ("Level?!?!", "Game", "");
//txMessageBox (level, "");
//txBitBlt (txDC(), 0, 0, 1000, 1000, Fon, 500, 0);
Hero Pacman = {306, 200, 1, 1, player, 2, 4, 1, 1};
int t = 0;
while (!GetAsyncKeyState (VK_ESCAPE))
{
Pacman.Phisica ();
Pacman.DrawHero (t);
}
Pacman.DeleteHDCDC ();
t++;
}
void Hero::Phisica ()
{
int xOld = x;
int yOld = y;
x = x + vx;
y = y + vy;
int xsize = txGetExtentX (photo) / 2 - 6;
int ysize = txGetExtentY (photo) / 4 - 6;
/*
printf ("xsize= %d\n", xsize);
printf ("ysize= %d\n", ysize);
txSetColor (TX_YELLOW);
txSetFillColor (TX_NULL);
txCircle (x - xsize/2, y, 5);
txCircle (x, y + ysize/2, 5);
txCircle (x + xsize/2, y, 5);
txCircle (x, y - ysize/2, 5);
txSetColor (TX_GREEN);
txSetFillColor (TX_NULL);
txCircle (x, y, 5);
*/
COLORREF leftpixel = txGetPixel (x - xsize/2, y);
COLORREF uppixel = txGetPixel (x, y + ysize/2);
COLORREF rightpixel = txGetPixel (x + xsize/2, y);
COLORREF downpixel = txGetPixel (x, y - ysize/2);
if (leftpixel != TX_BLACK || rightpixel != TX_BLACK)
{
x = xOld;
Logic ();
}
if (uppixel != TX_BLACK || downpixel != TX_BLACK)
{
y = yOld;
Logic ();
}
}
void Hero::KeyState ()
{
if (GetAsyncKeyState (UP)) (vy)--;
if (GetAsyncKeyState (DOWN)) (vy)++;
if (GetAsyncKeyState (LEFT)) (vx)--;
if (GetAsyncKeyState (RIGHT)) (vx)++;
if (GetAsyncKeyState (STOP)) vx = vy = 0;
//if (GetAsyncKeyState ('E')) status = Life;
//if (GetAsyncKeyState ('E')) status = Rip;
}
void Hero::DrawHero (int t)
{
int xsize = txGetExtentX (photo) / FrameSizeX;
int ysize = txGetExtentY (photo) / FrameSizeY;
int v = 0;
if (vx > 0 && vy == 0) v = 0;
if (vx < 0 && vy == 0) v = 1;
if (vy > 0 && vx == 0) v = 2;
if (vy < 0 && vx == 0) v = 3;
//if (status == Life) txTransparentBlt (txDC(), x - xsize/FrameSizeX, y - ysize/FrameSizeX, xsize, ysize, photo, t%FrameSizeX*xsize, v*ysize, TX_WHITE);
//if (status == Rip) { txSetFillColor (TX_WHITE); txCircle (x, y , 15); }
/*
1
vx > 0, vy = 0
2
vx< 0 , vy = 0
3
vx = 0, vy < 0
4
vx = 0, vy > 0
0 > -vy ,
0 > vx
= 1 , TransparentBlt
= 0 , DrawHero TransparentBlt
*/
}
void Hero::DeleteHDCDC ()
{
txDeleteDC (photo);
}
void Hero::Logic ()
{
if (rand () % 2 == 0)
{
if (rand () % 2 == 0) vx = +1;
else vx = -1;
vy = 0;
}
else
{
if (rand () % 2 == 0) vy = +1;
else vy = -1;
vx = 0;
}
}
void Hero::Mouse (int leftm, int rightm)
{
if (GetAsyncKeyState (leftm))
{
x = txMouseX();
y = txMouseY();
}
if (GetAsyncKeyState (rightm))
{
x = txMouseX();
y = txMouseY();
}
}
void Hero::Pull (Hero* hero2)
{
vx = -(x - hero2->x) / 50;
vy = -(y - hero2->y) / 50;
}
/*
if (Yellow.status == Rip || Red.status == Rip)
{
int Answer = txMessageBox ("Level 2 ?!?!?","???", MB_YESNO);
if (Answer == IDYES)
{
//txDeleteDC (fon);
txTransparentBlt (txDC(), 0, 0, 1700, 1070, fon2, 0, 0, TX_WHITE);
Red.status = Life;
Yellow.status = Life;
score = Touching (&Pacman, &Red, &Yellow, &life);
}
else
{
break;
}
}
*/
| true |
b94a4186f46a2a6efe506232b32f960425d1723d | C++ | Stasychbr/Calculator-2.0 | /ExprParser.cpp | UTF-8 | 263 | 2.625 | 3 | [] | no_license | #include "ExprParser.h"
#include <sstream>
vector<shared_ptr<Lexem>> ExprParser::parseLexems(string& expression) {
vector<shared_ptr<Lexem>> lexems;
while (!expression.empty()) {
lexems.push_back(getLexem(expression));
}
return lexems;
}
| true |
4804630008eec0af54123f4dab74a0bff4586469 | C++ | NQLong/sang-sang | /Library/Source/Catalog.cpp | UTF-8 | 4,890 | 3.140625 | 3 | [] | no_license | #include "../Header/Catalog.h"
#include "../Header/Library.h"
Catalog::Catalog()
{
}
Catalog::~Catalog()
{
}
Catalog::Catalog(list<Book> books)
{
this->books = books;
}
// friend ostream &operator<<(ostream &os, const Catalog &);
// friend bool operator==(const Catalog &lhs, const Catalog &rhs);
//manage
bool Catalog::add_book(Book i)
{
if (get_book(i.getISBN(), "ISBN") || get_book(i.getTitle(), "title"))
{
return false;
}
books.push_back(i);
return true;
}
bool Catalog::add_book()
{
cout << "add new book: " << endl;
Book i = Book::input();
return add_book(i);
}
bool Catalog::remove_book()
{
Book *ptr = pick_book();
if (!ptr)
{
cout << "Invalid pattern";
return false;
}
cout << "success";
return remove_book(*ptr);
}
bool Catalog::remove_book(Book i)
{
books.remove(i);
return true;
}
Book *Catalog::get_book(string pattern, string by)
{
for (auto it = books.begin(); it != books.end(); it++)
{
if (
(by == "ISBN" && it->getISBN() == pattern) ||
(by == "title" && it->getTitle() == pattern)
)
return &*it;
}
return NULL;
}
Book *Catalog::pick_book()
{
string by;
if (select_statement("get book by ISBN", "get book by title"))
{
clear();
return get_book(input_str("Enter book title: "), "title");
}
clear();
return get_book(input_str("Enter book ISBN: "), "ISBN");
}
bool Catalog::select_book()
{
Book *ptr = pick_book();
if (!ptr)
{
cout << "Invalid name";
wait();
clear();
return false;
}
clear();
if (select_statement("View book", "modify book"))
{
ptr->modify();
}
else
{
clear();
cout << *ptr;
wait();
}
return true;
}
void Catalog::books_list(list<Book> lst)
{
cout
<< setw(88) << setfill('*') << "" << endl
<< setfill(' ')
<< setw(10) << left << "| ISBN " << '|'
<< setw(12) << left << "publish year" << '|'
<< setw(20) << left << "publisher" << '|'
<< setw(10) << left << "status" << '|'
<< setw(30) << left << " Title" << '|'
<< endl
<< setw(88) << setfill('*') << "" << endl
<< setfill(' ');
for (auto it = lst.begin(); it != lst.end(); it++)
{
if (!&*it)
continue;
cout
<< setw(10) << left << "|" + it->getISBN() << '|'
<< setw(12) << left << it->getPublish_year() << '|'
<< setw(20) << left << it->getPublisher() << '|'
<< setw(10) << left << (BookStatus)it->getStatus() << '|'
<< setw(30) << left << it->getTitle() << '|'
<< endl
<< setw(88) << setfill('*') << "" << endl
<< setfill(' ');
}
}
list<Book> Catalog::getBooks(string pattern, string type)
{
list<Book> temp;
for (auto it = books.begin(); it != books.end(); it++)
{
if (type == "author")
{
if (it->write_by(pattern))
temp.push_back(*it);
}
else if (type == "publisher")
{
if (it->getPublisher() == (pattern))
temp.push_back(*it);
}
else if (type == "publication year")
{
if (to_string(it->getPublish_year()) == pattern)
temp.push_back(*it);
}
}
return temp;
}
void Catalog::search_book()
{
Book *ptr = pick_book();
if (!ptr)
{
cout << "book not found";
wait();
}
cout << *ptr;
wait();
}
void Catalog::search_books()
{
cout << "Search by:" << endl;
string typ = select_statements(
{
"author",
"publication year",
"publisher",
});
clear();
string pattern = input_str("Enter " + typ + ": ");
clear();
return books_list(getBooks(pattern, typ));
}
bool Catalog::add_book_request(Member *member)
{
clear();
cout << "select a book:\n";
Book *book = pick_book();
if (!book)
{
cout << "invlaid book";
return false;
}
BookRequest temp = BookRequest::input(member->getAccount_id(), book->getISBN());
return ((Library *)Holder::library)->add_request(temp);
}
bool Catalog::add_book_request()
{
Member *member = ((Library *)Holder::library)->pick_member();
if (!member)
{
cout << "invlaid member";
return false;
}
return add_book_request(member);
}
list<Book> *Catalog::getBooks()
{
return &this->books;
}
void Catalog::setBooks(list<Book> books)
{
this->books = books;
} | true |
968194e67e14b73c75e9473e52326c24e8004216 | C++ | lawtonsclass/f20-code-from-class | /csci40/lec01/hello.cpp | UTF-8 | 487 | 3.984375 | 4 | [] | no_license | #include <iostream>
using namespace std; // now we can skip the "std::"s
int main() {
// a complete C++ statement ends with a semicolon
// think of << as arrows that point in the direction of data
// transfer
cout << "Hello, world!\n"; // std::cout prints the text you give it to
// the screen
cout << "Hello, world!" << endl; // std::endl is equivalent '\n'
// "Hello, world!" is called a string (of characters)
return 0;
}
| true |
b89e1470739005c917ab6304312e86e34f932375 | C++ | ahmadmamdouh-10/OOP-With-C- | /Day1/Day1.1/main.cpp | UTF-8 | 959 | 4.15625 | 4 | [] | no_license | #include <iostream>
using namespace std;
//struct declaration:
struct point
{
int x, y;
};
//function prototype:
int Sum(int x,int y);
double Sum(double x, double y);
point Sum(point p1, point p2)
{
point result;
result.x=p1.x+p2.x;
result.y=p1.y+p2.y;
return result;
}
int main()
{
int x,y;
double x1,y1;
point p1,p2;
p1.x=10;
p1.y=20;
p2.x=15;
p2.y=30;
cout<<"Enter Integer Number one : ";
cin>>x;
cout<<"Enter Integer Number two : ";
cin>>y;
cout<<Sum(x,y)<<endl; //call function
cout<<"Enter Float Number one : ";
cin>>x1;
cout<<"Enter Float Number two : ";
cin>>y1;
cout<<Sum(x1,y1)<<endl;
cout<<"================"<<endl;
cout<<"Sum of X: "<<Sum(p1,p2).x<<endl<< "Sum of Y: "<<Sum(p1,p2).y<<endl;
return 0;
}
//function implementation:
int Sum(int x,int y)
{
return (x+y);
}
double Sum(double x, double y)
{
return (x+y);
}
| true |
a1424a564896cd8fe2fe1b38a3e20ffc515820ee | C++ | lesleyping/leetcode-together | /src/offer14.cutRope/cupRope.cpp | UTF-8 | 1,015 | 3.375 | 3 | [] | no_license | class Solution1 {
public:
int cutRope(int number) {
if(number <= 2)
return number;
if(number == 3)
return 2;
int* res = new int[number+1];
res[0] = 0;
res[1] = 1;
res[2] = 2;
res[3] = 3;
int max = 0;
for(int i = 4; i <= number; i++){
max = 0;
for(int j = 1; j <= i/2; j++){
int tmp = res[j] * res[i-j];
if(tmp > max)
max = tmp;
}
res[i] = max;
}
return res[number];
}
};
class Solution2 {
public:
int cutRope(int number) {
if(number < 2)
return 0;
if(number == 2)
return 1;
if(number == 3)
return 2;
int timesOf3 = number/3;
if(number - timesOf3 * 3 == 1){
timesOf3 -= 1;
}
int timesOf2 = (number - timesOf3*3)/2;
return (int)(pow(3,timesOf3)) * (int)(pow(2,timesOf2));
}
}; | true |
1e1a25c9476b5c31d6e76ed033ce04f46178c4e2 | C++ | hnutank163/algor | /leetcode/maxSlidingWindow.cpp | UTF-8 | 2,317 | 3.265625 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <deque>
using namespace std;
class Solution{
public:
int max(vector<int>::iterator iter1, vector<int>::iterator iter2){
int maxNum = *iter1;
if(iter1>=iter2)
return 0;
while(iter1!=iter2)
{
if(maxNum < *iter1)
maxNum = *iter1;
++iter1;
}
return maxNum;
}
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> vi;
if((int)nums.size() < k)
return vi;
vi.assign(nums.begin(), nums.end()-k+1);
int size = nums.size();
for(int i= 0;i<size;++i)
{
for(int j=i-(k-1); j<i+1; ++j){
if(j>=0 && j<size-k+1)
vi[j] = std::max(vi[j],nums[i]);
}
}
return vi;
}
vector<int> maxSlidingWindow2(vector<int> &nums, int k)
{
vector<int> vi;
if( (int)nums.size()<k || k==0)
return vi;
vi.assign(nums.begin(), nums.end()-k+1);
int size = nums.size();
for(int i=0; i<size-k+1; i+=2){
int temp = max(nums.begin()+i+1,nums.begin()+i+k);
cout<<"temp "<<temp<<endl;
vi[i] = std::max(nums[i],temp);
vi[i+1] = std::max(nums[i+k],temp);
}
vi[size-k] = max(nums.end()-k,nums.end());
return vi;
}
vector<int> maxSlidingWindow3(vector<int> &nums, int k)
{
int size = nums.size();
vector<int> vi;
if(k==0)
return vi;
deque<int> dq;
for(int i=0; i<size; ++i){
while( !dq.empty() && dq.front()<=i-k)
dq.pop_front();
while( !dq.empty() && nums[dq.back()]<nums[i])
dq.pop_back();
dq.push_back(i);
if(i>=k-1)
vi.push_back(nums[dq.front()]);
}
return vi;
}
};
int main(){
Solution sl;
int a[ ] = {-6,-10,-7,-1,-9,9,-8,-4,10,-5,2,9,0,-7,7,4,-2,-10,8,7};
vector<int> vi;
vi.assign(a,a+20);
vector<int> v = sl.maxSlidingWindow2(vi,7);
for(auto i:v)
cout<<i<< " ";
cout<<endl;
vector<int> v2 = sl.maxSlidingWindow3(vi,7);
for(auto i:v2)
cout<<i<< " ";
cout<<endl;
}
| true |
2c3f40bf13bb84c5189cac5ad5c9218a7138320d | C++ | rahul2412/C_plus_plus | /overstring.cpp | UTF-8 | 1,600 | 3.34375 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
class test {
char *value;
int len;
public:
test(){
len=0;
value=0;
}
test(char *s){
len=strlen(s);
value=new char[len+1];
strcpy(value,s);
}
test (test &s)
{
len=strlen(s.value);
value=new char[len+1];
strcpy(value,s.value);
}
friend test&operator +(test obj1,test obj2)
{
test obj3;
obj3.len=obj1.len+obj2.len;
obj3.value=new char[obj3.len+1];
strcpy(obj3.value,obj1.value);
strcat(obj3.value,obj2.value);
return obj3;
}
friend int operator==(test obj1,test obj2)
{
int rel=0;
if(strcmp(obj1.value,obj2.value)==0)
{
rel=1;}
return rel;
}
friend int operator !=(test obj1,test obj2){
int rel=0;
if(strcmp(obj1.value,obj2.value)!=0)
{
rel=1;
}
return rel;
}
friend int operator<(test obj1,test obj2)
{
int rel=0;
int result=0;
rel=strcmp(obj1.value,obj2,value)
if(rel<0)
{
result=1;
}
return result;
}
friend int operator>(test obj1,test obj2)
{
int rel=0;
int result=0;
rel=strcmp(obj1.value,obj2.value);
if(rel>0)
{
result=1;
}
return result;
}
void display()
{
cout<<"result is"<<value;
}
};
int main()
{
test obj1("xxxyyz");
test obj2("hello");
obj1.display();
obj2.display();
test obj3;
obj3=obj1+obj2;
obj3.display();
if(obj1==obj2)
cout<<"obj1 is equal to obj2";
else
cout<<"not equal";
if(obj1!=obj2)
cout<<"obj1 is not equal to obj2";
else
cout<<"objects are equal";
if(obj1>obj2)
cout<<"obj1 is greater than obj2";
if(obj1<obj2)
cout<<"obj1 is less than obj2";
}
| true |