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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d724bf1a4383ce9eef7e9619e19facbc248c4716 | C++ | KhronosGroup/SYCL-CTS | /tests/common/once_per_unit.h | UTF-8 | 1,323 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
//
// SYCL 2020 Conformance Test Suite
//
// Factory methods for objects created once per translation unit
//
*******************************************************************************/
#ifndef __SYCLCTS_TESTS_COMMON_ONCE_PER_UNIT_H
#define __SYCLCTS_TESTS_COMMON_ONCE_PER_UNIT_H
#include "../../util/logger.h"
#include "../common/get_cts_object.h"
namespace detail {
/**
* @brief Helper class for once_per_unit::log() function
*/
struct log_notice {
log_notice(sycl_cts::util::logger &log, const std::string &message) {
log.note(message);
}
};
} // namespace detail
namespace {
/**
* All symbols have internal linkage here;
* special attention to the ODR rules should be made
*/
namespace once_per_unit {
/**
* @brief Factory method; provides unique queue instance per compilation unit
*/
inline sycl::queue &get_queue() {
static auto q = sycl_cts::util::get_cts_object::queue();
return q;
}
/**
* @brief Provide possibility to log message once per translation unit
*/
inline void log(sycl_cts::util::logger& log, const std::string& message) {
static const detail::log_notice log_just_once(log, message);
}
} // namespace once_per_unit
} // namespace
#endif // __SYCLCTS_TESTS_COMMON_ONCE_PER_UNIT_H
| true |
13b7bcda0f644676416593e0fe6e7fcc176827f8 | C++ | jeonghyeon-kwon/algorithm | /problem13547.cpp | UTF-8 | 3,023 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define MOD 1000000007
#define MAX_INT 2147483647
#define MAX_LLONG 9223372036854775807
/*
MO's algorithm을 이용
- 설명
알고리즘은 별거 없다.
많은 갯수의 query가 들어올때 정렬 잘해서 복잡도를 줄이는 방법이다.
즉 정렬 방법이 중요하다는 뜻이다.
정렬방법은 N을 sqrt N 단위로 쪼개서 그 part 별로 정렬하는 것이다.
복잡도는 O(N sqrt(N))이다.
sqrtN = sqrt(N) 의 값을 100이라 하면
query가 (1, 100), (99, 100), (1, 200), (199, 200), (1, 300), (299, 300) .....
으로 들어올때 복잡도는 100 + 100 + 200 + 200 + 300 ... = 200(1+2+3+4+5+.....100)
O(N sqrt(N))이 된다.
query자체의 갯수는 크게 중요하지 않다.
- 참고자료
http://kesakiyo.tistory.com/25
복잡도를 더 줄이고 싶으면 펜윅트리를 사용한다.
*/
struct range{
int start;
int end;
int idx;
range():start(0),end(0),idx(0){}
range(int s, int e, int i):start(s),end(e),idx(i){}
};
int N, M;
int sqrtN;
int input[100001] = {0,};
int value[1000001] = {0,};
int differentCount = 0;
bool cmp(struct range fir, struct range sec)
{
int firPos = fir.end / sqrtN;
int secPos = sec.end / sqrtN;
return firPos == secPos ? fir.start < sec.start : firPos < secPos;
}
int main ()
{
freopen("sample.txt", "r", stdin);
scanf("%d", &N);
sqrtN = (int)sqrt(N);
for(int i = 1; i <= N; i++)
{
scanf("%d", &input[i]);
}
scanf("%d", &M);
vector <struct range> query(M);
int s,e;
for(int i = 0; i < M; i++)
{
scanf("%d%d", &s, &e);
query[i] = range(s,e,i);
}
sort(query.begin(), query.end(), cmp);
vector <int> ans(M);
int prevStart = query[0].start, prevEnd = query[0].start - 1;
int currStart, currEnd;
for(int i = 0; i < M; i++)
{
currStart = query[i].start;
currEnd = query[i].end;
if(prevStart < currStart)
{
for(int j = prevStart; j < currStart; j++)
{
value[input[j]]--;
if(value[input[j]] == 0)
{
differentCount--;
}
}
}
else
{
for(int j = currStart; j < prevStart; j++)
{
value[input[j]]++;
if(value[input[j]] == 1)
{
differentCount++;
}
}
}
if(prevEnd < currEnd)
{
for(int j = prevEnd + 1; j <= currEnd; j++)
{
value[input[j]]++;
if(value[input[j]] == 1)
{
differentCount++;
}
}
}
else
{
for(int j = currEnd + 1; j <= prevEnd; j++)
{
value[input[j]]--;
if(value[input[j]] == 0)
{
differentCount--;
}
}
}
ans[query[i].idx] = differentCount;
prevStart = currStart;
prevEnd = currEnd;
}
for(int i = 0; i < M; i++)
{
printf("%d\n", ans[i]);
}
return 0;
} | true |
f661358b5eb4112e0cb679a42d63bacfc4a1bdea | C++ | joeychun/usaco | /training/ride.cpp | UTF-8 | 574 | 2.953125 | 3 | [] | no_license | /*
ID: joey.s.1
LANG: C++
TASK: ride
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin ("ride.in");
ofstream fout ("ride.out");
string first, second;
int first_multi=1, second_multi=1;
fin >> first >> second;
for (int i=0; i<first.length(); ++i) {
first_multi *= first.at(i) - 'A' + 1;
}
for (int i=0; i<second.length(); ++i) {
second_multi *= second.at(i) - 'A' + 1;
}
if (first_multi%47 == second_multi%47) {
fout << "GO\n";
} else {
fout << "STAY\n";
}
return 0;
}
| true |
2dcb9739866d8af8de9c82b2e5a1d9195cf9e562 | C++ | woodsking2/mbed-os | /targets/TARGET_Dialog/TARGET_DA1469x/configurable_MAC/configurable_MAC.h | UTF-8 | 794 | 2.53125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | #pragma once
#include <memory>
#include "gsl/gsl"
#include "Nondestructive.h"
class Configurable_MAC final : virtual public Nondestructive
{
public:
enum class Result
{
success,
uninitialized,
initialized,
};
Configurable_MAC();
~Configurable_MAC();
/**
* @brief only call once
*
* @return Result
*/
Result initialize();
/**
* @brief only can call before initialized
*
* @param ble address
* @return
*
*/
Result set_address(gsl::span<uint8_t, 6> address);
/**
* @brief only can call after initialized
*
* @param data
* @return Result
*/
Result write(gsl::span<uint8_t const> data);
private:
class Impl;
std::unique_ptr<Impl> m_impl;
};
| true |
a82d5b5e342d4c575ab7dfd4a9a96ae6f61b224b | C++ | jeff431/Antix | /antix2/gptest.cc | UTF-8 | 2,465 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include "antix.pb.h"
using namespace std;
string master_host = "localhost";
string master_publish_port = "7773";
string master_node_port = "7770";
int main(int argc, char* argv[]) {
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc != 2) {
cerr << "Usage: " << argv[0] << "FILE" << endl;
return -1;
}
antixtransfer::RobotRequestMap rrm;
{
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!rrm.ParseFromIstream(&input)) {
cerr << "Failed to parse rrm." << endl;
return -1;
}
}
cout << "robotid: " << rrm.robotid() << endl;
cout << "robotx: " << rrm.robotx() << endl;
cout << "roboty: " << rrm.roboty() << endl;
cout << "robotfacing: " << rrm.robotfacing() << endl;
cout << "Enter robotid: ";
int robotid;
cin >> robotid;
rrm.set_robotid(robotid);
cout << "Enter robotx: ";
double robotx;
cin >> robotx;
rrm.set_robotx(robotx);
cout << "Enter roboty: ";
double roboty;
cin >> roboty;
rrm.set_roboty(roboty);
cout << "Enter robotfacing: ";
double robotfacing;
cin >> robotfacing;
rrm.set_robotfacing(robotfacing);
/*send rrm to master using protobuf*/
zmq::context_t context(1);
zmq::socket_t node_master_sock(context, ZMQ_REQ);
node_master_sock.connect(antix::make_endpoint(master_host, master_node_port));
cout << "connecting to master..." << endl;
zmq::socket_t master_publish_sock(context, ZMQ_SUB);
// subscribe to all messages on this socket: should just be a list of nodes
master_publish_sock.setsockopt(ZMQ_SUBSCRIBE, "", 0);
master_publish_sock.connect(antix::make_endpoint(master_host, master_publish_port));
cout << "sending a robot to master..." << endl;
antix::send_pb(&node_master_sock, &rrm);
{
// Write the new address book back to disk.
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!rrm.SerializeToOstream(&output)) {
cerr << "Failed to write rrm." << endl;
return -1;
}
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
| true |
23b4f75bc1c5f35f9783f80ee76832b90fe81f82 | C++ | Peterskhan/TDL | /task.cpp | UTF-8 | 1,871 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "task.h"
#include "tdl.h"
namespace tdl {
std::atomic_uint Task::s_task_id_counter {0};
Task::Task()
: m_task_id(++s_task_id_counter),
m_refcount(1),
m_parent(nullptr),
m_continuation(nullptr),
m_affinity(thread_affinity::none)
{}
void Task::process() {
// Executing task
execute();
// Decrementing parent refcount
if (m_parent != nullptr)
m_parent->decrement_refcount();
// Decrementing own refcount
decrement_refcount();
}
void Task::wait() {
std::unique_lock<std::mutex> lock(m_mutex);
m_wait_cv.wait(lock, [this](){
return m_refcount == 0;
});
}
std::size_t Task::get_id() const {
return m_task_id;
}
std::size_t Task::get_refcount() const {
return m_refcount;
}
task_ptr Task::get_parent() const {
return m_parent;
}
task_ptr Task::get_continuation() const {
return m_continuation;
}
thread_affinity Task::get_thread_affinity() const {
return m_affinity;
}
void Task::set_parent(task_ptr parent) {
m_parent = parent;
}
task_ptr Task::set_continuation(task_ptr continuation) {
m_continuation = continuation;
return continuation;
}
void Task::set_thread_affinity(thread_affinity affinity) {
m_affinity = affinity;
}
void Task::increment_refcount() {
m_refcount++;
}
void Task::decrement_refcount() {
if (--m_refcount == 0) {
// Pushing continuation
if (m_continuation != nullptr) {
tdl::detail::push_task(m_continuation);
}
// Waking up threads waiting for completion
m_wait_cv.notify_all();
}
}
} // namespace tdl
| true |
f2acfd99b03a84f31bd64300ff9e50272020453c | C++ | stz91/wangdaoC- | /20190812/Factory/test.cc | UTF-8 | 211 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Test
{
public:
void Print()
{
cout << "Print()" << endl;
}
};
int main(void)
{
Test * tp = new Test();
tp->Print();
return 0;
} | true |
d5196a2ae242a6feeb9953c8248621021baf0f23 | C++ | NekoSilverFox/CPP | /512 - тех. пр. B3/B3-1/task1.cpp | UTF-8 | 3,582 | 3.078125 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <sstream>
#include "phoneBook.hpp"
#include "bookmarks.hpp"
#include "info.hpp"
#include "taskFunctions.hpp"
void task1()
{
std::string line;
jianing::PhoneBook book_phone;
jianing::Bookmarks marks(&book_phone);
while (getline(std::cin, line))
{
if (std::cin.fail())
{
throw std::ios_base::failure("Error reading data.");
}
std::stringstream string(line);
std::string command;
string >> command;
if (command == "add")
{
std::string external_number;
string >> external_number;
std::string external_name = getName(string);
if (external_name.empty())
{
std::cout << "<INVALID COMMAND>\n";
continue;
}
if (book_phone.isEmpty())
{
book_phone.pushBack({external_name, external_number});
auto mark = marks.getCurrent();
mark.iter = book_phone.getRecord();
marks.replaceCurrent(mark);
}
else
{
book_phone.pushBack({external_name, external_number});
}
}
else if (command == "store")
{
std::string markName;
std::string newMarkName;
string >> markName >> newMarkName;
if (marks.findBookmark(markName))
{
marks.store(markName, newMarkName);
}
else
{
std::cout << "<INVALID BOOKMARK>\n";
}
}
else if (command == "insert")
{
std::string additionalCommand;
std::string markName;
std::string external_number;
string >> additionalCommand;
string >> markName >> external_number;
std::string external_name = getName(string);
if (external_name.empty())
{
std::cout << "<INVALID COMMAND>\n";
continue;
}
if (marks.findBookmark(markName))
{
if (additionalCommand == "before")
{
marks.insertBefore(markName, external_number, external_name);
}
else if (additionalCommand == "after")
{
marks.insertAfter(markName, external_number, external_name);
}
else
{
std::cout << "<INVALID COMMAND>\n";
}
}
else
{
std::cout << "<INVALID BOOKMARK>\n";
}
}
else if (command == "delete")
{
std::string markName;
string >> markName;
if (marks.findBookmark(markName))
{
marks.remove(markName);
}
else
{
std::cout << "<INVALID BOOKMARK>\n";
}
}
else if (command == "show")
{
std::string markName;
string >> markName;
if (marks.findBookmark(markName))
{
marks.show(markName);
}
else
{
std::cout << "<INVALID BOOKMARK>\n";
}
}
else if (command == "move")
{
std::string markName;
std::string externalStep;
string >> markName >> externalStep;
if (marks.findBookmark(markName))
{
if (externalStep == "first")
{
marks.moveFirst(markName);
}
else if (externalStep == "last")
{
marks.moveLast(markName);
}
else
{
try
{
int step = std::stoi(externalStep);
marks.move(markName, step);
}
catch (std::invalid_argument&)
{
std::cout << "<INVALID STEP>\n";
}
}
}
else
{
std::cout << "<INVALID BOOKMARK>\n";
}
}
else
{
std::cout << "<INVALID COMMAND>\n";
}
}
}
| true |
0997bbf78bf7096a8c2b27cdbd497fe0cc2119b7 | C++ | Computer-Kids-Club/screenshare-pro-backend | /utils.cpp | UTF-8 | 288 | 2.6875 | 3 | [] | no_license | #include "utils.h"
std::string get_file_contents(const char *filename) {
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
return (std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()));
}
throw(errno);
} | true |
2abf087e78bfdac673412cf1063c926c356bfb51 | C++ | ArchieGoodwin/OnTimeMed | /cvlibbase/Src/Timer.cpp | WINDOWS-1252 | 2,918 | 2.75 | 3 | [] | no_license | /*!
* \file Timer.cpp
* \ingroup base
* \brief ˾ ױ ̡ е ̩ٳ.
* \author ˧
*/
#include "cvlibmacros.h"
#if CVLIB_OS == CVLIB_OS_WIN32
#include <windows.h>
#undef GetRValue
#undef GetGValue
#undef GetBValue
#endif
#include "Timer.h"
#ifndef _MSC_VER
#include <sys/times.h>
#include <unistd.h>
#endif
namespace CVLib
{
#ifdef _MSC_VER
time_t Timer::base_time = 0;
#endif
Timer::Timer()
{
#ifdef _MSC_VER
while(!base_time)
time(&base_time);
#endif
total_time = 0;
is_running = false;
start_time = GetRunTime();
#if CVLIB_OS == CVLIB_OS_WIN32
m_StartTime=0;
m_StopTime=0;
QueryPerformanceFrequency((LARGE_INTEGER*)&m_Frequency);
QueryPerformanceCounter((LARGE_INTEGER*)&m_StartTime);
#endif
}
Timer::~Timer()
{
}
char* Timer::AscCurrentTime()
{
struct tm *newtime;
time_t aclock;
time( &aclock ); /* Get time in seconds */
newtime = localtime( &aclock ); /* Convert time to struct */
return asctime(newtime);
}
double Timer::GetRunTime()
{
#ifdef _MSC_VER
time_t truc_foireux;
time(&truc_foireux);
return (double)(difftime(truc_foireux, base_time));
#else
struct tms current;
times(¤t);
double norm = (double)sysconf(_SC_CLK_TCK);
return(((double)current.tms_utime)/norm);
#endif
}
void Timer::Reset()
{
#if CVLIB_OS==CVLIB_OS_WIN32
m_StartTime=0;
m_StopTime=0;
QueryPerformanceCounter((LARGE_INTEGER*)&m_StartTime);
#endif
total_time = 0;
start_time = GetRunTime();
}
void Timer::Stop()
{
if(!is_running)
return;
#if CVLIB_OS==CVLIB_OS_WIN32
QueryPerformanceCounter((LARGE_INTEGER*)&m_StopTime);
total_time += static_cast<double>(m_StopTime - m_StartTime) / m_Frequency;
#else
double current_time = GetRunTime() - start_time;
total_time += current_time;
#endif
is_running = false;
}
void Timer::Resume()
{
if(is_running)
return;
#if CVLIB_OS==CVLIB_OS_WIN32
QueryPerformanceCounter((LARGE_INTEGER*)&m_StartTime);
#else
start_time = GetRunTime();
#endif
is_running = true;
}
double Timer::GetElapsedTime()
{
if(is_running)
{
#if CVLIB_OS==CVLIB_OS_WIN32
__int64 curTime;
QueryPerformanceCounter((LARGE_INTEGER*)&curTime);
return total_time + static_cast<double>(curTime-m_StartTime)/m_Frequency;
#else
double current_time = GetRunTime() - start_time;
return(total_time+current_time);
#endif
}
else
return total_time;
}
void Timer::Sleep(int nMilliseconds)
{
Reset();
double rSecond = (double)nMilliseconds / 1000.0;
while (1)
{
double rNow=GetRunTime();
double rDelay=rNow-start_time;
if (rDelay > rSecond)
break;
}
}
// double CSProfiler::GetElapsed() const
// {
// const double t = static_cast<double>(m_StopTime - m_StartTime) / m_Frequency;
// return t;
// }
// #endif
}
| true |
5252c26d75ea5f01542b34d1eee6255367c6ce77 | C++ | ganeshvjy/DatastructuresDemo | /RecordsSearch.cpp | UTF-8 | 3,664 | 3.421875 | 3 | [] | no_license | #include"RecordsSearch.h"
RecordsSearch::RecordsSearch(){
}
RecordsSearch::~RecordsSearch(){
}
void RecordsSearch::bulkInsert(std::vector<Employee> records){
for (int i = 0; i<records.size(); i++)
{
RecordsFName.push_back(records[i]);
RecordsLName.push_back(records[i]);
RecordsPWord.push_back(records[i]);
}
quickFName(RecordsFName, 0, RecordsFName.size() - 1);
quickLName(RecordsLName, 0, RecordsLName.size() - 1);
quickPWord(RecordsPWord, 0, RecordsPWord.size() - 1);
}
void RecordsSearch::quickFName(std::vector<Employee>& Vector, int front, int back){
int start = front;
int end = back;
std::string pivot = Vector[(front + back) / 2].first_name;
while (start <= end){
while (Vector[start].first_name < pivot){ start++; }
while (Vector[end].first_name > pivot){ end--; }
if (start <= end){
Employee temp = Vector[start];
Vector[start] = Vector[end];
Vector[end] = temp;start++;end--;
}
}
if (front < end)
quickFName(Vector, front, end);
if (start < back)
quickFName(Vector, start, back);
}
void RecordsSearch::quickLName(std::vector<Employee>& Vector, int front, int back){
int start = front;
int end = back;
std::string pivot = Vector[(front + back) / 2].last_name;
while (start <= end){
while (Vector[start].last_name < pivot){ start++; }
while (Vector[end].last_name > pivot){ end--; }
if (start <= end){
Employee temp = Vector[start];
Vector[start] = Vector[end];
Vector[end] = temp;start++;end--;
}
}
if (front < end)
quickLName(Vector, front, end);
if (start < back)
quickLName(Vector, start, back);
}
void RecordsSearch::quickPWord(std::vector<Employee>& Vector, int front, int back){
int start = front;
int end = back;
std::string pivot = Vector[(front + back) / 2].password;
while (start <= end){
while (Vector[start].password < pivot){ start++; }
while (Vector[end].password > pivot){ end--; }
if (start <= end){
Employee temp = Vector[start];
Vector[start] = Vector[end];
Vector[end] = temp;start++;end--;
}
}
if (front < end)
quickPWord(Vector, front, end);
if (start < back)
quickPWord(Vector, start, back);
}
int RecordsSearch::binarySearchFName(std::vector<Employee>& Vector, std::string key){
int low = 0;
int mid;
int high = Vector.size() - 1;
while (low <= high){
mid = (low + high) / 2;
if (key < Vector[mid].first_name){
high = mid - 1;
}
else if (Vector[mid].first_name < key){
low = mid + 1;
}
else {
return mid;
}
}
return -1;
}
int RecordsSearch::binarySearchLName(std::vector<Employee>& Vector, std::string key){
int low = 0;
int mid;
int high = Vector.size() - 1;
while (low <= high){
mid = (low + high) / 2;
if (key < Vector[mid].last_name){
high = mid - 1;
}
else if (Vector[mid].last_name < key){
low = mid + 1;
}
else {
return mid;
}
}
return -1;
}
int RecordsSearch::binarySearchPWord(std::vector<Employee>& Vector, std::string key){
int low = 0;
int mid;
int high = Vector.size() - 1;
while (low <= high){
mid = (low + high) / 2;
if (key < Vector[mid].password){
high = mid - 1;
}
else if (Vector[mid].password < key){
low = mid + 1;
}
else {
return mid;
}
}
return -1;
}
Employee RecordsSearch::searchFirstName(std::string first_name){
int index = binarySearchFName(RecordsFName, first_name);
return RecordsFName[index];
}
Employee RecordsSearch::searchLastName(std::string last_name){
int index = binarySearchLName(RecordsLName, last_name);
return RecordsLName[index];
}
Employee RecordsSearch::searchPassword(std::string password){
int index = binarySearchPWord(RecordsPWord, password);
return RecordsPWord[index];
} | true |
a1482e3a06a9e5e2fce061c6bff91f383402e70c | C++ | parthabb/cplusplus | /sortlib/heap.h | UTF-8 | 278 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | // Header file for heap.
class Heap {
protected:
int size, *heap;
public:
Heap(int *, int);
void MaxHeapify(int);
void BuildMaxHeap();
void MinHeapify(int);
void BuildMinHeap();
void HeapSort();
void RevHeapSort();
void PrintHeap();
};
| true |
74dd589b0cdda4b35a5edd810e1a45456a5d0dc9 | C++ | Kitware/vtk-examples | /src/Cxx/DataStructures/BuildLocatorFromKClosestPoints.cxx | UTF-8 | 1,035 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive | #include <vtkIdList.h>
#include <vtkKdTree.h>
#include <vtkNew.h>
#include <vtkPoints.h>
int main(int, char*[])
{
// Create some points
double origin[3] = {0.0, 0.0, 0.0};
double x[3] = {1.0, 0.0, 0.0};
double y[3] = {0.0, 1.0, 0.0};
double z[3] = {0.0, 0.0, 1.0};
vtkNew<vtkPoints> points;
points->InsertNextPoint(origin);
points->InsertNextPoint(x);
points->InsertNextPoint(y);
points->InsertNextPoint(z);
// Create the tree
vtkNew<vtkKdTree> pointTree;
pointTree->BuildLocatorFromPoints(points);
// Find the 2 closest points to (0.5,0,0)
vtkIdType k = 2;
double testPoint[3] = {0.5, 0.0, 0.0};
vtkNew<vtkIdList> result;
pointTree->FindClosestNPoints(k, testPoint, result);
for (vtkIdType i = 0; i < k; i++)
{
vtkIdType point_ind = result->GetId(i);
double p[3];
points->GetPoint(point_ind, p);
std::cout << "Closest point " << i << ": Point " << point_ind << ": ("
<< p[0] << ", " << p[1] << ", " << p[2] << ")" << std::endl;
}
return EXIT_SUCCESS;
}
| true |
817801077eb9a93c2f632ed6e520b6b239adf6b3 | C++ | madsend/Media-Database-Project | /Book.h | UTF-8 | 717 | 2.828125 | 3 | [] | no_license | #pragma once
#include "item.h"
class Book :
public Item
{
public:
static string getMediaTypeName();
Book(void);
Book(const string& newTitle);
Book(const string& newTitle, const string& newCreator, const int& newDivisions);
Book(const string& newTitle, const string& newCreator, const int& newDivisions, const int& nKeywords, ...);
~Book(void);
string toString() const;
string getCreatorType() const;
string getMediaType() const;
string getDivisionType() const;
bool hasAuthor(const string& authorName) const;
string getAuthor() const;
void setAuthor(const string& newAuthor);
private:
static const string CREATOR_TYPE;
static const string MEDIA_TYPE;
static const string DIVISION_TYPE;
};
| true |
a0f3583a0640fed400b9247e3953774c28072576 | C++ | SilasA/CIS-HW | /CIS-263/Assignment 1/agnew.cpp | UTF-8 | 843 | 3.59375 | 4 | [] | no_license | #include "house.h"
#include <iostream>
house::house()
{
this->color = "unknown";
this->price = -1;
this->num_rooms = -1;
}
house::house(const string &ColorValue, int PriceValue, int Num_roomsValue)
{
this->color = ColorValue;
this->price = PriceValue;
this->num_rooms = Num_roomsValue;
}
void house::SetColor(const string &ColorValue)
{
this->color = ColorValue;
}
string house::GetColor() const { return this->color; }
void house::SetPrice(int PriceValue)
{
this->price = PriceValue;
}
int house::GetPrice() const { return this->price; }
void house::SetNum_rooms(int Num_roomsValue)
{
this->num_rooms = Num_roomsValue;
}
int house::GetNum_rooms() const { return this->num_rooms; }
void house::PrintInfo() const
{
cout << this->color << " " << this->price << " " << this->num_rooms << endl;
}
| true |
ce81b55d6d157fe59edd17be3c7524988c60fd75 | C++ | AdirthaBorgohain/Seam-Carving | /SeamCarving.cpp | UTF-8 | 1,703 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
//#include"dijkstra.h"
using namespace std;
class pixel
{
public:
int vertex_no, pixel_value;
};
int main()
{
char id1,id2;
int h, w, maxvalue,i;
pixel **t1;
ifstream fp;
fp.open("test.pgm", ios::in);
fp >> id1 >> id2;
fp >> h >> w >> maxvalue;
t1 = new pixel *[w];
for(i = 0; i < h; i++)
t1[i] = new pixel [h];
for(i = 0; i < w; i++)
for(int j = 0; j < h; j++)
{
fp >> t1[i][j].pixel_value;
t1[i][j].vertex_no = (i * w)+ j;
}
//cout<<h<<"\t"<<w<<"\t"<<maxvalue;
fp.close();
for(i = 0; i < h; i++)
for(j = 0; j < w-1; j++)
{
gh.addEdge(t1[i][j].vertex_no, t1[i][j+1].vertex_no, abs(t1[i][j].pixel_value - t1[[i][j+1].vertex_no));
if(i == 0)
{
gh.addEdge(t1[i][j].vertex_no, t1[i+1][j+1].vertex_no, abs(t1[i][j].pixel_value - t1[[i+1][j+1].vertex_no));
}
else if(i == h-1)
{
gh.addEdge(t1[i][j].vertex_no, t1[i-1][j+1].vertex_no, abs(t1[i][j].pixel_value - t1[[i-1][j+1].vertex_no));
}
else
{
gh.addEdge(t1[i][j].vertex_no, t1[i-1][j+1].vertex_no, abs(t1[i][j].pixel_value - t1[[i-1][j+1].vertex_no));
gh.addEdge(t1[i][j].vertex_no, t1[i+1][j+1].vertex_no, abs(t1[i][j].pixel_value - t1[[i+1][j+1].vertex_no));
}
}
for(i = 0; i < w; i++)
{
for(int j = 0; j < h; j++)
cout << t1[i][j].pixel_value << "\t";
cout << endl;
}
}
| true |
b0f3771c04683a2d9e9032e204cb2b09de64138c | C++ | walker0643/testxhotkeys | /xhotkeys.h | UTF-8 | 698 | 2.5625 | 3 | [] | no_license | #pragma once
#include "xkeygrab.h"
#include <map>
class XHotkeys
{
public:
typedef unsigned int keyid_t;
explicit XHotkeys(Display * display, Window window) :
_display(display),
_window(window)
{ }
keyid_t grab(KeySym keysym, unsigned int modifiers);
void ungrab(KeySym keysym, unsigned int modifiers);
void ungrab(keyid_t id);
bool is_hotkey_event(const XEvent& ev, keyid_t *pid_out = nullptr) const;
bool id_exists(keyid_t id) const;
Display * display() const { return _display; }
Window window() const { return _window; }
private:
Display * const _display;
const Window _window;
std::map<keyid_t, XKeyGrab> _keygrab;
};
| true |
01914921887a5684d42028ff390f7764f50bf0c7 | C++ | piotrpopiolek/Code | /Szkoła Programowania/Rozdział 2 Listing 2.5 ourfunc/Rozdział 1 Listing 2.5 ourfunc/ourfunc.cpp | UTF-8 | 341 | 3.171875 | 3 | [] | no_license | #include<iostream>
void simon(int);
int main()
{
using namespace std;
simon(3);
cout << "Podaj liczbe calkowita: ";
int count;
cin >> count;
simon(count);
cout << "Gotowe!" << endl;
system("pause");
return 0;
}
void simon(int n)
{
using namespace std;
cout << "Simon prosi, abys dotknal palcow u stop " << n << " razy." << endl;
} | true |
61e7a20138f59bb07c18506b341cb8c2242c7fab | C++ | ericlivergood/dataluge | /Spiral.h | UTF-8 | 652 | 2.609375 | 3 | [] | no_license | #include <objbase.h>
#pragma once
//The "spiral" is the track on which one luges. Kinda looks like a pipe.
//This class is intended to facilitate to transfer between two of our VDISockets, or a pipe.
//Super simple implementation for now:
// No buffering, no name resolution; just connect to both sides call recv then send
class Spiral
{
public:
Spiral(void);
~Spiral(void);
HRESULT Initialize();
HRESULT Transfer();
private:
HRESULT NetworkingCleanup(void);
static HRESULT ConnectTo(SOCKET* Socket, LPCSTR Address, LPCSTR Port);
LPCSTR SourcePort;
LPCSTR SourceAddr;
LPCSTR DestPort;
LPCSTR DestAddr;
SOCKET Source;
SOCKET Dest;
};
| true |
c58cbe2cb75a4ccf1740137c08039cbc8c08e1ce | C++ | DennyLindberg/Tree-Generator | /source/generation/turtle3d.h | UTF-8 | 5,354 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "../opengl/mesh.h"
#include "../core/math.h"
#include <map>
#include <stack>
#include <functional>
template<class OptionalState = int>
struct TurtleTransform
{
glm::fvec3 position = glm::fvec3{ 0.0f };
glm::fvec3 forward = glm::fvec3{ 0.0f, 1.0f, 0.0f }; // the direction the turtle is travelling (Y+ by default)
glm::fvec3 up = glm::fvec3{ 0.0f, 0.0f, 1.0f }; // orthogonal to the forward direction, used for orientation (Z+ by default)
OptionalState properties;
void Clear()
{
position = glm::fvec3{ 0.0f };
forward = glm::fvec3{ 0.0f, 1.0f, 0.0f };
up = glm::fvec3{ 0.0f, 0.0f, 1.0f };
}
};
template<class OptionalState = int>
struct Bone
{
using TBone = Bone<OptionalState>;
TBone* parent = nullptr;
TBone* firstChild = nullptr;
TBone* lastChild = nullptr;
TBone* previousSibling = nullptr;
TBone* nextSibling = nullptr;
TurtleTransform<OptionalState> transform;
float length = 0.0f;
int nodeDepth = 1; // distance from root bone in the node tree
Bone() = default;
~Bone()
{
Clear();
}
glm::fvec3 tipPosition()
{
return transform.position + transform.forward*length;
}
void Clear()
{
parent = nullptr;
transform.Clear();
length = 0.0f;
if (firstChild)
{
delete firstChild;
firstChild = nullptr;
}
if (nextSibling)
{
delete nextSibling;
nextSibling = nullptr;
}
}
TBone* NewChild()
{
TBone* newChild = new TBone();
if (!firstChild)
{
firstChild = newChild;
lastChild = newChild;
}
else
{
newChild->previousSibling = lastChild;
lastChild->nextSibling = newChild;
lastChild = newChild;
}
newChild->parent = this;
newChild->transform.position = this->tipPosition();
newChild->nodeDepth = this->nodeDepth + 1;
return newChild;
}
void DebugPrint(int depth = 0)
{
for (int i = 0; i < depth; ++i)
{
printf(" ");
}
printf("%d\n", nodeDepth);
if (firstChild)
{
firstChild->DebugPrint(depth+1);
}
if (nextSibling)
{
nextSibling->DebugPrint(depth);
}
}
void ForEach(std::function<void(TBone*)>& callback)
{
callback(this);
if (firstChild)
{
firstChild->ForEach(callback);
}
if (nextSibling)
{
nextSibling->ForEach(callback);
}
}
};
template<class OptionalState = int>
class Turtle3D
{
protected:
using TurtleBone = Bone<OptionalState>;
using TTransform = TurtleTransform<OptionalState>;
public:
std::map<char, std::function<void(Turtle3D&, int)>> actions;
TTransform transform;
std::stack<TTransform> transformStack;
std::stack<TurtleBone*> branchStack;
TurtleBone* activeBone = nullptr;
TurtleBone* rootBone = nullptr;
int boneCount = 0;
Turtle3D()
{
Clear();
}
~Turtle3D() = default;
void Clear()
{
transform.Clear();
boneCount = 0;
if (rootBone)
{
delete rootBone;
rootBone = nullptr;
activeBone = nullptr;
}
transformStack = std::stack<TTransform>();
branchStack = std::stack<TurtleBone*>();
}
void GenerateSkeleton(std::string& symbols, TTransform startTransform = TTransform{})
{
Clear();
transform = std::move(startTransform);
size_t size = symbols.size();
for (int i=0; i<size; i++)
{
int repetitionCounter = 1;
while ((i < int(size - 1)) && symbols[i] == symbols[i + 1])
{
repetitionCounter++;
i++;
}
if (actions.count(symbols[i]))
{
actions[symbols[i]](*this, repetitionCounter);
}
}
}
void PushState()
{
branchStack.push(activeBone);
transformStack.push(transform);
}
void PopState()
{
transform = transformStack.top();
transformStack.pop();
activeBone = branchStack.top();
branchStack.pop();
}
// Angles are related to the forward and up basis vectors. (Roll is applied first)
void Rotate(float rollDegrees, float pitchDegrees)
{
glm::mat4 identity{ 1 };
// Roll the forward direction
auto rollRot = glm::rotate(identity, glm::radians(rollDegrees), transform.forward);
transform.up = rollRot * glm::fvec4(transform.up, 0.0f);
// Change the up/down angle of the forward direction and up direction
glm::fvec3 pitchVector = glm::cross(transform.forward, transform.up);
Rotate(pitchDegrees, pitchVector);
}
void Rotate(float degrees, glm::fvec3 rotateVector)
{
auto rotateMatrix = glm::rotate(glm::mat4{ 1.0f }, glm::radians(degrees), rotateVector);
transform.forward = rotateMatrix * glm::fvec4(transform.forward, 0.0f);
transform.up = rotateMatrix * glm::fvec4(transform.up, 0.0f);
}
void MoveForward(float distance)
{
PushBone(distance);
transform.position += transform.forward*distance;
}
void PushBone(float length)
{
if (!rootBone)
{
rootBone = new TurtleBone{};
activeBone = rootBone;
}
else
{
activeBone = activeBone->NewChild();
}
activeBone->transform = transform;
activeBone->length = length;
boneCount++;
}
void ForEachBone(std::function<void(TurtleBone*)> callback)
{
if (rootBone && callback)
{
rootBone->ForEach(callback);
}
}
void BonesToGLLines(GLLine& lines, glm::fvec4 boneColor, glm::fvec4 normalColor)
{
ForEachBone([&lines, &boneColor, &normalColor](TurtleBone* b) -> void
{
lines.AddLine(
b->transform.position,
b->tipPosition(),
boneColor
);
lines.AddLine(
b->transform.position,
b->transform.position + b->transform.up*0.2f,
normalColor
);
});
lines.SendToGPU();
}
}; | true |
44b7826573dfade0c3c442991e02b29a6e7a4733 | C++ | Kracav4ik/saturn | /src/lab1/Frame.cpp | UTF-8 | 1,488 | 2.53125 | 3 | [] | no_license | #include "Frame.h"
#include <QDebug>
#include <QDragMoveEvent>
Frame::Frame(QWidget* parent)
: QGraphicsView(parent)
, fb(320, 240)
{
reset();
}
void Frame::drawFrame(ll::Matrix4x4 projection, ll::Matrix4x4 world, float angle) {
drawAPi.reset();
drawAPi.clear(fb, ll::Color(0.5, 0.5, 0.5));
drawAPi.pushMatrix(ll::Matrix4x4::toScreenSpace(fb.getW(), fb.getH()));
drawAPi.pushMatrix(projection);
drawAPi.pushMatrix(fullRot * currRot);
drawAPi.pushMatrix(world);
draw(drawAPi, angle);
drawAPi.drawFrame(fb);
auto pixels = fb.getColorsARGB32();
auto img = QImage((const uchar*)pixels.data(), fb.getW(), fb.getH(), QImage::Format_ARGB32);
auto pm = QPixmap::fromImage(img);
scene.clear();
scene.addPixmap(pm);
setScene(&scene);
show();
}
void Frame::setDrawer(DrawFunc drawFunc) {
draw = std::move(drawFunc);
}
void Frame::reset() {
fullRot = ll::Matrix4x4::identity();
currRot = ll::Matrix4x4::identity();
}
void Frame::mousePressEvent(QMouseEvent* event) {
startDragPoint = event->pos();
dragging = true;
}
void Frame::mouseMoveEvent(QMouseEvent* event) {
if (dragging) {
auto diff = event->pos() - startDragPoint;
currRot = ll::Matrix4x4::rotY(diff.x() / 100.f) * ll::Matrix4x4::rotX(diff.y() / 100.f);
}
}
void Frame::mouseReleaseEvent(QMouseEvent* event) {
fullRot = fullRot * currRot;
currRot = ll::Matrix4x4::identity();
dragging = false;
}
| true |
0401382e15bc9fb1f27560b33bfd5b783bd4717f | C++ | neeraj2296/programming-contest | /URI/Solved/C++/1174.cpp | UTF-8 | 302 | 2.703125 | 3 | [] | no_license | /*
Author: Auro Mota <auro@blueorc.com>
*/
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
int i;
float b[100];
for(i=0;i<100;i++) {
scanf("%f", &b[i]);
if(b[i]<=10) {
cout << "A[" << i << "] = " << b[i] << endl;
}
}
return 0;
}
| true |
846e273a9c6dd3ee14624d3f072efef689ddc0e0 | C++ | TeodorLys/VGA-Utillity | /VGAPlayer/src/Events/Animation.cpp | UTF-8 | 2,689 | 3.21875 | 3 | [] | no_license | #include "Animation.h"
using namespace std;
const double Animation::PI = 3.14159265;
sf::Uint8 Animation::Lerp_Opacity(sf::Uint8 value, const sf::Uint8 speed) {
if (value != 0 && speed < value) {
value -= (speed + 1);
return value;
}
else if (value < speed) {
return 0;
}
return 0;
}
sf::Uint8 Animation::Lerp_Opacity_Inverted(sf::Uint8 value, const sf::Uint8 speed) {
if (value != 0 && speed < value) {
value += (speed + 1);
return value;
}
else if (value < speed) {
return 0;
}
return 0;
}
sf::Uint8 Animation::Lerp_Value(sf::Uint8 start_Point, sf::Uint8 end_Point, const sf::Uint8 speed) {
if (start_Point != end_Point && start_Point - end_Point > speed || end_Point - start_Point > speed) {
if (start_Point < end_Point)
start_Point += (speed + 1);
else
start_Point -= (speed + 1);
return start_Point;
}
else {
return end_Point;
}
}
sf::Uint8 Animation::Lerp_Cosine(sf::Uint8 start_Point, sf::Uint8 end_Point, const sf::Uint8 speed, int &test, bool &done) {
if (test <= end_Point - 4) {
done = false;
test += speed;
return static_cast<int>(sin((float)test * PI / (float)end_Point) * (float)end_Point);
}
else {
done = true;
return 0;
}
}
float Animation::Lerp_float(float start_Point, float end_Point, float speed) {
if (start_Point != end_Point && start_Point - end_Point > speed || end_Point - start_Point > speed) {
if (start_Point < end_Point) {
start_Point += speed;
}
else {
start_Point -= speed;
}
return start_Point;
}
else {
return end_Point;
}
}
sf::Color Animation::Lerp_Color(sf::Color ref, sf::Color end_Point, const float speed, std::string colr) {
ref.r = Animation::Lerp_Value(ref.r, end_Point.r, static_cast<sf::Uint8>(speed));
ref.g = Animation::Lerp_Value(ref.g, end_Point.g, static_cast<sf::Uint8>(speed));
ref.b = Animation::Lerp_Value(ref.b, end_Point.b, static_cast<sf::Uint8>(speed));
return ref;
}
sf::Color Animation::Lerp_Color(sf::Color ref, sf::Color end_Point, const float speedR, const float speedG, const float speedB, std::string colr) {
ref.r = Animation::Lerp_Value(ref.r, end_Point.r, static_cast<sf::Uint8>(speedR));
ref.g = Animation::Lerp_Value(ref.g, end_Point.g, static_cast<sf::Uint8>(speedG));
ref.b = Animation::Lerp_Value(ref.b, end_Point.b, static_cast<sf::Uint8>(speedB));
return ref;
}
float Animation::Lerp_Position(float start_Point, float end_Point, const sf::Uint8 speed) {
if (start_Point != end_Point && start_Point - end_Point > speed || end_Point - start_Point > speed) {
if (start_Point < end_Point)
start_Point += (speed + 1);
else
start_Point -= (speed + 1);
return start_Point;
}
else {
return end_Point;
}
}
| true |
e1ed5c9ed257e140f6f4eac7b769f1e94208bc33 | C++ | dylsmith/ITS-MTCDataParser | /ConsoleApplication2/VGroup.cpp | UTF-8 | 2,853 | 3.015625 | 3 | [] | no_license | #include "stdafx.h"
#include "VGroup.h"
#include "DataClasses.h"
using namespace std;
VGroup::VGroup(Trip& t)
{
leader = &t;
trips.push_back(&t);
}
VGroup::~VGroup()
{
for (Trip* t : trips)
{
t->group = NULL;
}
}
bool VGroup::canAddTrip(Trip& t2)
{
if (!t2.shared || (t2.group && t2.group->trips.size() > 1) || all_people[t2.perid].totalScore < sharingRequirement) //If trip is already sharing with others
return false;
if (Maximize)
{
if (trips.size() >= MaxPeople)
{
return false;
}
}
else
{
if (trips.size() >= MinPeople)
{
return false;
}
}
int numPassengers = 0;
for (Trip* t1 : trips) //Sum numPassengers, or return false if the t2 cannot share with a trip in the group
{
if (!strictCompare(*t1, t2))
{
return false;
}
}
return true;
/*
if (Maximize) //Keep returning true until the car is full
return(numPassengers <= MaxPeople);
else //Keep returning true until the car has a certain number of people
return(numPassengers >= MinPeople && numPassengers <= MaxPeople);
*/
}
//Try to avoid sharing drivers initially
void VGroup::addTrip(Trip& t2)
{
//Add t2 to the group's trips, set t2 and the leader as doable, delete t2's old group if needed
trips.push_back(&t2);
leader->setDoable(true);
t2.setDoable(true);
#pragma omp critical
if (t2.group)
delete t2.group;
#pragma omp critical
t2.group = this;
}
void VGroup::removeTrip(Trip& t1)
{
if (t1.shared)
{
t1.shared = false;
t1.setDoable(false);
int size = trips.size();
unshared++;
if (size == 2)//If t1 shares with one other
{
Trip* t2; //Get t2's id from the group
if (*trips.begin() == &t1)
t2 = *trips.rbegin();
else
t2 = *trips.begin();
delete t1.group;
t1.group = new VGroup(t1);//Form a solo group for t1
t2->group = NULL; //And orphan t2
t2->setDoable(false);
}
else if (size > 2) //if t1 shares with multiple others
{
removeFromTrips(t1); //Remove t1, and give it a new solo group.
VGroup* group = t1.group;
bool wasLeader = group->leader == &t1;
t1.group = new VGroup(t1);
//Try to find a new driver for the group, if t1 was the old driver
bool foundNewDriver = false;
if (wasLeader)
{
for (Trip* t2 : group->trips)
{
if (DrivingModes[t2->mode]) //If new driver is found, set it as driver and stop looking
{
foundNewDriver = true;
group->leader = t2;
break;
}
}
if (!foundNewDriver) //If no new driver was found, disband the group
{
for (Trip* t2 : group->trips)
{
t2->setDoable(false);
t2->group = new VGroup(*t2);
}
delete group;
}
}
}
}
}
//Search through the vrgoup, find t, remove it
void VGroup::removeFromTrips(Trip& t)
{
vector<Trip*>::iterator it = trips.begin();
while (*it != &t)
it++;
it = trips.erase(it);
} | true |
d6acfee1a110df76b137b5ae676fc403d9a0a02a | C++ | csimstu/OI | /hdu/bzoj/p1588.cpp | UTF-8 | 2,219 | 2.734375 | 3 | [] | no_license | #include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAXN 100000 * 2
#define INF 1 << 30
#define UNDEF INF
struct node
{
node *pre, *ch[2];
int value, size;
} tree[MAXN], *root, *Null;
int top1 = 0;
int n;
long long ans = 0;
node *New_Node(int v)
{
node *x;
x = &tree[top1 ++];
x->value = v, x->size = 1;
x->pre = x->ch[0] = x->ch[1] = Null;
return x;
}
void Update(node *x)
{
x->size = x->ch[0]->size + x->ch[1]->size + 1;
}
void Rotate(node *x, int c)
{
node *y = x->pre;
y->ch[! c] = x->ch[c];
if(x->ch[c] != Null) x->ch[c]->pre = y;
x->pre = y->pre;
if(y->pre != Null) y->pre->ch[y == y->pre->ch[1]] = x;
y->pre = x, x->ch[c] = y;
if(y == root) root = x;
Update(y);
}
void Splay(node *x, node *f)
{
while(x->pre != f)
{
if(x->pre->pre == f)
Rotate(x, x->pre->ch[0] == x);
else
{
node *y = x->pre, *z = y->pre;
if(y == z->ch[0])
if(x == y->ch[0]) Rotate(y, 1), Rotate(x, 1);
else Rotate(x, 0), Rotate(x, 1);
else
if(x == y->ch[1]) Rotate(y, 0), Rotate(x, 0);
else Rotate(x, 1), Rotate(x, 0);
}
}
Update(x);
}
node *Insert(int value)
{
node *now, *p;
for(now = root; ; )
{
if(now->value > value)
{
if(now->ch[0] != Null) now = now->ch[0];
else break;
}
else
if(now->ch[1] != Null) now = now->ch[1];
else break;
}
if(now->value > value)
{
now->ch[0] = New_Node(value);
p = now->ch[0];
}
else
{
now->ch[1] = New_Node(value);
p = now->ch[1];
}
p->pre = now;
Splay(p, Null);
return p;
}
int main()
{
freopen("t.in","r",stdin);
Null = New_Node(UNDEF), Null->size = 0;
root = New_Node(UNDEF), root->ch[1] = New_Node(UNDEF), root->ch[1]->pre = root;
Update(root);
scanf("%d",&n);
int i = 0;
while(i < n)
{
i++;
int v = 0;
////if(feof(stdin)) v = 0;
scanf("%d",&v);
node *p = Insert(v);
if(i == 1)
{
ans = v;
continue;
}
node *x = p->ch[0];
if(x != Null)
while(x->ch[1] != Null) x = x->ch[1];
node *y = p->ch[1];
if(y != Null)
while(y->ch[0] != Null) y = y->ch[0];
if(x == Null) ans += abs(y->value - v);
else if(y == Null) ans += abs(x->value - v);
else ans += min(abs(x->value - v), abs(y->value - v));
}
printf("%lld\n",ans);
}
| true |
e19923b0fa62424e659ffcd847f1fc385cf1892b | C++ | the-iron-ryan/RyanDougherty-CS-3505 | /Assignment2/huge_integer.cpp | UTF-8 | 6,667 | 3.953125 | 4 | [] | no_license | #include "huge_integer.h"
#include <iostream>
using namespace std;
huge_integer::huge_integer(const string & s)
{
//check to see if the string contains ONLY non-negative integers
if(!(s.find_first_not_of("0123456789") == string::npos))
val = "0"; //assign default value of 0 if the passed string is not a non-negative integer
else
val = s;
}
huge_integer::huge_integer()
{
val = "0";
}
huge_integer::huge_integer(const huge_integer & other)
{
val = other.val;
}
string huge_integer::get_value() const
{
return val;
}
huge_integer& huge_integer::operator=(const huge_integer right)
{
this->val = right.val;
return *this;
}
huge_integer huge_integer::operator+(const huge_integer right) const
{
string result = "";
string leftNumString = this->get_value();
string rightNumString = right.get_value();
//get lengths of left and right strings
int leftPos = leftNumString.length() - 1;
int rightPos = rightNumString.length() - 1;
int carry = 0;
while(leftPos >= 0 || rightPos >= 0 || carry > 0)
{
//get the left and right digit of the strings if they exist
//if not, then set them to 0.
//subtracting the char 0 from the returned character will yeild
//the integer value of the character.
int leftDigit = leftPos >= 0 ? leftNumString[leftPos--] - '0' : 0;
int rightDigit = rightPos >= 0 ? rightNumString[rightPos--] - '0' : 0;
//add the two digits and the carried value together
int sum = leftDigit + rightDigit + carry;
//the carried value will be the the number in the 10's digit.
//the sum integer will be the value in the 1's digit.
carry = sum / 10;
sum = sum % 10;
//insert the sum into the final result
result.insert(0, 1, (char)(sum + '0'));
}
//delete all leading zeros
//while(result.length() > 1 && result[0] == '0')
//result.erase(0, 1);
//create
huge_integer returnedVal(result);
return returnedVal;
}
huge_integer huge_integer::operator-(const huge_integer right) const
{
string result = "";
string leftNumString = this->get_value();
string rightNumString = right.get_value();
//get lengths of left and right strings
int leftPos = leftNumString.length() - 1;
int rightPos = rightNumString.length() - 1;
while(leftPos >= 0 || rightPos >= 0)
{
//get the left and right digit of the strings if they exist
//if not, then set them to 0.
//subtracting the char 0 from the returned character will yeild
//the integer value of the character.
int leftDigit = leftPos >= 0 ? leftNumString[leftPos] - '0' : 0;
int rightDigit = rightPos >= 0 ? rightNumString[rightPos] - '0' : 0;
if(leftDigit < rightDigit)
{
if(!borrow(leftNumString, rightNumString, leftPos, rightPos))
{
huge_integer defaultInteger;
return defaultInteger;
}
leftDigit = leftPos >= 0 ? leftNumString[leftPos] - '0' : 0;
rightDigit = rightPos >= 0 ? rightNumString[rightPos] - '0' : 0;
}
leftPos--;
rightPos--;
//subtract the two digits together
int difference = leftDigit - rightDigit;
result.insert(0, 1, (char)(difference + '0'));
}
huge_integer returnedVal(result);
return returnedVal;
}
huge_integer huge_integer::operator*(const huge_integer right) const
{
string result = "";
string leftNumString = this->get_value();
string rightNumString = right.get_value();
int rightPos = 0;
while(rightPos < (int)rightNumString.length())
{
//multiply the number by 10
result.append("0");
int rightDigit = rightNumString[rightPos++] - '0';
for(int i = 0; i < rightDigit; i++)
{
//add the right to the left the amount of the right
//digit
result = (*this + huge_integer(result)).get_value();
}
}
return huge_integer(result);
}
huge_integer huge_integer::operator/(const huge_integer right) const
{
string result = "";
string rightNumString = this->get_value();
string leftNumString = this->get_value();
//check for divide by zero division
if(rightNumString == "0" || leftNumString == "0")
{
return huge_integer("0");
}
int leftPos = 0, rightPos = 0;
int leftLength = leftNumString.length(), rightLength = rightNumString.length();
int leftDigit = leftNumString[leftPos] - '0';
int rightDigit = rightNumString[rightPos] - '0';
while(leftPos < (int)leftNumString.length())
{
if(leftDigit > rightDigit)
{
//TODO: right string could be only 1 big
leftDigit += leftNumString[++leftPos] - '0';
}
bool isCorrectGuess = false;
while(!isCorrectGuess)
{
int divisionResult = rightDigit / leftDigit;
huge_integer a (rightNumString.substr(0, rightPos));
huge_integer b (std::to_string(divisionResult));
huge_integer c = a * b;
if(c < right)
{
}
else if(c > right <F11>)
{
}
else
{
isCorrectGuess = true;
}
}
}
return huge_integer("0");
}
huge_integer huge_integer::operator%(const huge_integer right) const
{
huge_integer divisionResult = *this / right;
huge_integer multiplicationResult = divisionResult * right;
return *this - multiplicationResult;
}
//========================
//Comparison Operators
//========================
bool huge_integer::operator<(const huge_integer right) const
{
}
bool huge_integer::operator>(const huge_integer right) const
{
}
bool huge_integer::operator==(const huge_integer right) const
{
}
//========================
//Private Helper Functions
//========================
bool huge_integer::borrow(string & leftString, string & rightString, int leftPos, int rightPos) const
{
int startingPos = leftPos;
int leftDigit = leftPos >= 0 ? leftString[leftPos] - '0' : 0;
int rightDigit = rightPos >= 0 ? rightString[rightPos] - '0' : 0;
//keep comparing left and right digits untill the highest up one is
//found
while(leftDigit < rightDigit)
{
leftPos--;
rightPos--;
//if it fully traverses the left string and cant borrow, then
//the string cannot be subtracted (will be negative)
if(leftPos < 0)
return false;
leftDigit = leftPos >= 0 ? leftString[leftPos] - '0' : 0;
rightDigit = rightPos >= 0 ? rightString[rightPos] - '0' : 0;
}
//the last borrow position has been found, now continue to borrow from
//leading numbers
while(leftPos < startingPos)
{
leftString[leftPos] -= 1;
leftString[leftPos + 1] += 10;
leftPos++;
}
return true;
}
int main(int argc, char* argv[])
{
huge_integer a("10");
huge_integer b("333333");
huge_integer c;
c = a + b;
std::cout << c.get_value() << std::endl;
c = a * b;
std::cout << c.get_value() << std::endl;
huge_integer b("333333");
huge_integer e("555");
c = d - e;
std::cout << c.get_value() << std::endl;
huge_integer x ("8030440");
huge_integer y ("57433");
c = x / y;
std::cout << c.get_value() << std::endl;
}
| true |
f9869a2cb2dcbf2b4fe532728937d1a62e6f427a | C++ | KitKatCake/DaiyCoder | /ProjectCppTest/a.cpp | UTF-8 | 1,526 | 3.265625 | 3 | [] | no_license | //#include <iostream>
//using namespace std;
//class Date;
//class Time {
//public:
// Time(int h, int m, int s);
// //friend void display(Time&);
// void display(Date &);
//private:
// int hour;
// int minute;
// int sec;
//};
//int sum(int a, int b) {
// return a + b;
//}
//Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){}
///*void display(Time &t){
// cout << t.hour << ":"<< t.minute <<":"<< t.sec << endl;
//}*/
//class Date {
//public:
// Date(int y, int m, int d) {
// year = y;
// month = m;
// day = d;
// }
// friend void Time::display(Date&);
//private:
// int year;
// int month;
// int day;
//};
//void Time::display(Date& d) {
// cout << d.year << "/" << d.month << "/" << d.day << endl;
// cout << hour << ":" << minute << ":" << sec << endl;
//}
//int main()
//{
//
//// exit(0);
//
//
//// int a = 10;
//
//// cout << a << endl;
//
// //++a;
//
//
// Time t1(10, 13, 56);
//
// Date d1(2004, 25, 12);
//
// //t1.display(d1);
//
//
//
// //display(it);
//
// int i, j, m, n;
//
// i = 8;
//
// j = 10;
//
// m = ++i + j++;
//
// n = (++i) + (++j) + m;
//
// cout << i << '\t' << j << '\t' << m << '\t' << n << endl;
//
// //cout << a << endl;
//
// cout << sum(10, 20) << endl;
//
//
///*
//for (int i = 1; i <= 100; i++)
// if (i % 3 == 0 && i % 15 != 0)
// cout << "Flip" << endl;
// else if (i % 5 == 0 && i % 15 != 0)
// cout << "Flop" << endl;
// else if (i % 15 == 0)
// cout << "FlipFlop" << endl;
// else
// cout << i << endl;
//
//*/
//
//
//
//
//
//
//
// //return 0;
//} | true |
12d33edf273438d92bf485e7b5a30a077bf764c1 | C++ | otifik/algorithm | /1037.cpp | UTF-8 | 912 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int nc,np;
vector<int> coupon;
vector<int> product;
int totalValue;
int main(){
cin>>nc;
coupon.resize(nc);
for(int i=0;i<nc;i++){
cin>>coupon[i];
}
cin>>np;
product.resize(np);
for(int i=0;i<np;i++){
cin>>product[i];
}
sort(coupon.begin(),coupon.end(),greater<int>());
sort(product.begin(),product.end(),greater<int>());
int index=0;
for(int i=0;i<nc;i++){
if(coupon[i]>0&&product[index]>0){
totalValue+=coupon[i]*product[index];
index++;
}else {
break;
}
}
index=np-1;
for(int i=nc-1;i>=0;i--){
if(coupon[i]<0&&product[index]<0){
totalValue+=coupon[i]*product[index];
index--;
}else {
break;
}
}
cout<<totalValue;
return 0;
} | true |
09499e08672b4b53b525c180d7fd9fdf828e8815 | C++ | kmhk/SparkD | /SparkD/Engine/cvlibbase/Inc/Template.h | UTF-8 | 28,208 | 2.515625 | 3 | [] | no_license |
/*!
* \file Template.h
* \ingroup base
* \brief
* \author
*/
#pragma once
#include "cvlibbaseDef.h"
#include "Object.h"
#include "String.hpp"
#include "Plex.h"
#include <new>
namespace cvlib
{
struct _CVLIB_POSITION { };
typedef _CVLIB_POSITION* CVLIB_POSITION;
#define CVLIB_BEFORE_START_POSITION ((CVLIB_POSITION)-1L)
template<class TYPE>
void CVLIB_DECLSPEC constructElements1(TYPE* pElements, int nCount)
{
// first do bit-wise zero initialization
memset((void*)pElements, 0, nCount * sizeof(TYPE));
// then call the constructor(s)
for (; nCount--; pElements++)
::new((void*)pElements) TYPE;
}
template<class TYPE>
void CVLIB_DECLSPEC constructElements1(TYPE* pElements, int nCount, const TYPE& newelem)
{
// then call the constructor(s)
for (; nCount--; pElements++)
{
::new((void*)pElements) TYPE;
*pElements = newelem;
}
}
template<class TYPE>
void CVLIB_DECLSPEC destructElements1(TYPE* pElements, int nCount)
{
// call the destructor(s)
for (; nCount--; pElements++)
pElements->~TYPE();
}
template<class TYPE>
void CVLIB_DECLSPEC copyElements1(TYPE* pDest, const TYPE* pSrc, int nCount)
{
// default is element-copy using assignment
while (nCount--)
*pDest++ = *pSrc++;
}
template<class TYPE, class ARG_TYPE>
bool CVLIB_DECLSPEC compareElements1(const TYPE* pElement1, const ARG_TYPE* pElement2)
{
return *pElement1 == *pElement2;
}
template<class ARG_KEY>
inline uint CVLIB_DECLSPEC cvlHashKey(ARG_KEY key)
{
// default identity hash - works for most primitive values
return ((uintptr_t)(void*)(ulong)key) >> 4;
}
#ifdef _MSC_VER
//#if CVLIB_OS==CVLIB_OS_WIN32
#if _MSC_VER >= 1100
template<> void CVLIB_DECLSPEC constructElements1<String>(String* pElements, int nCount);
template<> void CVLIB_DECLSPEC destructElements1<String>(String* pElements, int nCount);
template<> void CVLIB_DECLSPEC copyElements1<String>(String* pDest, const String* pSrc, int nCount);
template<> uint CVLIB_DECLSPEC cvlHashKey<const String&>(const String& key);
#else // _MSC_VER >= 1100
void CVLIB_DECLSPEC constructElements1(String* pElements, int nCount);
void CVLIB_DECLSPEC destructElements1(String* pElements, int nCount);
void CVLIB_DECLSPEC copyElements1(String* pDest, const String* pSrc, int nCount);
uint CVLIB_DECLSPEC cvlHashKey(const String& key);
#endif
#elif CVLIB_OS==CVLIB_OS_APPLE
template<> void CVLIB_DECLSPEC constructElements1<String>(String* pElements, int nCount);
template<> void CVLIB_DECLSPEC destructElements1<String>(String* pElements, int nCount);
template<> void CVLIB_DECLSPEC copyElements1<String>(String* pDest, const String* pSrc, int nCount);
template<> uint CVLIB_DECLSPEC cvlHashKey<const String&>(const String& key);
#else
template<> void CVLIB_DECLSPEC constructElements1<String>(String* pElements, int nCount);
template<> void CVLIB_DECLSPEC destructElements1<String>(String* pElements, int nCount);
template<> void CVLIB_DECLSPEC copyElements1<String>(String* pDest, const String* pSrc, int nCount);
template<> uint CVLIB_DECLSPEC cvlHashKey<const String&>(const String& key);
#endif
/////////////////////////////////////////////////////////////////////////////
// #define new new(__FILE__, __LINE__)
template<class TYPE, class ARG_TYPE = const TYPE&>
class CVLIB_DECLSPEC ConstArray : public Object
{
public:
typedef ConstArray<TYPE, ARG_TYPE> _MyArray;
ConstArray() {
m_fcopydata = false;
m_pData = 0; m_nSize = m_nMaxSize = m_nGrowBy = 0;
}
ConstArray(const _MyArray& t) {
m_fcopydata = false;
m_pData = t.m_pData;
m_nSize = m_nMaxSize = t.m_nSize;
m_nGrowBy = 0;
}
ConstArray(const TYPE* parray, int len) {
m_fcopydata = false;
m_pData = parray;
m_nSize = m_nMaxSize = len;
m_nGrowBy = 0;
}
_MyArray& operator=(const _MyArray& other)
{
if (this == &other)
return *this;
removeAll();
append(other);
return *this;
}
virtual void removeAll() { m_pData = 0; m_nSize = m_nMaxSize = m_nGrowBy = 0; }
int getSize() const { return m_nSize; }
int length() const { return m_nSize; }
int getUpperBound() const { return m_nSize - 1; }
const TYPE& getAt(int nIndex) const { assert(nIndex >= 0 && nIndex < m_nSize); return m_pData[nIndex]; }
const TYPE* getData() const { return (const TYPE*)m_pData; }
const TYPE& operator[](int nIndex) const { return getAt(nIndex); }
const TYPE& front() const { return getAt(0); }
const TYPE& back() const { return getAt(getSize() - 1); }
bool isEmpty() const { return m_nSize == 0; }
protected:
TYPE* m_pData;
int m_nSize; // # of elements (upperBound - 1)
int m_nMaxSize;
int m_nGrowBy;
bool m_fcopydata;
public:
~ConstArray() {
removeAll();
}
};
template<class TYPE, class ARG_TYPE = const TYPE&>
class CVLIB_DECLSPEC Array : public Object
{
public:
typedef Array<TYPE, ARG_TYPE> _MyArray;
public:
Array() { m_fcopydata = true; m_pData = 0; m_nSize = m_nMaxSize = m_nGrowBy = 0; }
Array(int nSize, const TYPE& _V = TYPE())
{
m_fcopydata = true;
m_pData = NULL;
m_nSize = m_nMaxSize = m_nGrowBy = 0;
setSize(nSize);
for (int i = 0; i < getSize(); i++)
m_pData[i] = _V;
}
Array(const _MyArray& other)
{
m_fcopydata = true;
m_pData = NULL;
m_nSize = m_nMaxSize = m_nGrowBy = 0;
append(other);
}
Array(const TYPE* parray, int len, bool fcopydata = true)
{
m_fcopydata = fcopydata;
if (fcopydata) {
m_pData = NULL;
m_nSize = m_nMaxSize = m_nGrowBy = 0;
append(parray, len);
}
else {
m_pData = (TYPE*)parray;
m_nSize = m_nMaxSize = len;
m_nGrowBy = 0;
}
}
_MyArray& operator=(const _MyArray& other)
{
if (this == &other)
return *this;
removeAll();
m_fcopydata = true;
append(other);
return *this;
}
// Attributes
void setSize(int nNewSize, int nGrowBy = -1);
void resize(int nNewSize, ARG_TYPE newElement = TYPE());
// Operations
void freeExtra();
void removeAll();
inline void setAt(int nIndex, ARG_TYPE newElement) { assert(nIndex >= 0 && nIndex < m_nSize); m_pData[nIndex] = newElement; }
inline int add(ARG_TYPE newElement) { int nIndex = m_nSize; setAtGrow(nIndex, newElement); return nIndex; }
void setAtGrow(int nIndex, ARG_TYPE newElement);
int append(const Array& src);
int append(const TYPE* parray, int size);
void copyFrom(const Array& src);
void removeAt(int nIndex, int nCount = 1);
void insertAt(int nIndex, ARG_TYPE newElement = TYPE(), int nCount = 1);
void insertAt(int nStartIndex, Array* pNewArray);
void insertAt(int nStartIndex, const _MyArray& newArray);
void swap(_MyArray& aray);
// readonly apis
inline const TYPE& operator[](int nIndex) const { return getAt(nIndex); }
inline operator const TYPE*() const { return (const TYPE*)m_pData; }
inline const TYPE& getAt(int nIndex) const { assert(nIndex >= 0 && nIndex < m_nSize); return m_pData[nIndex]; }
inline const TYPE* getData() const { return (const TYPE*)m_pData; }
inline const TYPE& front() const { return getAt(0); }
inline const TYPE& back() const { return getAt(getSize() - 1); }
// write apis
inline TYPE& operator[](int nIndex) { return getAt(nIndex); }
inline operator TYPE*() { return (TYPE*)m_pData; }
inline TYPE& getAt(int nIndex) { assert(nIndex >= 0 && nIndex < m_nSize); return m_pData[nIndex]; }
inline TYPE* getData() { return (TYPE*)m_pData; }
inline TYPE& front() { return getAt(0); }
inline TYPE& back() { return getAt(getSize() - 1); }
inline void pushBack(ARG_TYPE t) { add(t); }
inline void popBack() { removeAt(getSize() - 1); }
int getSize() const { return m_nSize; }
int length() const { return m_nSize; }
int getUpperBound() const { return m_nSize - 1; }
bool isEmpty() const { return m_nSize == 0; }
public:
~Array();
protected:
TYPE* m_pData;
int m_nSize; // # of elements (upperBound - 1)
int m_nMaxSize;
int m_nGrowBy;
bool m_fcopydata;
};
/////////////////////////////////////////////////////////////////////////////
// Array<TYPE, ARG_TYPE> inline functions
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::removeAll() {
if (m_fcopydata)
setSize(0, -1);
else {
m_fcopydata = true;
m_pData = 0; m_nSize = m_nMaxSize = m_nGrowBy = 0;
}
}
/////////////////////////////////////////////////////////////////////////////
// Array<TYPE, ARG_TYPE> out-of-line functions
template<class TYPE, class ARG_TYPE>
Array<TYPE, ARG_TYPE>::~Array()
{
assert(this);
if (m_fcopydata) {
if (m_pData != NULL)
{
destructElements1<TYPE>(m_pData, m_nSize);
delete[](uchar*)m_pData;
}
}
else {
m_fcopydata = true;
m_pData = 0; m_nSize = m_nMaxSize = m_nGrowBy = 0;
}
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::setSize(int nNewSize, int _nGrowBy)
{
assert(this);
assert(nNewSize >= 0);
if (_nGrowBy != -1)
m_nGrowBy = _nGrowBy; // set new size
if (nNewSize == 0)
{
// shrink to nothing
if (m_pData != NULL)
{
destructElements1<TYPE>(m_pData, m_nSize);
delete[](uchar*)m_pData;
m_pData = NULL;
}
m_nSize = m_nMaxSize = 0;
}
else if (m_pData == NULL)
{
// create one with exact size
#ifdef SIZE_T_MAX
assert(nNewSize <= SIZE_T_MAX / sizeof(TYPE)); // no overflow
#endif
m_pData = (TYPE*) new uchar[nNewSize * sizeof(TYPE)];
constructElements1<TYPE>(m_pData, nNewSize);
m_nSize = m_nMaxSize = nNewSize;
}
else if (nNewSize <= m_nMaxSize)
{
// it fits
if (nNewSize > m_nSize)
{
// initialize the new elements
constructElements1<TYPE>(&m_pData[m_nSize], nNewSize - m_nSize);
}
else if (m_nSize > nNewSize)
{
// destroy the old elements
destructElements1<TYPE>(&m_pData[nNewSize], m_nSize - nNewSize);
}
m_nSize = nNewSize;
}
else
{
// otherwise, grow array
int nGrowBy = m_nGrowBy;
if (nGrowBy == 0)
{
// heuristically determine growth when nGrowBy == 0
// (this avoids heap fragmentation in many situations)
nGrowBy = m_nSize / 8;
nGrowBy = (nGrowBy < 4) ? 4 : ((nGrowBy > 1024) ? 1024 : nGrowBy);
}
int nNewMax;
if (nNewSize < m_nMaxSize + nGrowBy)
nNewMax = m_nMaxSize + nGrowBy; // granularity
else
nNewMax = nNewSize; // no slush
assert(nNewMax >= m_nMaxSize); // no wrap around
#ifdef SIZE_T_MAX
assert(nNewMax <= SIZE_T_MAX / sizeof(TYPE)); // no overflow
#endif
TYPE* pNewData = (TYPE*) new uchar[nNewMax * sizeof(TYPE)];
// copy new data from old
memcpy((void*)pNewData, (const void*)m_pData, m_nSize * sizeof(TYPE));
// construct remaining elements
assert(nNewSize > m_nSize);
constructElements1<TYPE>(&pNewData[m_nSize], nNewSize - m_nSize);
// get rid of old stuff (note: no destructors called)
delete[](uchar*)m_pData;
m_pData = pNewData;
m_nSize = nNewSize;
m_nMaxSize = nNewMax;
}
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::resize(int nNewSize, ARG_TYPE elem)
{
assert(this);
assert(nNewSize >= 0);
if (nNewSize == 0)
{
// shrink to nothing
if (m_pData != NULL)
{
destructElements1<TYPE>(m_pData, m_nSize);
delete[](uchar*)m_pData;
m_pData = NULL;
}
m_nSize = m_nMaxSize = 0;
}
else if (m_pData == NULL)
{
// create one with exact size
#ifdef SIZE_T_MAX
assert(nNewSize <= SIZE_T_MAX / sizeof(TYPE)); // no overflow
#endif
m_pData = (TYPE*) new uchar[nNewSize * sizeof(TYPE)];
constructElements1<TYPE>(m_pData, nNewSize, elem);
m_nSize = m_nMaxSize = nNewSize;
}
else if (nNewSize <= m_nMaxSize)
{
// it fits
if (nNewSize > m_nSize)
{
// initialize the new elements
constructElements1<TYPE>(&m_pData[m_nSize], nNewSize - m_nSize, elem);
}
else if (m_nSize > nNewSize)
{
// destroy the old elements
destructElements1<TYPE>(&m_pData[nNewSize], m_nSize - nNewSize);
}
m_nSize = nNewSize;
}
else
{
// otherwise, grow array
int nGrowBy = m_nGrowBy;
if (nGrowBy == 0)
{
// heuristically determine growth when nGrowBy == 0
// (this avoids heap fragmentation in many situations)
nGrowBy = m_nSize / 8;
nGrowBy = (nGrowBy < 4) ? 4 : ((nGrowBy > 1024) ? 1024 : nGrowBy);
}
int nNewMax;
if (nNewSize < m_nMaxSize + nGrowBy)
nNewMax = m_nMaxSize + nGrowBy; // granularity
else
nNewMax = nNewSize; // no slush
assert(nNewMax >= m_nMaxSize); // no wrap around
#ifdef SIZE_T_MAX
assert(nNewMax <= SIZE_T_MAX / sizeof(TYPE)); // no overflow
#endif
TYPE* pNewData = (TYPE*) new uchar[nNewMax * sizeof(TYPE)];
// copy new data from old
memcpy((void*)pNewData, (const void*)m_pData, m_nSize * sizeof(TYPE));
// construct remaining elements
assert(nNewSize > m_nSize);
constructElements1<TYPE>(&pNewData[m_nSize], nNewSize - m_nSize, elem);
// get rid of old stuff (note: no destructors called)
delete[](uchar*)m_pData;
m_pData = pNewData;
m_nSize = nNewSize;
m_nMaxSize = nNewMax;
}
}
template<class TYPE, class ARG_TYPE>
int Array<TYPE, ARG_TYPE>::append(const Array& src)
{
assert(this);
assert(this != &src); // cannot append to itself
int nOldSize = m_nSize;
setSize(m_nSize + src.m_nSize);
copyElements1<TYPE>(m_pData + nOldSize, src.m_pData, src.m_nSize);
return nOldSize;
}
template<class TYPE, class ARG_TYPE>
int Array<TYPE, ARG_TYPE>::append(const TYPE* parray, int size)
{
assert(this);
int nOldSize = m_nSize;
setSize(m_nSize + size);
copyElements1<TYPE>(m_pData + nOldSize, parray, size);
return nOldSize;
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::copyFrom(const Array& src)
{
assert(this);
assert(this != &src); // cannot append to itself
setSize(src.m_nSize);
copyElements1<TYPE>(m_pData, src.m_pData, src.m_nSize);
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::freeExtra()
{
assert(this);
if (m_nSize != m_nMaxSize && m_fcopydata)
{
// shrink to desired size
#ifdef SIZE_T_MAX
assert(m_nSize <= SIZE_T_MAX / sizeof(TYPE)); // no overflow
#endif
TYPE* pNewData = NULL;
if (m_nSize != 0)
{
pNewData = (TYPE*) new uchar[m_nSize * sizeof(TYPE)];
// copy new data from old
memcpy((void*)pNewData, (const void*)m_pData, m_nSize * sizeof(TYPE));
}
// get rid of old stuff (note: no destructors called)
delete[](uchar*)m_pData;
m_pData = pNewData;
m_nMaxSize = m_nSize;
}
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::setAtGrow(int nIndex, ARG_TYPE newElement)
{
assert(this);
assert(nIndex >= 0);
if (nIndex >= m_nSize)
setSize(nIndex + 1, -1);
m_pData[nIndex] = newElement;
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::insertAt(int nIndex, ARG_TYPE newElement, int nCount /*=1*/)
{
assert(this);
assert(nIndex >= 0); // will expand to meet need
assert(nCount > 0); // zero or negative size not allowed
if (nIndex >= m_nSize)
{
// adding after the end of the array
setSize(nIndex + nCount, -1); // grow so nIndex is valid
}
else
{
// inserting in the middle of the array
int nOldSize = m_nSize;
setSize(m_nSize + nCount, -1); // grow it to new size
// destroy intial data before copying over it
destructElements1<TYPE>(&m_pData[nOldSize], nCount);
// shift old data up to fill gap
memmove((void*)&m_pData[nIndex + nCount], (const void*)&m_pData[nIndex], (nOldSize - nIndex) * sizeof(TYPE));
// re-init slots we copied from
constructElements1<TYPE>(&m_pData[nIndex], nCount);
}
// insert new value in the gap
assert(nIndex + nCount <= m_nSize);
while (nCount--)
m_pData[nIndex++] = newElement;
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::removeAt(int nIndex, int nCount)
{
assert(this);
assert(nIndex >= 0);
assert(nCount >= 0);
assert(nIndex + nCount <= m_nSize);
// just remove a range
int nMoveCount = m_nSize - (nIndex + nCount);
destructElements1<TYPE>(&m_pData[nIndex], nCount);
if (nMoveCount)
memmove((void*)&m_pData[nIndex], (const void*)&m_pData[nIndex + nCount], nMoveCount * sizeof(TYPE));
m_nSize -= nCount;
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::insertAt(int nStartIndex, Array* pNewArray)
{
assert(this);
assert(pNewArray != NULL);
assert(pNewArray);
assert(nStartIndex >= 0);
if (pNewArray->getSize() > 0)
{
insertAt(nStartIndex, pNewArray->getAt(0), pNewArray->getSize());
for (int i = 0; i < pNewArray->getSize(); i++)
setAt(nStartIndex + i, pNewArray->getAt(i));
}
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::insertAt(int nStartIndex, const _MyArray& newArray)
{
assert(this);
assert(nStartIndex >= 0);
if (newArray.getSize() > 0)
{
int nCount = newArray.getSize();
if (nStartIndex >= m_nSize)
{
// adding after the end of the array
setSize(nStartIndex + nCount, -1); // grow so nIndex is valid
}
else
{
// inserting in the middle of the array
int nOldSize = m_nSize;
setSize(m_nSize + nCount, -1); // grow it to new size
// destroy intial data before copying over it
destructElements1<TYPE>(&m_pData[nOldSize], nCount);
// shift old data up to fill gap
memmove((void*)&m_pData[nStartIndex + nCount], (const void*)&m_pData[nStartIndex], (nOldSize - nStartIndex) * sizeof(TYPE));
// re-init slots we copied from
constructElements1<TYPE>(&m_pData[nStartIndex], nCount);
}
// insert new value in the gap
assert(nStartIndex + nCount <= m_nSize);
int i = 0;
while (nCount--)
m_pData[nStartIndex++] = newArray[i++];
}
}
template<class TYPE, class ARG_TYPE>
void Array<TYPE, ARG_TYPE>::swap(_MyArray& aray)
{
int nTemp;
TYPE* pType;
SWAP(m_nGrowBy, aray.m_nGrowBy, nTemp);
SWAP(m_nMaxSize, aray.m_nMaxSize, nTemp);
SWAP(m_nSize, aray.m_nSize, nTemp);
SWAP(m_pData, aray.m_pData, pType);
}
/************************************************************************/
/* */
/************************************************************************/
template<class KEY, class VALUE, class ARG_KEY = const KEY&, class ARG_VALUE = const VALUE&>
class CVLIB_DECLSPEC Map : public Object
{
protected:
// Association
struct mapAssoc
{
mapAssoc* pNext;
uint nHashValue; // needed for efficient iteration
KEY key;
VALUE value;
};
public:
// Construction
Map(int nBlockSize = 10);
// Attributes
// number of elements
int count() const;
bool isEmpty() const;
// lookup
bool lookup(ARG_KEY key, VALUE& rValue) const;
// Operations
// lookup and add if not there
VALUE& operator[](ARG_KEY key);
// add a new (key, value) pair
void setAt(ARG_KEY key, ARG_VALUE newValue);
// removing existing (key, ?) pair
bool removeKey(ARG_KEY key);
void removeAll();
// iterating all (key, value) pairs
CVLIB_POSITION getStartPosition() const;
void getNextAssoc(CVLIB_POSITION& rNextPosition, KEY& rKey, VALUE& rValue) const;
// advanced features for derived classes
uint getHashTableSize() const;
void initHashTable(uint hashSize, bool bAllocNow = true);
// Implementation
protected:
mapAssoc** m_pHashTable;
uint m_nHashTableSize;
int m_nCount;
mapAssoc* m_pFreeList;
struct Plex* m_pBlocks;
int m_nBlockSize;
mapAssoc* newAssoc();
void freeAssoc(mapAssoc*);
mapAssoc* getAssocAt(ARG_KEY, uint&) const;
public:
~Map();
};
/////////////////////////////////////////////////////////////////////////////
// Map<KEY, VALUE, ARG_KEY,ARG_VALUE> inline functions
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
inline int Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::count() const
{
return m_nCount;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
inline bool Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::isEmpty() const
{
return m_nCount == 0;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
inline void Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::setAt(ARG_KEY key, ARG_VALUE newValue)
{
(*this)[key] = newValue;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
inline CVLIB_POSITION Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::getStartPosition() const
{
return (m_nCount == 0) ? NULL : CVLIB_BEFORE_START_POSITION;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
inline uint Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::getHashTableSize() const
{
return m_nHashTableSize;
}
/////////////////////////////////////////////////////////////////////////////
// Map<KEY, VALUE, ARG_KEY,ARG_VALUE> out-of-line functions
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::Map(int nBlockSize)
{
assert(nBlockSize > 0);
m_pHashTable = NULL;
m_nHashTableSize = 17; // default size
m_nCount = 0;
m_pFreeList = NULL;
m_pBlocks = NULL;
m_nBlockSize = nBlockSize;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
void Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::initHashTable(uint nHashSize, bool bAllocNow)
//
// Used to force allocation of a hash table or to override the default
// hash table size of (which is fairly small)
{
assert(this);
assert(m_nCount == 0);
assert(nHashSize > 0);
if (m_pHashTable != NULL)
{
// free hash table
delete[] m_pHashTable;
m_pHashTable = NULL;
}
if (bAllocNow)
{
m_pHashTable = new mapAssoc*[nHashSize];
memset(m_pHashTable, 0, sizeof(mapAssoc*) * nHashSize);
}
m_nHashTableSize = nHashSize;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
void Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::removeAll()
{
assert(this);
if (m_pHashTable != NULL)
{
// destroy elements (values and keys)
for (uint nHash = 0; nHash < m_nHashTableSize; nHash++)
{
mapAssoc* pAssoc;
for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL;
pAssoc = pAssoc->pNext)
{
destructElements1<VALUE>(&pAssoc->value, 1);
destructElements1<KEY>(&pAssoc->key, 1);
}
}
}
// free hash table
delete[] m_pHashTable;
m_pHashTable = NULL;
m_nCount = 0;
m_pFreeList = NULL;
m_pBlocks->freeDataChain();
m_pBlocks = NULL;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::~Map()
{
removeAll();
assert(m_nCount == 0);
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
typename Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::mapAssoc* Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::newAssoc()
{
if (m_pFreeList == NULL)
{
// add another block
Plex* newBlock = Plex::create(m_pBlocks, m_nBlockSize, sizeof(Map::mapAssoc));
// chain them into free list
typename Map::mapAssoc* pAssoc = (typename Map::mapAssoc*) newBlock->data();
// free in reverse order to make it easier to debug
pAssoc += m_nBlockSize - 1;
for (int i = m_nBlockSize - 1; i >= 0; i--, pAssoc--)
{
pAssoc->pNext = m_pFreeList;
m_pFreeList = pAssoc;
}
}
assert(m_pFreeList != NULL); // we must have something
typename Map::mapAssoc* pAssoc = m_pFreeList;
m_pFreeList = m_pFreeList->pNext;
m_nCount++;
assert(m_nCount > 0); // make sure we don't overflow
constructElements1<KEY>(&pAssoc->key, 1);
constructElements1<VALUE>(&pAssoc->value, 1); // special construct values
return pAssoc;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
void Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::freeAssoc(typename Map::mapAssoc* pAssoc)
{
destructElements1<VALUE>(&pAssoc->value, 1);
destructElements1<KEY>(&pAssoc->key, 1);
pAssoc->pNext = m_pFreeList;
m_pFreeList = pAssoc;
m_nCount--;
assert(m_nCount >= 0); // make sure we don't underflow
// if no more elements, cleanup completely
if (m_nCount == 0)
removeAll();
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
typename Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::mapAssoc*
Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::getAssocAt(ARG_KEY key, uint& nHash) const
// find association (or return NULL)
{
nHash = cvlHashKey<ARG_KEY>(key) % m_nHashTableSize;
if (m_pHashTable == NULL)
return NULL;
// see if it exists
mapAssoc* pAssoc;
for (pAssoc = m_pHashTable[nHash]; pAssoc != NULL; pAssoc = pAssoc->pNext)
{
if (compareElements1(&pAssoc->key, &key))
return pAssoc;
}
return NULL;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
bool Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::lookup(ARG_KEY key, VALUE& rValue) const
{
assert(this);
uint nHash;
mapAssoc* pAssoc = getAssocAt(key, nHash);
if (pAssoc == NULL)
return false; // not in map
rValue = pAssoc->value;
return true;
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
VALUE& Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::operator[](ARG_KEY key)
{
assert(this);
uint nHash;
mapAssoc* pAssoc;
if ((pAssoc = GetAssocAt(key, nHash)) == NULL)
{
if (m_pHashTable == NULL)
initHashTable(m_nHashTableSize);
// it doesn't exist, add a new Association
pAssoc = newAssoc();
pAssoc->nHashValue = nHash;
pAssoc->key = key;
// 'pAssoc->value' is a constructed object, nothing more
// put into hash table
pAssoc->pNext = m_pHashTable[nHash];
m_pHashTable[nHash] = pAssoc;
}
return pAssoc->value; // return new reference
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
bool Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::removeKey(ARG_KEY key)
// remove key - return true if removed
{
assert(this);
if (m_pHashTable == NULL)
return false; // nothing in the table
mapAssoc** ppAssocPrev;
ppAssocPrev = &m_pHashTable[cvlHashKey<ARG_KEY>(key) % m_nHashTableSize];
mapAssoc* pAssoc;
for (pAssoc = *ppAssocPrev; pAssoc != NULL; pAssoc = pAssoc->pNext)
{
if (CompareElements1(&pAssoc->key, &key))
{
// remove it
*ppAssocPrev = pAssoc->pNext; // remove from list
FreeAssoc(pAssoc);
return true;
}
ppAssocPrev = &pAssoc->pNext;
}
return false; // not found
}
template<class KEY, class VALUE, class ARG_KEY, class ARG_VALUE>
void Map<KEY, VALUE, ARG_KEY, ARG_VALUE>::getNextAssoc(CVLIB_POSITION& rNextPosition, KEY& rKey, VALUE& rValue) const
{
assert(this);
assert(m_pHashTable != NULL); // never call on empty map
mapAssoc* pAssocRet = (mapAssoc*)rNextPosition;
assert(pAssocRet != NULL);
if (pAssocRet == (mapAssoc*)CVLIB_BEFORE_START_POSITION)
{
// find the first association
for (uint nBucket = 0; nBucket < m_nHashTableSize; nBucket++)
if ((pAssocRet = m_pHashTable[nBucket]) != NULL)
break;
assert(pAssocRet != NULL); // must find something
}
// find next association
mapAssoc* pAssocNext;
if ((pAssocNext = pAssocRet->pNext) == NULL)
{
// go to next bucket
for (uint nBucket = pAssocRet->nHashValue + 1;
nBucket < m_nHashTableSize; nBucket++)
if ((pAssocNext = m_pHashTable[nBucket]) != NULL)
break;
}
rNextPosition = (CVLIB_POSITION)pAssocNext;
// fill in return data
rKey = pAssocRet->key;
rValue = pAssocRet->value;
}
#define Vector Array
#define ConstVector ConstArray
template<class TYPE, class ARG_TYPE = const TYPE&>
class CVLIB_DECLSPEC Matrix : public Vector<Vector<TYPE, ARG_TYPE>, const Vector<TYPE, ARG_TYPE>&>
{
public:
typedef Matrix<TYPE, ARG_TYPE> _MyMatrix;
Matrix() {}
Matrix(int nRows, int nCols, const TYPE& _V = TYPE())
{
create(nRows, nCols, _V);
}
int create(int nRows, int nCols, const TYPE& _V = TYPE())
{
Vector<Vector<TYPE, ARG_TYPE>, const Vector<TYPE, ARG_TYPE>&>::removeAll();
Vector<Vector<TYPE, ARG_TYPE>, const Vector<TYPE, ARG_TYPE>&>::setSize(nRows);
for (int i = 0; i < Vector<Vector<TYPE, ARG_TYPE>, const Vector<TYPE, ARG_TYPE>&>::length(); i++)
{
Vector<Vector<TYPE, ARG_TYPE>, const Vector<TYPE, ARG_TYPE>&>::getAt(i).insertAt(0, _V, nCols);
}
return 1;
}
};
#pragma warning(disable: 4786)
#undef new
#ifdef _REDEF_NEW
//#define new new(__FILE__, __LINE__)
#undef _REDEF_NEW
#endif
} | true |
265f9ebb2197f30fa14528591a82eae8fd6d4243 | C++ | tony-montemuro/aoc-2020 | /day-5/day5.cpp | UTF-8 | 1,498 | 3.515625 | 4 | [] | no_license | //Programmer: Anthony Montemuro
//Date: 12/5/2020
//Description: Solution to Day 5 in Advent of Code 2020
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int getID(string s);
int getYourID(const vector<int>& v);
int main()
{
//Declare variables
int maxSeatID = 0;
vector<int> ids;
ifstream puzzle_input;
//Open file - if unable, return 1
puzzle_input.open("puzzleInput.txt");
if (!puzzle_input)
{
return 1;
}
while (!puzzle_input.eof())
{
string s;
puzzle_input >> s;
int i = getID(s);
if (i > maxSeatID)
{
maxSeatID = i;
}
ids.push_back(i);
}
sort(ids.begin(), ids.end());
//Print result to console
cout << maxSeatID << endl;
cout << getYourID(ids) << endl;
return 0;
}
int getID(string s)
{
/*
Precond: s is of type string, and represents a binary space partitioned seat.
Postcond: The seat ID is returned.
*/
int row, col, lower = 0, upper = 127;
for (int i = 0; i < 7; i++)
{
char c = s[i];
if (c == 'F')
{
upper = (lower + upper) / 2;
}
else
{
lower = (lower + upper) / 2 + 1;
}
}
row = upper;
lower = 0;
upper = 7;
for (int i = 7; i < 10; i++)
{
char c = s[i];
if (c == 'L')
{
upper = (lower + upper) / 2;
}
else
{
lower = (lower + upper) / 2 + 1;
}
}
col = upper;
return row * 8 + col;
}
int getYourID(const vector<int>& v)
{
for (int i = 0, j = v.at(i); i < v.size(); i++, j++)
{
if (v.at(i) != j)
{
return v.at(i) - 1;
}
}
return -1;
}
| true |
54f33ef0e913ba6ab007fd09271f7a34cf9a9f3c | C++ | Arinjbj/startcpp | /vsProject/vsProject/e_maxmin.cpp | UTF-8 | 347 | 3.296875 | 3 | [] | no_license | #include "e_maxmin.h"
int E_max(int* num, int size)
{
int max = *num;
size /= sizeof(int);
for (int i = 0; i < size; i++)
{
if (*(num + i) > max) max = *(num + i);
}
return max;
}
int E_min(int* num, int size)
{
int min = *num;
size /= sizeof(int);
for (int i = 0; i < size; i++)
{
if (num[i] < min) min = num[i];
}
return min;
} | true |
4d664520077f5c11200cc489cb3b27cb55f1da17 | C++ | SaipraveenB/super-duper-octo-lamp | /tests/test_Q_agent.cpp | UTF-8 | 3,203 | 2.59375 | 3 | [] | no_license | #include "planning/agents.h"
#include "environment/env.h"
#include <utility>
#include <vector>
class QAgentExperiment {
public:
QAgentExperiment(const std::vector<std::vector<float>> &rewards, std::pair<int, int> start_state, std::pair<int, int> end_state);
std::vector<std::pair<float, float>> RunMultipleExperiments(const int num_reps, const int max_num_iterations, const int max_num_steps);
private:
std::vector<std::pair<int, float>> RunSingleExperiment(const int max_num_iterations, const int max_num_steps, QAgent& agent, SingleMDP& env);
QAgent agent;
SingleMDP env;
};
QAgentExperiment::QAgentExperiment(const std::vector<std::vector<float>> &rewards, std::pair<int, int> start_state, std::pair<int, int> end_state) {
this->env = SingleMDP();
this->env.SetEnv(rewards, start_state, end_state);
this->agent = QAgent();
this->agent.Init(this->env);
}
std::vector<std::pair<int, float>> QAgentExperiment::RunSingleExperiment(const int max_num_iterations, const int max_num_steps, QAgent& agent, SingleMDP& env) {
std::vector<std::pair<int, float>> iter_avg_reward_training(max_num_iterations, std::make_pair(0,0.0f));
for(int i=0;i<max_num_iterations;i++) {
int num_steps = 0;
float rewards = 0.0f;
// First step
int action = agent.Step(env.GetStartState(),0.0f);
while(num_steps < max_num_steps) {
// Get new state from action.
auto new_state = env.Step(action);
// Update tracking params.
rewards += std::get<1>(new_state);
num_steps++;
// If reached completion, break.
if(std::get<2>(new_state))
break;
action = agent.Step(std::get<0>(new_state));
}
// Reset env, soft reset agent.
env.Reset();
agent.SoftReset();
// Update array.
iter_avg_reward_training[i] = make_pair(num_steps, rewards/num_steps);
}
return iter_avg_rewards;
}
std::vector<std::pair<float, float>> QAgentExperiment::RunMultipleExperiments(const int num_reps, const int max_num_iterations, const int max_num_steps) {
std::vector<std::pair<float, float>> avg_steps_rewards(max_num_iterations, std::make_pair(0.0f,0.0f));
#pragma omp parallel for
for(int i=0;i<num_reps;i++) {
QAgent inside_agent(agent);
SingleMDP inside_env(env);
const auto steps_rewards = this->RunSingleExperiment(max_num_iterations, max_num_steps, inside_agent, inside_env);
for(int j=0;j<max_num_iterations;j++)
#pragma omp critical
{
avg_steps_rewards[j].first += steps_rewards[j].first;
avg_steps_rewards[j].second += steps_rewards[j].second;
}
}
for(auto& vals : avg_steps_rewards) {
vals[i].first /= num_reps;
vals[i].second /= num_reps;
}
return avg_steps_rewards;
}
//TODO(SaiPraveenB) : Make Python call to this function
std::vector<std::pair<float,float>> GetData(const std::vector<std::vector<float>> &rewards, std::pair<int,int> start_state, std::pair<int,int> end_state, const int num_reps, const int max_num_iterations, const int max_num_steps) {
QAgentExperiment q_agent_exp(rewards, start_state, end_state);
auto stats = q_agent_exp.RunMultipleExperiments(num_reps, max_num_iterations, max_num_steps);
return stats;
}
| true |
82e80ba909a690e3a7acaa043571bf3991e8ca15 | C++ | meriadec/Nibbler | /srcs/Kasparov.cpp | UTF-8 | 1,999 | 2.671875 | 3 | [] | no_license | #include <Kasparov.hpp>
std::vector<std::vector<int> > Kasparov::getMap(void) const {
return _map;
}
void Kasparov::addPlayer (std::string name, eKeys left, eKeys right, ePos pos, eColor color) {
_players.push_back(new Hiddleston(name, left, right, pos, this, color));
}
Kasparov::~Kasparov (void) {
for (std::list<Hiddleston *>::iterator it = _players.begin(); it != _players.end(); ++it) {
delete *it;
}
}
Kasparov::Kasparov (void) {
}
std::list<Hiddleston *> Kasparov::getPlayers (void) {
return _players;
}
Kasparov::Kasparov (int w, int h, bool isPinte) : _w(w), _h(h), isPinte(isPinte) {
}
int Kasparov::getH (void) const {
return _h;
}
int Kasparov::getW (void) const {
return _w;
}
void Kasparov::gyneco (void) {
int xavier = false;
std::pair<int, int> pos;
while (!xavier) {
pos = _randomPos();
xavier = _isFree(pos);
}
_bigMac = pos;
}
bool Kasparov::_isFree (std::pair<int, int> pos) {
if (pos == _bigMac) { return false; }
for (std::list<Hiddleston *>::iterator it = _players.begin(); it != _players.end(); it++) {
std::list< std::pair<int, int> > blocks = (*it)->getBlocks();
for (std::list< std::pair<int, int> >::iterator it2 = blocks.begin(); it2 != blocks.end(); it2++) {
if (pos == (*it2)) { return false; }
}
}
return true;
}
std::pair<int, int> Kasparov::_randomPos (void) {
int maxH = this->isPinte ? this->_h - 1 : this->_h;
int maxW = this->isPinte ? this->_w - 1 : this->_w;
int x = rand() % maxW;
int y = rand() % maxH;
if (this->isPinte && x == 0) { x = 1; }
if (this->isPinte && y == 0) { y = 1; }
return std::make_pair(x, y);
}
std::pair<int, int> &Kasparov::getLunch (void) {
return this->_bigMac;
}
bool Kasparov::hasAlive (void) {
for (std::list<Hiddleston *>::iterator it = _players.begin(); it != _players.end(); it++) {
if (!(*it)->isDead) { return true; }
}
return false;
}
| true |
dad4c46892c1d79d6590fd92c170e90037bf4b45 | C++ | whutwutao/BiTree | /BiTree.h | UTF-8 | 24,635 | 3.109375 | 3 | [] | no_license | //
// BiTree.h
// 二叉树
//
// Created by WuTao on 2020/2/6.
// Copyright © 2020 WuTao. All rights reserved.
//
#ifndef BiTree_h
#define BiTree_h
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
int find(ElemType a[], ElemType x, int n)
{
for (int i = 0; i < n ; i++)
{
if (a[i] == x)
{
return i;
}
}
return -1;
}
//根据前序遍历序列和中序遍历序列构造二叉树
BiTree PreInCreateTree(ElemType Pre[], ElemType In[], int n)
{
BiTree T = (BiTNode*)malloc(sizeof(BiTNode));
T->data = Pre[0];
T->lchild = NULL;
T->rchild = NULL;
if (n > 1)
{
int index = find(In,Pre[0],n);
int lSize = index;
int rSize = n-1-lSize;
ElemType lPre[lSize],lIn[lSize];//左子树的先序、中序序列
ElemType rPre[rSize],rIn[rSize];//右子树的先序、中序序列
if (lSize > 0 && rSize > 0)//若左右子树均非空
{
int i = 0;
for (; i < lSize; i++)
{
lPre[i] = Pre[i+1];
lIn[i] = In[i];
}
T->lchild = PreInCreateTree(lPre, lIn, lSize);//构造左子树
i++;
for (int j = 0; i < n; j++,i++)
{
rPre[j] = Pre[i];
rIn[j] = In[i];
}
T->rchild = PreInCreateTree(rPre, rIn, rSize);//构造右子树
}
else if (lSize > 0)//左子树不为空,右子树为空
{
for (int i = 0; i < lSize; i++)
{
lPre[i] = Pre[i+1];
lIn[i] = In[i];
}
T->lchild = PreInCreateTree(lPre, lIn, lSize);
}
else if (rSize > 0)//左子树为空,右子树不为空
{
int i = 1,j = 0;
for (;i < n; i++,j++)
{
rPre[j] = Pre[i];
rIn[j] = In[i];
}
T->rchild = PreInCreateTree(rPre, rIn,rSize);
}
}
return T;
}
//另一种写法,代码量比较少
//s1,e1分别为先序遍历序列的起点和终点位置下标,s2,e2分别为中序遍历序列的起点和终点位置下标
BiTree PreInCreateTree(ElemType Pre[],ElemType In[],int s1,int e1,int s2,int e2)
{
BiTree T = (BiTree)malloc(sizeof(BiTNode));
T->data = Pre[s1];
int i;
for (i = s2; T->data != In[i]; i++);
int len1 = i - s2;//左子树序列长度
int len2 = e2 - i;//右子树序列长度
if (len1 > 0)
{
T->lchild = PreInCreateTree(Pre,In,s1+1,s1+len1,s2,s2+len1-1);
}
else
{
T->lchild = NULL;
}
if (len2 > 0)
{
T->rchild = PreInCreateTree(Pre,In,s1+1+len1,s1+len1+len2,s2+len1+1,s2+len1+len2);
}
else
{
T->rchild = NULL;
}
return T;
}
//释放以T为根结点的二叉树所占存储空间
void destoryBiTree(BiTree T)
{
if (T != NULL)
{
destoryBiTree(T->lchild);
destoryBiTree(T->rchild);
// printf("结点%d已释放\n",T->data);
free(T);
}
}
//访问结点
void visit(BiTNode *node)
{
if (node != NULL)
{
cout << node->data << " ";
}
}
//先序遍历
void PreOrder(BiTree T)
{
if (T != NULL)
{
visit(T);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
//先序遍历的非递归算法
void PreOrder1(BiTree T)
{
//结点栈的初始化
//结点栈用来保存遍历过程中 访问过的结点的 右孩子结点
int MaxSize = 50;
BiTNode* Stack[MaxSize];
int top = -1;
BiTNode *p = T;//p指向根结点
while (p != NULL || top != -1)//当p的指向不为空 或 栈非空时
{
if (p != NULL)
{
visit(p);//先访问根结点
if (p->rchild != NULL)
{
Stack[++top] = p->rchild;//若根结点的右孩子不为空则将其入栈
}
p = p->lchild;//p指向根结点的左孩子
}
else//p为空时
{
//p为空说明刚刚访问过的结点的左孩子为空,则从栈中将该结点的右孩子出栈进行下一次访问
p = Stack[top--];
}
}
}
//中序遍历
void InOrder(BiTree T)
{
if (T != NULL)
{
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
//中序遍历的非递归算法
void InOrder1(BiTree T)
{
if (T == NULL)
{
return;
}
//结点栈的初始化
//结点栈用来保存遍历过程中 访问过的结点的 双亲结点
int MaxSize = 50;
BiTNode* Stack[MaxSize];
int top = -1;
BiTNode *p = T;
while (p != NULL || top != -1)//当p指向结点不空 或 栈非空时
{
if (p != NULL)//p指向结点非空时
{
Stack[++top] = p;//将p入栈
p = p->lchild;//p指向其左孩子结点
}
else//p指向结点为空但栈非空时
{
p = Stack[top--];//栈顶结点出栈,p指向此结点
visit(p);//访问该结点
p = p->rchild;//p指向该结点的右孩子结点
}
}
}
//后序遍历
void PostOrder(BiTree T)
{
if (T != NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
visit(T);
}
}
//后序遍历的非递归算法
//后序遍历与其他两种遍历有所不同,后序遍历每个根结点都要入栈两次
void PostOrder1(BiTree T)
{
if (T == NULL)
{
return;
}
typedef struct
{
BiTNode *nodeptr;//结点指针
bool status; //入栈标志;表示该结点是第几次入栈,false为第1次,true为第2次
}stackElem;//栈元素类型,保存一个结点指针和这个结点的入栈标志
//结点栈的初始化
//结点栈用来保存遍历过程中 经过但未访问的 根结点
int MaxSize = 50;
stackElem Stack[MaxSize];
int top = -1;//栈顶指针
BiTNode *p = T;
stackElem temp;
while (p != NULL || top != -1)
{
if (p != NULL)//根结点非空
{
temp.nodeptr = p; //将根结点入栈
temp.status = false; //记录此结点为第一次入栈
Stack[++top] = temp;
p = p->lchild; //p指向根结点的左孩子
}
else
{
temp = Stack[top--];//栈顶结点及其入栈标志出栈
p = temp.nodeptr;
if (!temp.status)//若此结点为第1次入栈,则将此结点2次入栈,并考察它的右子树
{
temp.status = true;
Stack[++top] = temp;
p = p->rchild;
}
else//若此结点已经为第2此入栈,则直接访问该结点
{
visit(p);//访问此结点
p = NULL;
//此结点已经访问,下一个要考察的结点是栈中的结点,所以要将p设为空,下一步就强制退栈
}
}
}
}
//层次遍历
void LevelOrder(BiTree T)
{
if (T == NULL)
{
return;
}
int MaxSize = 50;//队列最大存放元素个数
BiTNode* Queue[MaxSize];//存放结点的队列
int front = 0, rear = 0;//初始化
BiTNode *p = T;
Queue[rear] = p; //根结点入队
rear = (rear + 1) % MaxSize;
while (front != rear)//当队列非空时
{
p = Queue[front];//队首元素出队
front = (front + 1) % MaxSize;
visit(p);
if (p->lchild != NULL)
{
Queue[rear] = p->lchild;
rear = (rear + 1) % MaxSize;
}
if (p->rchild != NULL)
{
Queue[rear] = p->rchild;
rear = (rear + 1) % MaxSize;
}
}
}
//以与层次遍历相反的顺序遍历二叉树
//利用栈,在进行层次遍历时,将出队元素入栈而不访问,等所有结点都入栈了再将栈中结点依次出栈访问
void reLevelOrder(BiTree T)
{
if (T != NULL)
{
int MaxSize = 50;//队列、栈的最大存放元素个数
//队列的初始化
BiTNode* Queue[MaxSize];//存放结点的队列
int front = 0, rear = 0;//初始化
//栈的初始化
BiTNode* Stack[MaxSize];
int top = -1;
BiTNode *p = T;
Queue[rear] = p;//根结点入队
rear = (rear + 1) % MaxSize;
//将所有结点按层次遍历的顺序依次入栈
while (front != rear)
{
p = Queue[front];//队首元素出队
front = (front + 1) % MaxSize;
Stack[++top] = p;//将其入栈
if (p->lchild != NULL)
{
Queue[rear] = p->lchild;
rear = (rear + 1) % MaxSize;
}
if (p->rchild != NULL)
{
Queue[rear] = p->rchild;
rear = (rear + 1) % MaxSize;
}
}
//将所有结点依次出栈访问
while (top > -1)
{
p = Stack[top--];//栈顶结点出栈
visit(p);//访问
}
}
}
//求二叉树的高度,递归算法
int getHeight(BiTree T)
{
if (T == NULL)
{
return 0;
}
else
{
BiTNode *p = T;
int lHeight = getHeight(p->lchild);
int rHeight = getHeight(p->rchild);
if (lHeight > rHeight)
{
return 1 + lHeight;
}
else
{
return 1 + rHeight;
}
}
}
//求二叉树的高度,非递归算法
int getHeight1(BiTree T)
{
if (T == NULL)
{
return 0;
}
int MaxSize = 50;
BiTNode* Queue[MaxSize];
int front = 0, rear = 0;
int last = 1;//下一层的第一个结点在队列中的下标
int level = 0;
Queue[rear++] = T;
BiTNode *p = T;
while (front != rear)
{
p = Queue[front++];
if (p->lchild)
{
Queue[rear++] = p->lchild;
}
if (p->rchild)
{
Queue[rear++] = p->rchild;
}
if (front == last)
{
level++;
last = rear;
}
}
return level;
}
//判断二叉树是否为完全二叉树
//还是利用层次遍历,在遍历过程中,将结点的左右孩子不论是否为空都入队,当出队元素为空时判断队列中此元素
//之后的结点是否都为空,若不是则不是完全二叉树
bool isComplete(BiTree T)
{
queue<BiTNode *> Queue;//结点队列
Queue.push(T);//根结点入队
BiTNode *p = T;
while (!Queue.empty())
{
p = Queue.front();
Queue.pop();
if (p)
{
Queue.push(p->lchild);
Queue.push(p->rchild);
}
else
{
while (!Queue.empty())
{
if (Queue.front() != NULL)
{
return false;
}
Queue.pop();
}
}
}
return true;
}
//求一颗二叉树的双分支结点的个数
int DoubleSonNode(BiTree T)
{
if (T == NULL)
{
return 0;
}
else if (T->lchild && T->rchild)//若根结点左右孩子均不为空
{
return DoubleSonNode(T->lchild) + DoubleSonNode(T->rchild) + 1;
//加1是加上根结点自己
}
else
{
return DoubleSonNode(T->lchild) + DoubleSonNode(T->rchild);
//此处根结点不是双分支结点,所以不加1
}
}
//将二叉树的所有结点的左右子树进行交换
void exchange(BiTree T)
{
if (T)
{
exchange(T->lchild);
exchange(T->rchild);
BiTNode *temp = T->lchild;
T->lchild = T->rchild;
T->rchild = temp;
}
}
//求二叉树先序遍历过程中第k个访问的结点的值
bool PreOrderNode(BiTree T, ElemType &value, int k)
{
if (!T)
{
return false;
}
static int i = 1;
if (i == k)
{
value = T->data;
return true;
}
else
{
i++;
if (PreOrderNode(T->lchild,value,k))
{
return true;
}
else
{
return PreOrderNode(T->rchild,value,k);
}
}
}
//求后序遍历的第k个结点值
bool PostOrderNode(BiTree T, ElemType &value, int k)
{
static int i = 1;
if (T == NULL)
{
return false;
}
typedef struct
{
BiTNode *nodeptr;
bool status;
}stackElem;
int MaxSize = 50;
stackElem stack[MaxSize];
int top = -1;
BiTNode *p = T;
stackElem temp;
while (p || top != -1)
{
if (p)
{
temp.nodeptr = p;
temp.status = false;
stack[++top] = temp;
p = p->lchild;
}
else
{
temp = stack[top--];
p = temp.nodeptr;
if (temp.status)
{
if (i == k)
{
value = p->data;
return true;
}
else
{
i++;
}
p = NULL;
}
else
{
temp.status = true;
stack[++top] = temp;
p = p->rchild;
}
}
}
return false;
}
//将二叉树中所有 根结点的值为x的子树删除
//层次遍历整棵树,当找到值为x的结点时,将其父结点的左(右)孩子指针置为空
void delXTree(BiTree T, ElemType x)
{
if (T)
{
if (T->data == x)
{
destoryBiTree(T);
return;
}
int MaxSize = 50;
BiTNode * Queue[MaxSize];
int front = 0, rear = 0;
BiTNode *p;
Queue[rear++] = T;
while (front < rear)
{
p = Queue[front++];
if (p->lchild)
{
if (p->lchild->data == x)
{
destoryBiTree(p->lchild);
p->lchild = NULL;
}
else
{
Queue[rear++] = p->lchild;
}
}
if (p->rchild)
{
if (p->rchild->data == x)
{
destoryBiTree(p->rchild);
p->rchild = NULL;
}
else
{
Queue[rear++] = p->rchild;
}
}
}
}
}
//打印值为x的结点的所有祖先结点值
//采用非递归的后序遍历,若当前结点值为x,则将栈中所有元素出栈,
//只需把后序遍历中的 visit(p) 改为输出栈中所有结点值即可
void ancestor(BiTree T, ElemType x)
{
if (T == NULL)
{
return;
}
typedef struct
{
BiTNode *nodeptr;//结点指针
bool status; //入栈标志;表示该结点是第几次入栈,false为第1次,true为第2次
}stackElem;//栈元素类型,保存一个结点指针和这个结点的入栈标志
//结点栈的初始化
//结点栈用来保存遍历过程中 经过但未访问的 根结点
int MaxSize = 50;
stackElem Stack[MaxSize];
int top = -1;//栈顶指针
BiTNode *p = T;
stackElem temp;
while (p != NULL || top != -1)
{
if (p != NULL)//根结点非空
{
temp.nodeptr = p; //将根结点入栈
temp.status = false; //记录此结点为第一次入栈
Stack[++top] = temp;
p = p->lchild; //p指向根结点的左孩子
}
else
{
temp = Stack[top--];//栈顶结点及其入栈标志出栈
p = temp.nodeptr;
if (!temp.status)//若此结点为第1次入栈,则将此结点2次入栈,并考察它的右子树
{
temp.status = true;
Stack[++top] = temp;
p = p->rchild;
}
else//若此结点已经为第2此入栈,则直接访问该结点
{
if (p->data == x)
{
while (top != -1)
{
cout << Stack[top--].nodeptr->data << " ";
}
cout << endl;
}
p = NULL;
//此结点已经访问,下一个要考察的结点是栈中的结点,所以要将p设为空,下一步就强制退栈
}
}
}
}
//找到二叉树中p、q结点最近的公共祖先结点
//利用非递归后序遍历中的栈
void commonAncestor(BiTree T, ElemType p, ElemType q)
{
if (T)
{
int MaxSize = 50;
typedef struct
{
BiTNode *ptr;
bool status;
}stackElem;
stackElem st1[MaxSize],st2[MaxSize],st3[MaxSize];//st1为工作栈,st2,st3为辅助栈
int top1 = -1, top2 = -1, top3 = -1;
BiTNode *s = T;
stackElem temp;
while (s || top1 != -1)
{
if (s)
{
temp.ptr = s;
temp.status = false;
st1[++top1] = temp;
s = s->lchild;
}
else
{
temp = st1[top1--];
s = temp.ptr;
if (!temp.status)
{
temp.status = true;
st1[++top1] = temp;
s = s->rchild;
}
else
{
//对此结点进行操作
if (temp.ptr->data == p)//若此结点为p,则将st1中结点复制到辅助栈st2中
{
for (int i = 0; i <= top1; i++)
{
st2[i] = st1[i];
}
top2 = top1;
}
if (temp.ptr->data == q)
//若此结点为q,则将当前st1中的结点复制到辅助栈st3中
{
for (int i = 0; i <= top1; i++)
{
st3[i] = st1[i];
}
top3 = top1;
}
if (top2 != -1 && top3 != -1)
//若两个辅助栈均非空,则说明p、q均已遍历到,将两个辅助栈进行匹配
//找到的第一个公共元素即为所求
{
for (int i = top3; i >= 0; i--)
{
for (int j = top2; j >=0; j--)
{
if (st3[i].ptr == st2[j].ptr)
{
visit(st1[i].ptr);
return;
}
}
}
}
s = NULL;
}
}
}
}
}
//求二叉树的宽度,即具有结点数最多的那一层的结点个数
int getWidth(BiTree T)
{
int MaxSize = 50;
BiTNode * Queue[MaxSize];
int front = 0, rear = 0;
int width = 0, count = 0;
int nextfirst = 1;//表示下一层的第一个结点在队列中的的下标
Queue[rear++] = T;
BiTNode *p;
while (front != rear)
{
p = Queue[front++];
count++;
if (p->lchild)
{
Queue[rear++] = p->lchild;
}
if (p->rchild)
{
Queue[rear++] = p->rchild;
}
//由于下一层第一个结点的位置取决于当前层结点的个数,
//所以要先把当前结点的左右孩子入队,再判断一层是否遍历完
if (front == nextfirst)
{
if (width < count)
{
width = count;
}
count = 0;
nextfirst = rear;
}
}
return width;
}
//已知一颗满二叉树的先序序列pre,求其后序序列post
void PreToPost(ElemType Pre[],int l1,int h1,ElemType Post[],int l2, int h2)
{
int half;
if (h1 >= l1)
{
Post[h2] = Pre[l1];
half = (h1 - h1) / 2;
PreToPost(Pre,l1+1,l1+half,Post,l2,l2+half-1);//转换左子树
PreToPost(Pre,l1+half+1,h1,Post,l2+half,h2-1);//转换右子树
}
}
//将二叉树的叶子结点从左至右顺序连成一个单链表,表头指针为head,用叶结点的右指针域存放链表指针
//采用中序遍历,当遍历到叶结点时将其插入到链表尾部
BiTNode * LeafLinkList(BiTree T)
{
BiTNode *head = NULL;
if (T)
{
int MaxSize = 50;
BiTNode *st[MaxSize];
int top = -1;
BiTNode *p = T;
BiTNode *pre = NULL;
while (p || top != -1)
{
if (p)
{
st[++top] = p;
p = p->lchild;
}
else
{
p = st[top--];
//对此结点进行操作
if (p->lchild == NULL && p->rchild == NULL)
{
if (pre == NULL)
{
head = p;
pre = p;
}
else
{
pre->rchild = p;
pre = p;
}
}
p = p->rchild;
}
}
}
return head;
}
//判断两棵二叉树是否相似,王道书2020版第127页第17题
bool isSimilar(BiTree T1, BiTree T2)
{
if (T1 == NULL && T2 == NULL)
{
return true;
}
if (T1 == NULL || T2 == NULL)
{
return false;
}
return isSimilar(T1->lchild,T2->lchild) && isSimilar(T1->rchild, T2->rchild);
}
//用递归算法求二叉树的带权路径长度(WPL)
//WPL:树的每个叶结点的权值与其到根结点路径长度乘积的总和
//先序递归遍历
int wpl_PreOrder(BiTree T, int deep)//deep为起始结点的深度
{
static int wpl = 0;//静态变量,累加的最终值为整棵树的WPL
if (T->lchild == NULL && T->rchild == NULL)
{
wpl += (deep - 1) * T->data;//路径长度为 深度-1
}
if (T->lchild != NULL)//将左子树的WPL累加至wpl
{
wpl_PreOrder(T->lchild, deep+1);
}
if (T->rchild != NULL)//将右子树的WPL累加至wpl
{
wpl_PreOrder(T->rchild, deep+1);
}
return wpl;
}
int wpl(BiTree root)
{
return wpl_PreOrder(root,1);//初始结点为根结点,深度为1
}
int wpl_LevelOrder(BiTree T)
{
int wpl = 0;
int level = 0, currentlast = 0, nextfirst = 1;
int MaxSize = 50;
BiTNode * Queue[MaxSize];
int front = 0, rear = 0;
Queue[rear++] = T;
BiTNode *p;
while (front != rear)
{
p = Queue[front++];
if (!p->lchild && !p->rchild)//若为叶结点3
{
wpl += level * p->data;
}
else
{
if (p->lchild)
{
Queue[rear++] = p->lchild;
}
if (p->rchild)
{
Queue[rear++] = p->rchild;
}
}
if (front == nextfirst)
{
level++;
currentlast = rear - 1;
nextfirst = rear;
}
}
return wpl;
}
void BiTreeToExp(BiTree root, int deep)
{
if (!root)
{
return;
}
else if (!root->lchild && !root->rchild)
{
printf("%c",root->data);
}
else
{
if (deep > 1)
{
printf("(");
}
BiTreeToExp(root->lchild,deep + 1);
printf("%c",root->data);
BiTreeToExp(root->rchild,deep + 1);
if (deep > 1)
{
printf(")");
}
}
}
void TreeToExpress(BiTree tree)
{
cout << "该树对应的中缀表达式为: ";
BiTreeToExp(tree, 1);
}
#endif /* BiTree_h */
| true |
6293b39b442a3bc2a16cb266eea1eaecd0e2d7c7 | C++ | null-char/dsa | /src/leetcode/L1493/Solution.cpp | UTF-8 | 1,057 | 3.53125 | 4 | [] | no_license | // Link:
// https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/
#include <bits/stdc++.h>
using namespace std;
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int res = 0;
int i = 0;
int j = 0;
int zeroes = 0;
// Maintain a sliding window with at most 1 zero in it. We move the sliding window right to the next zero if the window contains more than one zero
while (j < nums.size()) {
if (nums[j] == 0) zeroes++;
if (zeroes > 1) {
while (nums[i++] != 0);
zeroes--;
}
res = max(res, j - i);
j++;
}
return res;
}
};
TEST_CASE("Returns length of the longest subarray of 1's",
"[longestSubarray]") {
Solution s;
vector<int> nums1 = {1, 1, 0, 1};
REQUIRE(s.longestSubarray(nums1) == 3);
vector<int> nums2 = {1, 1, 1};
REQUIRE(s.longestSubarray(nums2) == 2);
vector<int> nums3 = {1, 1, 0, 0, 1, 1, 1, 0, 1};
REQUIRE(s.longestSubarray(nums3) == 4);
} | true |
117baff328ec0ecd83dca39b79be7044a099f1a4 | C++ | Gitem2001/Complex_numbers | /main.cpp | UTF-8 | 3,758 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include "rational.h"
#include "complex.h"
#include "catch_amalgamated.hpp"
#include <fstream>
TEST_CASE("Tests for complex_numbers") {
SECTION("Contructors for complex_numbers","[constuctors]"){
rational_num a(5,1);
rational_num b(6,1);
complex_num c(a,b);
complex_num d(5,1,6,1);
REQUIRE(c == d);
}
SECTION("Operators = for complex num", "[=]"){
complex_num a(10204,15,8664,2);
complex_num b = a;
REQUIRE(a==b);
complex_num c = - b;
REQUIRE(c == -(a));
}
SECTION("Operators +, += for complex num", "[+ +=]" ){
complex_num a(1403,5,1202,10);
complex_num b(5604,42,1802,25);
complex_num c = a+b;
REQUIRE(c.getreal().result == 414.029);
REQUIRE(c.getimage().result == 192.28);
c+=a; // с положительными
REQUIRE(c.getreal().result == 694.629);
REQUIRE(c.getimage().result == 312.48);
c+=-(a); // проверка на сложение с отрицательными
REQUIRE(c.getreal().result == 414.029);
REQUIRE(c.getimage().result == 192.28);
}
SECTION("Operators -, -= for complex num", "[- -=]" ){
complex_num a(2543,12,5634,78);
complex_num b(13745,34,17875,24);
complex_num c = a - b;
REQUIRE(c.getreal().result == -192.348);
REQUIRE(c.getimage().result == -672.561);
c -= (-a); // проверка на сложение с отрицательными
REQUIRE(c.getreal().result == 19.569);
REQUIRE(c.getimage().result == -600.33);
}
SECTION("Operators * / for complex_num", "[* /]" ){
complex_num a(12,2,6,1);
complex_num b(15,3,4,2);
complex_num c = a * b;
REQUIRE(c.getreal().result == 18.0);
REQUIRE(c.getimage().result == 42.0);
c = a / b;
REQUIRE(c.getreal().result == 1.448);
REQUIRE(c.getimage().result == 0.621);
}
SECTION("Operators ^ for complex_num", "[^]" ){
complex_num a(12,2,6,1);
complex_num b = a^3;
REQUIRE(b == a*a*a);
}
SECTION("Operator - for complex num", "[-]" ){
complex_num a(2543,12,5634,78);
complex_num b = -a;
REQUIRE(b.real.result == -211.917);
REQUIRE(b.imagine.result == -72.231);
complex_num c = -b;
REQUIRE(c.real.result == 211.917);
REQUIRE(c.imagine.result == 72.231);
}
SECTION("Functions get for complex_num", "[get]" ){
complex_num a(2543,12,5634,78);
REQUIRE(a.getreal().result == 211.917);
REQUIRE(a.getimage().result == 72.231);
}
SECTION("Function abs() for complex_num", "[abs]" ){
complex_num a(2543,12,5634,78);
REQUIRE(a.abs() == 223.888);
}
SECTION("Function set image, set real for complex_num", "[set]" ){
complex_num a(7645,3645,678234,23);
rational_num b (5,1);
rational_num c (10,1);
a.setreal(b);
a.setimage(c);
REQUIRE(a.real == b);
REQUIRE(a.imagine == c);
}
SECTION("Function argv for complex_num", "[argv]" ){
complex_num a(2256,24,45633,1235);
REQUIRE(a.argv() == 0.375);
}
SECTION("Operators << for complex_num", "[<<]" ){
complex_num a(12,1,17,13);
std::ofstream fout("output.txt");
fout<<a.imagine.up;
fout.close();
std::ifstream fin("output.txt");
int b= 0;
fin>>b;
fin.close();
REQUIRE( b == 17);
}
SECTION("Operators == != for complex_num", "[== !=]" ){
complex_num a(16,12,4,1);
complex_num b(12,12,4,1);
REQUIRE( a == a);
REQUIRE(a != b);
}
}
| true |
86ab106caf7b89513dd93845f65fe37bd987977b | C++ | Allen-xuhw/Socket | /EasyTcpServer/CELLTimestamp.hpp | UTF-8 | 621 | 2.9375 | 3 | [] | no_license | #ifndef _CELLTimestamp_hpp_
#define _CELLTimestamp_hpp_
#include<chrono>
using namespace std::chrono;
class CELLTimestamp
{
public:
CELLTimestamp()
{
update();
}
~CELLTimestamp()
{
}
void update()
{
_begin = high_resolution_clock::now();
}
double getElapsedSecond()
{
return getElapsedTimeInMicrosSec() * 0.000001;
}
double getElapsedTimeInMilliSec()
{
return getElapsedTimeInMicrosSec() * 0.001;
}
double getElapsedTimeInMicrosSec()
{
return duration_cast<microseconds>(high_resolution_clock::now() - _begin).count();
}
private:
time_point<high_resolution_clock> _begin;
};
#endif | true |
215d72c6b6bd3430f5ab8bc533949560122ce4ca | C++ | MrFICAX/StrukturePodataka | /Tudji labovi/LabPraktikum/Lab1LancaneListe/StruktureStackQueueDeque/StruktureStackQueueDeque/Glavni.cpp | UTF-8 | 727 | 3.0625 | 3 | [] | no_license | #include"StackJedan.h"
#include"StackAsArray.h"
#include<iostream>
#include"Queue.h"
using namespace std;
void main() {
try {
cout << "<<<<<< STACK >>>>>>>"<<endl;
StackAsArray PrviStek(5);
PrviStek.push(10);
PrviStek.push(6);
PrviStek.push(9);
PrviStek.push(20);
PrviStek.push(67);
cout << "Popovan: "<< PrviStek.pop()<<endl;
cout <<"Broj elemenata: " <<PrviStek.numberOfElements() << endl;
cout << "<<<<<< RED >>>>>>>"<<endl;
Queue Nizic(5);
cout << Nizic.getHead();
Nizic.enqueue(1);
Nizic.enqueue(2);
Nizic.enqueue(4);
Nizic.enqueue(8);
cout <<"Izbrisan: " <<Nizic.dequeue() << endl;
cout <<"Glava: " <<Nizic.getHead() << endl;
}
catch (char* izuzetak)
{
cout << izuzetak;
}
} | true |
73dbc058f7ec112602d90a3caa6f32b9168d17ac | C++ | sweethoneybee/AlgorithmStudy | /AlgorithmStudy/개인/월간코드챌린지시즌3_1.cpp | UTF-8 | 507 | 2.765625 | 3 | [] | no_license | //
// 월간코드챌린지시즌3_1.cpp
// AlgorithmStudy
//
// Created by 정성훈 on 2021/09/09.
//
#include <string>
#include <vector>
#include <set>
using namespace std;
int solution(vector<int> numbers) {
set<int> s;
for (int i = 0; i < 10; i++) {
s.insert(i);
}
for (const auto n: numbers) {
s.erase(n);
}
int answer = 0;
for (const auto num: s) {
answer += num;
}
return answer;
}
| true |
c8f944379cb0f52080303b2411cc604c921e3ee6 | C++ | jj97181818/zj | /b965.cpp | BIG5 | 1,484 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int rotation (int matrix[][100], int &r, int &c) { //
int a[100][100] = {0};
int temp = 0;
for (int i = 1;i < r + 1;i++) {
for (int j = 1; j < c + 1;j++) {
a[i][j] = matrix[(c - j) + 1][i];
}
}
for (int i = 1;i < r + 1;i++) {
for (int j = 1; j < c + 1;j++) {
matrix[i][j] = a[i][j];
}
}
temp = r;
r = c;
c = temp;
}
int overturn (int matrix[][100], int &r, int &c) { //½
int b[100][100] = {0};
for (int i = 1;i < r + 1;i++) {
for (int j = 1; j < c + 1;j++) {
b[i][j] = matrix[r - i + 1][j];
}
}
for (int i = 1;i < r + 1;i++) {
for (int j = 1; j < c + 1;j++) {
matrix[i][j] = b[i][j];
}
}
}
int main () {
int r = 0, c = 0, m = 0;
int matrix[100][100] = {0};
int action[100] = {0};
while (cin >> r >> c >> m) { //J
for (int i = 1;i < r + 1;i++) {
for (int j = 1; j < c + 1;j++) {
cin >> matrix[i][j];
}
}
for (int i = 1;i < m + 1;i++) {
cin >> action[i];
}
for (int i = m;i > 0;i--) { //Pw½
if (action[i] == 0) {
rotation(matrix,r ,c);
}
else {
overturn(matrix, r, c);
}
}
cout << r << " " << c <<endl; //X
for (int i = 1;i < r + 1;i++) {
for (int j = 1; j < c;j++) {
cout << matrix[i][j] << " ";
}
cout << matrix[i][c] << endl;
}
}
}
/*
r*c
12 22 32 11 12 13
11 21 31 21 22 23
11 12
21 22
31 32
11 12
21 22
31 32
41 42
41 42
31
*/
| true |
2686e32c4f7610a474574e5134ee2315fee0b05c | C++ | YALAMA/4nationwar | /_ref/engine/game.cpp | UTF-8 | 5,428 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include "player.h"
#include "piece.h"
#include "boardcontext.h"
#include "firetable.h"
#include "game.h"
Game::Game() {
for ( int i = 0; i < 4; i++) {
players[i] = NULL;
}
initFireTable();
}
Game::~Game() {
}
void Game::setPlayer( Player *player ) {
players[player->color] = player;
}
void Game::setupPieces( Piece* pieces[]) {
for(int i = 0; i < 4; i++) {
players[i]->setupPieces(pieces[i]);
}
}
AI4::ACTION_RESULT Game::doAction(AI4::PIECE_COLOR color, Move move) {
if ( players[color]->board_->checkMove(color, move) == false) {
std::cout << "Error this is illegal move " << std::endl;
return AI4::AR_ILLEGAL;
}
AI4::ACTION_RESULT ar;
Piece *a = players[color]->board_->getPiece(move.fromY, move.fromX);
Piece *b = players[color]->board_->getPiece(move.toY, move.toX);
if ( b == NULL) {
ar = AI4::AR_MOVED;
} else {
AI4::PIECE_COLOR fireColor = b->color;
b = players[fireColor]->board_->getPiece(move.toY, move.toX);
ar = fireTable[a->role][b->role];
if ( ar == AI4::AR_FIRE) {
if ( a->role == AI4::PR_LING && b->role == AI4::PR_LING) {
ar = AI4::AR_LING_LING;
} else if ( a->role == AI4::PR_LING && b->role == AI4::PR_BOMB) {
ar = AI4::AR_LING_BOMP;
} else if ( b->role == AI4::PR_LING && a->role == AI4::PR_BOMB) {
ar = AI4::AR_BOMP_LING;
}
} else if ( ar == AI4::AR_LOST) {
if ( a->role == AI4::PR_LING ) {
ar = AI4::AR_LING_MINE;
}
} else if ( ar == AI4::AR_CAPTURE) {
if ( b->role == AI4::PR_FLAG) {
ar = AI4::AR_FLAG;
}
}
}
return ar;
}
void Game::doUpdate(AI4::PIECE_COLOR color, AI4::PLAYER_ACTION ac) {
for (int i = 0; i < 4; i++) {
players[i]->doUpdate(color, ac);
}
}
void Game::doUpdate(AI4::ACTION_RESULT ar, Move move) {
Piece *a = players[0]->board_->getPiece(move.fromY, move.fromX);
Piece *b = players[0]->board_->getPiece(move.toY, move.toX);
for(int i = 0; i < 4; i++) {
players[i]->doUpdate(ar, move);
}
bool openAflag = false;
bool openBflag = false;
if ( ar == AI4::AR_LING_LING) {
openAflag = true;
openBflag = true;
} else if ( ar == AI4::AR_LING_BOMP || ar == AI4::AR_LING_MINE) {
openAflag = true;
} else if ( ar == AI4::AR_BOMP_LING) {
openBflag = true;
}
if ( a != NULL && openAflag ) {
AI4::PIECE_COLOR color = a->color;
int flagX = -1;
for(int i = 0; i < 25; i++) {
if ( players[color]->board_->getPiece(color*25+i)->role == AI4::PR_FLAG) {
flagX = players[color]->board_->getPiece(color*25+i)->x;
break;
}
}
if (flagX != -1) {
for(int i = 0; i < 4; i++) {
players[i]->openFlag(flagX);
}
}
}
if ( b != NULL && openBflag ) {
AI4::PIECE_COLOR color = b->color;
int flagX = -1;
for(int i = 0; i < 25; i++) {
if ( players[color]->board_->getPiece(color*25+i)->role == AI4::PR_FLAG) {
flagX = players[color]->board_->getPiece(color*25+i)->x;
break;
}
}
if (flagX != -1) {
for(int i = 0; i < 4; i++) {
players[i]->openFlag(flagX);
}
}
}
}
AI4::PLAYER_ACTION Game::doAI(AI4::PIECE_COLOR color, Move &newMove) {
return players[color]->doAI(newMove);
}
int Game::checkBoard() {
for (int y = 0; y <= 7; y++) {
for (int x = 0; x < 20; x++) {
if ( players[0]->board_->getPiece(y, x) == NULL) {
if ( players[1]->status == AI4::PS_ONLINE && players[1]->board_->getPiece(y, x) != NULL) {
return -1;
}
if ( players[2]->status == AI4::PS_ONLINE && players[2]->board_->getPiece(y, x) != NULL) {
return -1;
}
if ( players[3]->status == AI4::PS_ONLINE && players[3]->board_->getPiece(y, x) != NULL) {
return -1;
}
} else {
if ( players[1]->status == AI4::PS_ONLINE && players[1]->board_->getPiece(y, x)->color != players[0]->board_->getPiece(y, x)->color) {
return -2;
}
if ( players[2]->status == AI4::PS_ONLINE && players[2]->board_->getPiece(y, x)->color != players[0]->board_->getPiece(y, x)->color) {
return -2;
}
if ( players[3]->status == AI4::PS_ONLINE && players[3]->board_->getPiece(y, x)->color != players[0]->board_->getPiece(y, x)->color) {
return -2;
}
}
for(int n = 0; n < 4; n++) {
if (players[n]->status != AI4::PS_ONLINE )
continue;
Piece *test = players[n]->board_->getPiece(y, x);
if ( test != NULL) {
if ( (int)test->y != y || (int)test->x != x) {
return -3;
}
}
}
}
}
return 0;
}
| true |
fb2fab5bdc68f5385e55cd29db845a4f164dddfe | C++ | DaDaMrX/ACM | /Templates/Dijkstra.cpp | UTF-8 | 3,238 | 3.46875 | 3 | [] | no_license | /*
1.堆优化的Dijkstra O(nlogn)
1.用邻接表adj[]存储图
2.存储结构中不需要节点数n和边数m变量,在main函数中临时定义即可
3.调用时只需给出起点start,因为采用邻接表,编号从1到n或者从0到n-1均可
4.输出start到每个点的最短距离,放在dis[]数组中
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int INF = 0x7f7f7f7f;
const int N = 1e3 + 10;
const int M = 1e3 + 10;
//********************Copy Begin********************
struct Edge
{
int to, w, next;
Edge() {}
Edge(int to, int w, int next): to(to), w(w), next(next) {}
} edge[M];
int adj[N], no;
void init()
{
memset(adj, -1, sizeof(adj));
no = 0;
}
void add(int u, int v, int w)
{
edge[no] = Edge(v, w, adj[u]);
adj[u] = no++;
}
int dis[N];
typedef pair<int, int> pii;
priority_queue<pii, vector<pii>, greater<pii> > pq;
void dijkstra(int start)
{
memset(dis, 0x7f, sizeof(dis));
dis[start] = 0;
while (!pq.empty()) pq.pop();
pq.push(pii(0, start));
while (!pq.empty())
{
pii p = pq.top(); pq.pop();
int u = p.second;
if (dis[u] < p.first) continue;
for (int i = adj[u]; i != -1; i = edge[i].next)
{
Edge &e = edge[i];
int sum = dis[u] + e.w;
if (sum < dis[e.to])
{
dis[e.to] = sum;
pq.push(pii(dis[e.to], e.to));
}
}
}
}
//********************Copy End********************
int main()
{
//1.建图:输入节点数n,边数m
int n, m;
scanf("%d%d", &n, &m);
init(); //初始化图
while (m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
//2.调用
dijkstra(1);
//3.输出dis[]
for (int i = 1; i <= n; i++) printf("%d ", dis[i]);
return 0;
}
/*
Sample Input
5 10
1 2 10
1 4 5
2 3 1
2 4 2
3 5 4
4 2 3
4 3 9
4 5 2
5 1 7
5 3 6
Sample Output
0 8 9 5 7
*/
/*****************************************************************/
/*
2.输出路径
多加一个pre[]数组
多加一个path()函数
*/
int dis[N], pre[N];
typedef pair<int, int> pii;
priority_queue<pii, vector<pii>, greater<pii> > pq;
void dijkstra(int start)
{
memset(dis, 0x7f, sizeof(dis));
memset(pre, -1, sizeof(pre));
dis[start] = 0;
while (!pq.empty()) pq.pop();
pq.push(pii(0, start));
while (!pq.empty())
{
pii p = pq.top(); pq.pop();
int u = p.second;
if (dis[u] < p.first) continue;
for (int i = adj[u]; i != -1; i = edge[i].next)
{
Edge &e = edge[i];
int sum = dis[u] + e.w;
if (sum < dis[e.to])
{
dis[e.to] = sum;
pre[e.to] = u;
pq.push(pii(dis[e.to], e.to));
}
}
}
}
void path(int u, int v)
{
if (u == v)
{
printf("%d", u);
return;
}
path(u, pre[v]);
printf(" %d", v);
}
int main()
{
//1.建图:输入节点数n,边数m
int n, m;
scanf("%d%d", &n, &m);
init(); //初始化图
while (m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
//2.调用
dijkstra(1);
//3.查询路径
int q;
scanf("%d", &q);
while (q--)
{
int v;
scanf("%d", &v);
path(1, v);
printf("\n");
}
return 0;
}
/*
Sample Input
5 10
1 2 10
1 4 5
2 3 1
2 4 2
3 5 4
4 2 3
4 3 9
4 5 2
5 1 7
5 3 6
5
1 2 3 4 5
Sample Output
0 8 9 5 7
-1 4 2 1 4
1
1 4 2
1 4 2 3
1 4
1 4 5
*/ | true |
932b5213b68bae1c81737d1cbcc5e46f8cc7b4c7 | C++ | IHR57/Competitive-Programming | /UVA/315 (Network).cpp | UTF-8 | 2,261 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <string.h>
#include <algorithm>
#include <sstream>
#define MAX 105
using namespace std;
typedef vector<int> vi;
vi adjList[MAX], dfs_num, dfs_low, articulation_vertex, dfs_parent;
int visited[MAX], dfsRoot, rootChildren, dfsNumberCounter;
void ArticulationPoint(int u)
{
dfs_num[u] = dfs_low[u] = dfsNumberCounter++;
visited[u] = 1;
for(int j = 0; j < adjList[u].size(); j++){
int v = adjList[u][j];
if(!visited[v]){
dfs_parent[v] = u;
if(u == dfsRoot) rootChildren++;
ArticulationPoint(v); //recursive call
if(dfs_low[v] >= dfs_num[u])
articulation_vertex[u] = 1;
dfs_low[u] = min(dfs_low[u], dfs_low[v]);
}
else if(v != dfs_parent[u]){ //if back edge and not direct cycle
dfs_low[u] = min(dfs_low[u], dfs_num[v]);
}
}
}
int main()
{
int node, edgeNo, v;
string str;
while(1){
scanf("%d\n", &node);
if(node == 0) break;
dfs_num.assign(node, 0); dfs_low.assign(node, 0); articulation_vertex.assign(node, 0); dfs_parent.assign(node, 0);
while(1){
getline(cin, str);
istringstream is(str);
is>>edgeNo;
if(edgeNo == 0)
break;
edgeNo--;
while(is>>v){
v--;
adjList[edgeNo].push_back(v);
adjList[v].push_back(edgeNo);
}
}
memset(visited, 0, sizeof(visited)); //initialize all node are unvisited
dfsNumberCounter = 0;
for(int i = 0; i < node; i++){
if(!visited[i]){
dfsRoot = i;
rootChildren = 0;
ArticulationPoint(i);
articulation_vertex[dfsRoot] = (rootChildren > 1); //if root has more than one children
}
}
int count = 0;
for(int i = 0; i < node; i++){
if(articulation_vertex[i])
count++;
}
printf("%d\n", count);
for(int i = 0; i <= node; i++){
adjList[i].clear();
}
}
return 0;
}
| true |
ad8753448cfb7b2f1a3f81f2984f2f3478784435 | C++ | slab14/IoT_Sec_Gateway | /SEI/alt2temp.cpp | UTF-8 | 509 | 2.921875 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
/*
* From P&FQ Toolbox
* Calculate temperature in R
* (accurate up to 60,000 feet)
* Input:
* h : Pressure alt (ft)
* Output:
* T : Temp (R)
*/
float alt2temp(float h){
float T;
float To = 518.69;
if (h > 36089) {
T = 389.99;
}
else {
T = To * (1 - 6.87559e-6 * h);
}
return T;
}
| true |
47a134ad8ec84b422a398d2a78dbfadf3ea79dc0 | C++ | jonaseck2/node-gpio | /src/GPIO.cpp | UTF-8 | 8,889 | 3.09375 | 3 | [] | no_license | #include <node.h>
#include "GPIO.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
v8::Persistent<v8::FunctionTemplate> GPIO::constructor;
std::string GPIO::IN = "in";
std::string GPIO::OUT = "out";
int GPIO::HIGH = 1;
int GPIO::LOW = 0;
bool GPIO::debug = false;
GPIO::GPIO(std::string num) : pin_num(num), opened(false)
{
}
GPIO::~GPIO()
{
}
void GPIO::Init(v8::Handle<v8::Object> exports)
{
v8::HandleScope scope;
// Constructor
v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New(New); //Binds the new
tpl->InstanceTemplate()->SetInternalFieldCount(1); //The constructor add only one instance
tpl->SetClassName(v8::String::NewSymbol("GPIO"));
//Accessors
tpl->InstanceTemplate()->SetAccessor(v8::String::New("num"), GetNum);
//Methods
tpl->PrototypeTemplate()->Set(v8::String::NewSymbol("open"), v8::FunctionTemplate::New(Open)->GetFunction());
tpl->PrototypeTemplate()->Set(v8::String::NewSymbol("close"), v8::FunctionTemplate::New(Close)->GetFunction());
tpl->PrototypeTemplate()->Set(v8::String::NewSymbol("setMode"), v8::FunctionTemplate::New(SetMode)->GetFunction());
tpl->PrototypeTemplate()->Set(v8::String::NewSymbol("write"), v8::FunctionTemplate::New(Write)->GetFunction());
tpl->PrototypeTemplate()->Set(v8::String::NewSymbol("read"), v8::FunctionTemplate::New(Read)->GetFunction());
tpl->PrototypeTemplate()->Set(v8::String::NewSymbol("toggle"), v8::FunctionTemplate::New(Toggle)->GetFunction());
//Persist constructor
GPIO::constructor = v8::Persistent<v8::FunctionTemplate>::New(tpl);
//Register GPIO on the exports
exports->Set(v8::String::NewSymbol("GPIO"), GPIO::constructor->GetFunction());
exports->Set(v8::String::NewSymbol("IN"), v8::String::New(GPIO::IN.c_str()));
exports->Set(v8::String::NewSymbol("OUT"), v8::String::New(GPIO::OUT.c_str()));
exports->Set(v8::String::NewSymbol("HIGH"), v8::Integer::New(GPIO::HIGH));
exports->Set(v8::String::NewSymbol("LOW"), v8::Integer::New(GPIO::LOW));
}
v8::Handle<v8::Value> GPIO::New(const v8::Arguments& args)
{
v8::HandleScope scope;
if (args.Length() > 0 && !args[0]->IsString()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong arguments")));
return scope.Close(v8::Undefined());
}
GPIO* gpio_instance = args.Length() < 1 ? new GPIO() : new GPIO(std::string(*v8::String::Utf8Value(args[0])));
gpio_instance->Wrap(args.This());
return args.This();
}
v8::Handle<v8::Value> GPIO::GetNum(v8::Local<v8::String> property, const v8::AccessorInfo& info)
{
GPIO* obj = node::ObjectWrap::Unwrap<GPIO>(info.Holder());
return v8::String::New(obj->pin_num.c_str());
}
void GPIO::log(std::string msg)
{
if (GPIO::debug) {
std::cout << msg << std::endl;
}
}
int GPIO::WriteValue(std::string path, std::string val)
{
std::ofstream file(path.c_str());
if (!file) {
return -1;
}
file << val;
file.close();
return 0;
}
int GPIO::open()
{
this->opened = true;
return this->WriteValue("/sys/class/gpio/export", this->pin_num);
}
int GPIO::close()
{
this->opened = false;
return this->WriteValue("/sys/class/gpio/unexport", this->pin_num);
}
int GPIO::write(int value) {
if (!this->opened) {
return -1;
}
std::string path = "/sys/class/gpio/gpio" + this->pin_num + "/value";
std::ostringstream ss;
ss << value;
return this->WriteValue(path, ss.str());
}
int GPIO::read()
{
if (!this->opened) {
return -1;
}
std::string path = "/sys/class/gpio/gpio" + this->pin_num + "/value";
return this->ReadValue(path);
}
int GPIO::setMode(std::string mode) {
std::string path = "/sys/class/gpio/gpio" + this->pin_num + "/direction";
this->mode = mode;
return this->WriteValue(path, mode);
}
int GPIO::ReadValue(std::string path)
{
std::ifstream file(path.c_str());
std::string line;
if (!file) {
return -1;
}
getline(file, line);
file.close();
return atoi(line.c_str());
}
v8::Handle<v8::Value> GPIO::Open(const v8::Arguments& args)
{
v8::HandleScope scope;
GPIO* obj = ObjectWrap::Unwrap<GPIO>(args.This());
int res = obj->open();
if (res < 0) {
std::string err_msg = "OPERATION FAILED: Unable to open GPIO " + obj->pin_num + ".";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
obj->log("GPIO " + obj->pin_num + " opened.");
return scope.Close(v8::Integer::New(res));
}
v8::Handle<v8::Value> GPIO::Close(const v8::Arguments& args)
{
v8::HandleScope scope;
GPIO* obj = ObjectWrap::Unwrap<GPIO>(args.This());
int res = obj->close();
if (res < 0) {
std::string err_msg = "OPERATION FAILED: Unable to close GPIO " + obj->pin_num + ".";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
obj->log("GPIO " + obj->pin_num + " closed.");
return scope.Close(v8::Integer::New(res));
}
v8::Handle<v8::Value> GPIO::SetMode(const v8::Arguments& args) {
v8::HandleScope scope;
GPIO* obj = ObjectWrap::Unwrap<GPIO>(args.This());
if (!obj->opened) {
std::string err_msg = "GPIO " + obj->pin_num + " is not opened.";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
if (args.Length() < 1) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong number of arguments")));
return scope.Close(v8::Undefined());
}
if (!args[0]->IsString()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong arguments")));
return scope.Close(v8::Undefined());
}
std::string mode(*v8::String::Utf8Value(args[0]));
int res = obj->setMode(mode);
if (res < 0) {
std::string err_msg = "OPERATION FAILED: Unable to change GPIO " + obj->pin_num + " mode.";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
obj->log("GPIO " + obj->pin_num + " mode changed to " + mode + ".");
return scope.Close(v8::Integer::New(res));
}
v8::Handle<v8::Value> GPIO::Write(const v8::Arguments& args) {
v8::HandleScope scope;
GPIO* obj = ObjectWrap::Unwrap<GPIO>(args.This());
if (args.Length() < 1) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong number of arguments")));
return scope.Close(v8::Undefined());
}
if (!args[0]->IsNumber()) {
v8::ThrowException(v8::Exception::TypeError(v8::String::New("Wrong arguments")));
return scope.Close(v8::Undefined());
}
v8::Local<v8::Integer> param1 = args[0]->ToInteger();
int value = param1->IntegerValue();
int res = obj->write(value);
if (res < 0) {
std::string err_msg = "OPERATION FAILED: Unable to change GPIO " + obj->pin_num + " value.";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
std::ostringstream ss;
ss << value;
obj->log("GPIO " + obj->pin_num + " value changed to " + ss.str() + ".");
return scope.Close(v8::Integer::New(res));
}
v8::Handle<v8::Value> GPIO::Read(const v8::Arguments& args) {
v8::HandleScope scope;
GPIO* obj = ObjectWrap::Unwrap<GPIO>(args.This());
if (!obj->opened) {
std::string err_msg = "GPIO " + obj->pin_num + " is not opened.";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
if (obj->mode == GPIO::OUT) {
std::string err_msg = "GPIO " + obj->pin_num + " is not in the right mode";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
int res = obj->read();
std::ostringstream ss;
ss << res;
if (res < 0) {
std::string err_msg = "OPERATION FAILED: Unable to change GPIO " + obj->pin_num + " value.";
v8::ThrowException(v8::Exception::Error(v8::String::New(err_msg.c_str())));
return scope.Close(v8::Undefined());
}
obj->log("GPIO " + obj->pin_num + " value changed to " + ss.str() + ".");
return scope.Close(v8::Integer::New(res));
}
v8::Handle<v8::Value> GPIO::Toggle(const v8::Arguments& args)
{
v8::HandleScope scope;
GPIO* obj = ObjectWrap::Unwrap<GPIO>(args.This());
std::string path = "/sys/class/gpio/gpio" + obj->pin_num + "/value";
int value = obj->ReadValue(path);
std::ostringstream ss;
ss << !value;
obj->WriteValue(path, ss.str());
return scope.Close(v8::Integer::New(0));
}
| true |
9e4d165820e43517dcb3468d4c506e620f6bb8f5 | C++ | TimBunk/tb2d | /tb2d/simplerenderer.cpp | UTF-8 | 5,659 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "simplerenderer.h"
#include "sprite.h"
SimpleRenderer::SimpleRenderer(Shader* shader, bool hud) : Renderer::Renderer(shader)
{
// Initialize variables
this->hud = hud;
drawCount = 0;
// Generate and bind the VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Generate and bind the positions
glGenBuffers(1, &VBO_position);
glBindBuffer(GL_ARRAY_BUFFER, VBO_position);
// Set attribute pointer for the position
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (GLvoid*)0);
// Generate and bind the positions
glGenBuffers(1, &VBO_texture);
glBindBuffer(GL_ARRAY_BUFFER, VBO_texture);
// Set attribute pointer for the position
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, sizeof(GLfloat), (GLvoid*)0);
// Generate and bind the color
glGenBuffers(1, &VBO_color);
glBindBuffer(GL_ARRAY_BUFFER, VBO_color);
// Set attribute pointer for the color
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (GLvoid*)0);
// Gererate the model buffer
glGenBuffers(1, &VBO_model);
glBindBuffer(GL_ARRAY_BUFFER, VBO_model);
// set attribute pointers for matrix (4 times vec4)
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)0);
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(sizeof(glm::vec4)));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(2 * sizeof(glm::vec4)));
glEnableVertexAttribArray(6);
glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(3 * sizeof(glm::vec4)));
// Unbind the VAO and VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Fill the activeTextureArray
for (int i = 0; i < 32; i++) {
activeTextureArray[i] = i;
}
}
SimpleRenderer::~SimpleRenderer()
{
// Delete all allocated memory
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO_position);
glDeleteBuffers(1, &VBO_texture);
glDeleteBuffers(1, &VBO_color);
glDeleteBuffers(1, &VBO_model);
}
void SimpleRenderer::Submit(Sprite* sprite)
{
// Set the sprite vertices
positions.push_back(glm::vec4(-0.5f + sprite->GetPivot().x, -0.5f + sprite->GetPivot().y, sprite->GetUV().x, sprite->GetUV().w));// lower left
positions.push_back(glm::vec4(0.5f + sprite->GetPivot().x, -0.5f + sprite->GetPivot().y, sprite->GetUV().z, sprite->GetUV().w));// lower right
positions.push_back(glm::vec4(-0.5f + sprite->GetPivot().x, 0.5f + sprite->GetPivot().y, sprite->GetUV().x, sprite->GetUV().y)); // upper left
positions.push_back(glm::vec4(0.5f + sprite->GetPivot().x, -0.5f + sprite->GetPivot().y, sprite->GetUV().z, sprite->GetUV().w));// lower right
positions.push_back(glm::vec4(0.5f + sprite->GetPivot().x, 0.5f + sprite->GetPivot().y, sprite->GetUV().z, sprite->GetUV().y));// upper right
positions.push_back(glm::vec4(-0.5f + sprite->GetPivot().x, 0.5f + sprite->GetPivot().y, sprite->GetUV().x, sprite->GetUV().y)); // upper left
// Set the textureID
int id = 0;
if (sprite->GetTextureID() > 0) {
bool found = false;
for (; id < textureSlots.size(); id++) {
if (sprite->GetTextureID() == textureSlots[id]) {
found = true;
break;
}
}
if (found == false) {
if (textureSlots.size() == 32) {
// TODO: Make a fix so that there can be more than 32 textures
std::cout << "above 32 textures! " << std::endl;
}
textureSlots.push_back(sprite->GetTextureID());
}
}
else {
id = -1;
}
// Get the model matrix from the sprite
glm::mat4 model = sprite->GetModelMatrix();
model = glm::scale(model, glm::vec3(sprite->GetWidth() * sprite->GetGlobalScale().x, sprite->GetHeight() * sprite->GetGlobalScale().y, 0.0f));
// Push back 6 times because we have 6 vertices
for (int i = 0; i < 6; i++) {
textures.push_back((GLfloat(id) + 1.0f));
colors.push_back(sprite->GetColor());
matrices.push_back(model);
}
// Increate the counter
drawCount++;
}
void SimpleRenderer::Render(Camera* camera)
{
// If there is nothing to draw return
if (drawCount == 0) { return; };
// Set the uniforms of the shader
shader->Use();
shader->SetMatrix4("projection", camera->GetProjectionMatrix());
if (!hud) {
shader->SetMatrix4("view", camera->GetViewMatrix());
}
else {
shader->SetMatrix4("view", glm::mat4());
}
shader->SetIntArray("textures", activeTextureArray, 32);
// Bind the VAO
glBindVertexArray(VAO);
for (int i = 0; i < textureSlots.size(); i++) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, textureSlots[i]);
}
// Fill all of the buffers with their data
glBindBuffer(GL_ARRAY_BUFFER, VBO_position);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec4), &positions[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, VBO_texture);
glBufferData(GL_ARRAY_BUFFER, textures.size() * sizeof(GLfloat), &textures[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, VBO_color);
glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(glm::vec4), &colors[0], GL_STREAM_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, VBO_model);
glBufferData(GL_ARRAY_BUFFER, matrices.size() * sizeof(glm::mat4), &matrices[0], GL_STREAM_DRAW);
// Unbind the buffer
glBindBuffer(GL_ARRAY_BUFFER, 0);
// bind texture and draw elements
glDrawArrays(GL_TRIANGLES, 0, drawCount * 6);
// Unbind the VAO and texture
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
// Clear all of the data
positions.clear();
textures.clear();
colors.clear();
matrices.clear();
textureSlots.clear();
drawCount = 0;
} | true |
85d57269410f27a9bd6d0d14b587da311be437bd | C++ | ydk1104/PS | /boj/2000~2999/2618.cpp | UHC | 1,612 | 2.78125 | 3 | [] | no_license | #include<stdio.h>
#define abs(x) (((x)>0) ? (x) : -(x))
#define min(a,b) (((a)<(b) && (a)!=0) ? (a) : (b))
typedef struct xy{
int x;
int y;
int sum;
int d;
}xy;
int distance(xy a, xy b){
int d = abs(a.x-b.x) + abs(a.y-b.y);
return d;
}
xy work[1003];
xy dp[2][1003][1003];
int main(void){
int N, W;
int d0, d1;
scanf("%d\n%d", &N, &W);
work[0].x = 1;
work[0].y = 1;
work[1].x = N;
work[1].y = N;
for(int i=2; i<=W+1; i++){
int a, b;
scanf("%d %d", &a, &b);
work[i].x = a;
work[i].y = b;
work[i].d = distance(work[i-1], work[i]); // Ÿ
work[i].sum = work[i-1].sum + work[i].d;
if(i==2){
work[i].sum = 0;
d0 = distance(work[0], work[i]);
d1 = distance(work[1], work[i]);
dp[0][0][i].sum = d0;
dp[1][0][i].sum = d1;
for(int j=0; j<=1; j++){
dp[j][1][i].sum = dp[j][0][i].sum;
}
}
else{
for(int j=0; j<=1; j++){
dp[j][0][i].sum = dp[j][0][i-1].sum + work[i].d;
dp[j][1][i].sum = dp[j][0][i].sum;
for(int k=2; k<i-1; k++){
dp[j][k][i].sum = dp[j][k][i-1].sum + work[i].d;
dp[j][1][i].sum = min(dp[j][1][i].sum, dp[j][k][i].sum);
}
dp[j][i-1][i].sum = dp[1-j][0][i-1].sum + distance(work[1-j], work[i]);
for(int k=2; k<i-2; k++){
dp[j][i-1][i].sum = min(dp[j][i-1][i].sum,
dp[1-j][k][i-1].sum+distance(work[k], work[i]));
}
dp[j][1][i].sum = min(dp[j][1][i].sum, dp[j][i-1][i].sum);
}
}
}
int ans;
printf("%d\n", ans = min(dp[0][1][W].sum, dp[1][1][W].sum));
for(int i=W+1; i>=2; i--){
for(int j=0; j<=1; j++){
if(ans == work[i].d + )
}
}
}
| true |
19d991663a5269d3b76c3cd60620eec58e276af3 | C++ | gpichot/cpp-formula-printer | /tests/beside.cpp | UTF-8 | 1,691 | 2.875 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <blk.hpp>
#include "utils.hpp"
TEST(Beside, PaddingOnDiagNE_SW) {
std::ostringstream output;
blk::Expr e1 = blk::debug('a', 1, 2, 0, 1);
blk::Expr e2 = blk::debug('b', 1, 2, 0, 0);
blk::Expr o = blk::beside(e1, e2);
ASSERT_EQ(3, o->height());
{
SCOPED_TRACE("Beside.PaddingOnDiagNE_SW");
ASSERT_OUTPUT("a.", output, o, 0);
ASSERT_OUTPUT("++", output, o, 1);
ASSERT_OUTPUT(".b", output, o, 2);
}
}
TEST(Beside, PaddingOnDiagNW_SE) {
std::ostringstream output;
blk::Expr e1 = blk::debug('a', 1, 2, 0, 1);
blk::Expr e2 = blk::debug('b', 1, 2, 0, 0);
blk::Expr o = blk::beside(e2, e1);
{
SCOPED_TRACE("Beside.PaddingOnDiagNW_SE");
ASSERT_OUTPUT(".a", output, o, 0);
ASSERT_OUTPUT("++", output, o, 1);
ASSERT_OUTPUT("b.", output, o, 2);
}
}
TEST(Beside, PaddingLeftBoth) {
std::ostringstream output;
blk::Expr e1 = blk::debug('a', 1, 3, 0, 1);
blk::Expr e2 = blk::debug('b', 1, 1, 0, 0);
blk::Expr o = blk::beside(e1, e2);
{
SCOPED_TRACE("Beside.PaddingLeftBoth");
ASSERT_OUTPUT("a.", output, o, 0);
ASSERT_OUTPUT("++", output, o, 1);
ASSERT_OUTPUT("a.", output, o, 2);
}
}
TEST(Beside, PaddingRightBoth) {
std::ostringstream output;
blk::Expr e1 = blk::debug('a', 1, 3, 0, 1);
blk::Expr e2 = blk::debug('b', 1, 1, 0, 0);
blk::Expr o = blk::beside(e2, e1);
{
SCOPED_TRACE("Beside.PaddingRightBoth");
ASSERT_OUTPUT(".a", output, o, 0);
ASSERT_OUTPUT("++", output, o, 1);
ASSERT_OUTPUT(".a", output, o, 2);
}
}
| true |
6963b9b2f48f1f572ab7f2a12e9bd412b167a119 | C++ | DarcySail/Leetcode_Solution | /567.cpp | UTF-8 | 1,214 | 2.921875 | 3 | [] | no_license | #include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution
{
public:
bool checkInclusion(string s1, string s2)
{
vector<int> dict(256, 0);
int win_size = s1.size();
for (auto i : s1) {
++dict[i];
}
vector<int> tmp_win(dict);
for (size_t left = 0, right = 0;
left < s2.length() && right < s2.length(); ++right) {
if (dict[s2[right]]-- > 0)
--win_size;
while (win_size == 0) {
if (s1.size() == right - left + 1) {
return true;
}
if (dict[s2[left++]]++ >= 0) {
++win_size;
}
}
}
return false;
}
};
int main()
{
Solution sol;
cout << sol.checkInclusion("ky", "wkckfykxlribaypk") << endl;
cout << sol.checkInclusion("ky", "ainwkckifykxlribaypk") << endl;
cout << sol.checkInclusion("ab", "eidbaooo") << endl;
cout << sol.checkInclusion("ab", "eidboaoo") << endl;
}
| true |
6d91b1b01ff94f9b580fe05006dbdcf9a86b466c | C++ | hardcoregandhi/AI-Rainbow-Islands-Neural-Network | /GameAI/ChessClosings.cpp | UTF-8 | 1,458 | 3.15625 | 3 | [] | no_license | #include "ChessClosings.h"
ChessClosings* ChessClosings::mInstance = NULL;
ChessClosings::ChessClosings()
{
isActive = false;
}
ChessClosings::~ChessClosings()
{
mInstance = NULL;
}
ChessClosings* ChessClosings::Instance()
{
if (!mInstance)
mInstance = new ChessClosings();
return mInstance;
}
bool ChessClosings::CheckForFinalPieces(Board board)
{
int wPawnCount = 0;
int wKnightCount = 0;
int wRookCount = 0;
int wQueenCount = 0;
int wBishopCount = 0;
int wKingCount = 0;
for (int x = 0; x < kBoardDimensions; x++)
{
for (int y = 0; y < kBoardDimensions; y++)
{
Vector2D piecePosition = Vector2D(x, y);
//Check for pieces.
BoardPiece currentPiece = board.currentLayout[x][y];
if (currentPiece.colour == COLOUR_WHITE && currentPiece.piece != PIECE_NONE)
{
switch (currentPiece.piece)
{
case PIECE_PAWN:
wPawnCount++;
break;
case PIECE_KNIGHT:
wKnightCount++;
break;
case PIECE_BISHOP:
wBishopCount++;
break;
case PIECE_ROOK:
wRookCount++;
break;
case PIECE_QUEEN:
wQueenCount++;
break;
case PIECE_KING:
wKingCount++;
break;
case PIECE_NONE:
break;
default:
break;
}
}
}
}
int pieceCount = wPawnCount + wKnightCount + wBishopCount + wRookCount + wQueenCount;
if (pieceCount < 5)
{
isActive = true;
cout << "Endgame is Active" << endl;
return true;
}
else
return false;
}
| true |
0ee2db73689c6664279382068adbf2a9f3da6c07 | C++ | ChrisCummins/msc-thesis | /exercises/templates/dac/skel-max-subarray.h | UTF-8 | 2,909 | 3.0625 | 3 | [] | no_license | #ifndef EXERCISES_TEMPLATES_DAC_SKEL_MAX_SUBARRAY_H_ // NOLINT(legal/copyright)
#define EXERCISES_TEMPLATES_DAC_SKEL_MAX_SUBARRAY_H_
#include <algorithm>
#include <vector>
#include "./skel.h"
#include "./range.h"
namespace skel {
template<typename ArrayType>
class Problem {
public:
const Range<ArrayType> left;
const Range<ArrayType> right;
Problem() {}
explicit Problem(const Range<ArrayType>& in) :
left(in), right(Range<ArrayType>()) {}
explicit Problem(const Problem& in) :
left(in.left), right(in.right) {}
Problem(const Range<ArrayType>& left, const Range<ArrayType>& right) :
left(left), right(right) {}
};
template<typename ArrayType>
ArrayType max_subarray(const Range<ArrayType>& in);
//
// Max subarray skeleton implementation.
////////////////////////////////////////////////////////////////////
//
// The "is_indivisble" muscle.
template<typename ArrayType>
bool is_indivisible(const Problem<ArrayType>& in) {
return in.right.size() || in.left.size() == 1;
}
// Our "conquer" muscle. A dumb insertion sort, good enough for small
// lists.
template<typename ArrayType>
ArrayType conquer(const Problem<ArrayType>& in) {
if (in.right.size()) {
ArrayType sum = 0, l = 0;
for (int i = in.left.size() - 1; i >= 0; i--) {
sum += in.left.left_[i];
l = std::max(l, sum);
}
sum = 0;
ArrayType r = 0;
for (int i = 0; i < in.right.size(); i++) {
sum += in.right.left_[i];
r = std::max(r, sum);
}
return l + r;
} else {
return in.left.left_[0];
}
}
template<typename ArrayType>
std::vector<Problem<ArrayType>> divide(const Problem<ArrayType>& in) {
std::vector<Range<ArrayType>> ranges =
split_range<ArrayType, 2>(in.left);
std::vector<Problem<ArrayType>> out;
out.push_back(Problem<ArrayType>(ranges[0]));
out.push_back(Problem<ArrayType>(ranges[1]));
out.push_back(Problem<ArrayType>(ranges[0], ranges[1]));
return out;
}
// Our "combine" muscle. Takes two sorted lists, and combines them
// into a single sorted list.
template<typename ArrayType>
ArrayType combine(std::vector<ArrayType> in) {
return std::max(in[0], in[1]) > in[2] ? std::max(in[0], in[1]) : in[2];
}
// Merge sort function.
template<typename ArrayType>
ArrayType max_subarray(ArrayType *const left, ArrayType *const right) {
const Range<ArrayType> range(left, right);
const Problem<ArrayType> problem(range);
return divide_and_conquer<
Problem<ArrayType>, ArrayType, // Data types
is_indivisible<ArrayType>, // is_indivisible() muscle
divide<ArrayType>, // divide() muscle
conquer<ArrayType>, // conquer() muscle
combine<ArrayType>> // combine() muscle
(problem);
}
} // namespace skel
#endif // EXERCISES_TEMPLATES_DAC_SKEL_MAX_SUBARRAY_H_
| true |
03a70dabb6e0b11aaf8b65b6c3a7b659914910d2 | C++ | ajberchek/FinalProectCSE165 | /LevelBuilderAlgorithmText.cpp | UTF-8 | 3,426 | 2.828125 | 3 | [] | no_license | #include "LevelBuilderAlgorithmText.h"
#include <iostream>
#include <fstream>
#include "CollisionShapeRect.h"
#include "Wall.h"
#include "Mole.h"
#include "Coin.h"
#include "Player.h"
#include "Door.h"
using namespace std;
LevelBuilderAlgorithmText::LevelBuilderAlgorithmText(string mazeFile)
{
fileForLvl = mazeFile;
}
void AssignPositions(CollideableContainer ** ccPtr, int maxTextWidth, int lineCount)
{
CollideableContainer * cc = *ccPtr;
//Assign x and y values for the different objects
//Keep in mind that the top left of the screen is 0,0 and the bottom right is width,height
float widthPerObj = newW/(float)maxTextWidth;
float heightPerObj = newH/(float)lineCount;
(*ccPtr)->updateScreenSize(newW, newH);
//cout << "Width of screen: " << newW << endl;
//cout << "Hight of screen: " << newH << endl;
//cout << "Text Width" << maxTextWidth << endl;
//cout << "Line count: " << lineCount << endl;
for(int i = 0; i < cc->collideableFieldPtr->size(); ++i)
{
vector<Collideable *> * currentRow = cc->collideableFieldPtr->at(i);
for(int j = 0; j < currentRow->size(); ++j)
{
Collideable * toEdit = currentRow->at(j);
if(toEdit)
{
toEdit->collisionBox = new CollisionShapeRect(widthPerObj*j,heightPerObj*i,widthPerObj,heightPerObj);
if(toEdit == cc->mainCharacterPtr)
{
toEdit->update(widthPerObj*j+(0.05*widthPerObj),heightPerObj*i + (0.05*heightPerObj),widthPerObj*0.8,heightPerObj*0.8);
}
else
{
toEdit->update(widthPerObj*j,heightPerObj*i,widthPerObj,heightPerObj);
}
}
}
}
}
void LevelBuilderAlgorithmText::genLvl(vector<CollideableContainer *> * ccVec)
{
int lineCount = 0;
int maxTextWidth = 0;
//cout << "Generating Level with filepath: " << fileForLvl << endl;
string line;
ifstream mazeFile(fileForLvl.c_str());
CollideableContainer * cc = new CollideableContainer();
if(mazeFile.is_open())
{
while(getline(mazeFile,line))
{
//cout << line << endl;
//cout << cc->collideableFieldPtr->size() << endl;
if(line == "nn" || line == "nn\n")
{
//cout << line << endl;
//cout << "*****************newLine***********************" << endl;
AssignPositions(&cc,maxTextWidth,lineCount);
ccVec->push_back(cc);
cc = new CollideableContainer();
maxTextWidth = 0;
lineCount = 0;
continue;
}
if(cc->collideableFieldPtr->size() <= lineCount)
{
cc->collideableFieldPtr->push_back(new vector<Collideable *>);
}
vector<Collideable *> * currentRow = cc->collideableFieldPtr->at(lineCount);
for(int i = 0; i < line.length(); ++i)
{
if(currentRow->size() <= i)
{
currentRow->push_back(0);
}
if(line[i] == 'm')
{
currentRow->at(i) = new Mole(0,true);
}
else if(line[i] == 'c')
{
currentRow->at(i) = new Coin();
}
else if(line[i] == 'd')
{
currentRow->at(i) = new Door();
}
else if(line[i] == 'p')
{
currentRow->at(i) = new Player();
cc->mainCharacterPtr = dynamic_cast<Player *>(currentRow->at(i));
}
else if(line[i] == '#')
{
currentRow->at(i) = new Wall();
}
if(i+1 > maxTextWidth)
{
maxTextWidth = i+1;
//cout << "New Max Width of data read: " << maxTextWidth << endl;
}
}
cc->collideableFieldPtr->at(lineCount) = currentRow;
lineCount++;
}
AssignPositions(&cc,maxTextWidth,lineCount);
ccVec->push_back(cc);
}
}
| true |
8190bbfa4d87650d6376208023f3b47dbc96c2ef | C++ | MannySchneck/L2_Compiler | /src/binop.cpp | UTF-8 | 2,256 | 2.578125 | 3 | [] | no_license | #include <binop.h>
#include <labels.h>
#include <ostream>
#include <regs.h>
#include <exception>
#include <iostream>
using namespace L2;
Binop::Binop(Binop_Op op, compiler_ptr<Binop_Lhs> lhs, compiler_ptr<Binop_Rhs> rhs):
lhs(std::move(lhs)),
op(op),
rhs(std::move(rhs)) {}
std::string Binop::stringify_binop_op(Binop_Op op) const{
switch(op){
case(Binop_Op::store):
return "<-";
break;
case(Binop_Op::add_Assign):
return "+=";
break;
case(Binop_Op::sub_Assign):
return "-=";
break;
case(Binop_Op::mult_Assign):
return "*=";
break;
case(Binop_Op::bit_And_Assign):
return "&=";
break;
default:
throw std::logic_error("Invalid binop op");
}
}
void Binop::dump(std::ostream &out) const{
out << "(";
lhs->dump(out);
out << " " << stringify_binop_op(op);
rhs->dump(out);
out << ")";
}
io_set_t Binop::gen() const{
io_set_t gen_st;
insert_name(gen_st, rhs);
// stupid
Memory_Ref* mem_ptr = nullptr;
switch(op){
case(Binop_Op::store):
if(mem_ptr = dynamic_cast<Memory_Ref*>(lhs.get())){
insert_name(gen_st, mem_ptr->get_base());
}
break;
default:
insert_name(gen_st, lhs);
break;
}
return gen_st;
}
io_set_t Binop::kill() const{
io_set_t kill_st;
switch(op){
case(Binop_Op::store):
insert_name(kill_st, lhs);
break;
default:
break;
}
return kill_st;
}
Inst_Ptr Binop::replace_vars(std::unordered_map<std::string, std::string> reg_map) const{
return Inst_Ptr{new Binop{op,
sub_reg_mapping<Binop_Lhs>(reg_map, lhs),
sub_reg_mapping<Binop_Rhs>(reg_map, rhs)}};
}
void Binop::accept(Instruction_Visitor &v){
v.visit(this);
}
void Binop::accept(AST_Item_Visitor &v){
v.visit(this);
}
| true |
5ab13948f6bde4c3dc00c8f5ac40f829c17fb833 | C++ | RusAl84/CaesarEncryptionCourseWork | /CaesarEncryptionСourseWork.cpp | UTF-8 | 824 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "ClassCaesarEncryption.h"
#include <windows.h>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
SetConsoleCP(1251); // Ввод с консоли в кодировке 1251
SetConsoleOutputCP(1251);
cout << "CaesarEncryptionCourseWork!"<<endl
<< "Введите строку для шифрования" << endl;
string inString = "dummy";
ClassCaesarEncryption ce = ClassCaesarEncryption();
while (inString.length() > 1)
{
cin >> inString;
string outString = ce.getEncryptionSting(inString);
cout << "Зашифрованная строка: " << endl
<< outString << endl
<< "Введите строку для шифрования" << endl;
}
return 0;
}
| true |
786bdd8dbe88def94b9cd4765e0e6ccad010ed1a | C++ | vanhoaile95/OOAD-SVN | /BattleTankOnline/BattleCity/BattleCity/UIDigit.cpp | UTF-8 | 854 | 2.765625 | 3 | [] | no_license | #include "UIDigit.h"
UIDigit::UIDigit(P pos, int maxLength, bool visible) :UIObject(pos, BObjectName::UI_DIGIT, visible)
{
InitSprite();
Length = maxLength;
Value = new int[Length];
CurrentColor = Color::White;
}
void UIDigit::UpdateValue(int value)
{
int temp = value;
if (value == -20 || value == -21)
{
RECTIndex = -value;
return;
}
int i = 0;
Length = 0;
do
{
Value[Length] = temp % 10;
Length++;
temp /= 10;
} while (temp > 0);
}
void UIDigit::Draw()
{
if (RECTIndex == 20 || RECTIndex == 21)
{
StaticObject::Draw();
return;
}
P pos = Position;
RECTIndex = 0;
for (int i = Length - 1; i >= 0; i--)
{
RECTIndex = Value[i];
RECTIndex += CurrentColor * 10;
Draw(pos);
pos.X += 30;
}
}
void UIDigit::Draw(P position)
{
UIObject::Draw(position);
}
| true |
4966881055133d35a55a77c64195a62c509f0b20 | C++ | MaximumEndurance/Algo-17 | /HackerBlocksTesting/structurally_idetnical_generic.cpp | UTF-8 | 2,290 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int data;
std::vector<Node*> vec;
Node(int val) {
data = val;
}
};
bool isInOrder = 1;
void InOrder(Node* root1, Node* root2) {
if((root1 == NULL) && (root2== NULL)) return;
// if(!root1 && !root2) { return;}
// if((root1 && !root2) || (!root1 && root2)) {
if((root1 == NULL) ^ (root2 == NULL)) {
isInOrder = 0;
return;
}
// cout<<root1->data<<' '<<root2->data<<endl;
cout<<(root1 == NULL)<<' '<<(root2== NULL)<<endl;
if(root1->data != root2->data) {
isInOrder = 0;
return;
}
if(root1->vec.size() != root2->vec.size()) {
isInOrder = 0;
return;
}
cout<<root1->data<<' '<<root2->data<<endl;
vector<Node*>::iterator ii, jj;
for(ii = root1->vec.begin(), jj = root2->vec.begin(); ii!= root1->vec.end(); ++ii, ++jj) {
root1->vec.push_back((*ii));
root2->vec.push_back((*jj));
InOrder(*ii, *jj);
}
}
// std::vector<int> vec1;
// void InOrder1(Node* root1, Node* root2) {
// if(!root1 && !root2) { return;}
// if((root1 && !root2) || (!root1 && root2)) {
// isInOrder = 0;
// return;
// }
// // cout<<root1->data<<' '<<root2->data<<endl;
// if(root1->data != root2->data) {
// isInOrder = 0;
// return;
// }
// InOrder1(root1->left, root2->left);
// InOrder1(root1->right, root2->right);
// }
// std::vector<int> vec2;
// void InOrder2(Node* root) {
// if(!root) return;
// vec2.push_back(root->data);
// InOrder2(root->left);
// InOrder2(root->right);
// }
Node* InputIt() {
int data;
cin >> data;
Node* root = new Node(data);
int children;
cin >> children;
if(children == 0){
return root;
}
//cout<<root->data<<endl;
while(children--) {
//cout<<'1'<<endl;
Node* newNode = InputIt();
root->vec.push_back(newNode);
}
return root;
}
int main() {
Node* root1 = NULL;
Node* root2 = NULL;
root1 = InputIt();
root2= InputIt();
InOrder(root1, root2);
cout<<"h"<<endl;
cout<<(isInOrder ?"true": "false")<<endl;
return 0;
} | true |
93d04601416a0562628832cb5eabcf04fb903ee4 | C++ | rishabh-997/cpp_codes | /Heaps/max_k_elements.cpp | UTF-8 | 591 | 3.5625 | 4 | [] | no_license | void heapify(int arr[], int n, int i) {
int par = i;
int left = 2*i + 1;
int right = 2*i + 2;
if(left<n && arr[left] > arr[par])
par = left;
if(right<n && arr[right] > arr[par])
par = right;
if(par!=i) {
swap(arr[par], arr[i]);
heapify(arr, n, par);
}
}
vector<int> kLargest(int arr[], int n, int k) {
for(int i = (n/2)-1;i>=0;i--)
heapify(arr, n, i);
vector<int> ans;
for(int i = n-1;i>=(n-k);i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
ans.push_back(arr[i]);
}
return ans;
}
| true |
ede959e30d91218b63b1c91ef2961ac8706817ba | C++ | h2ssh/Vulcan | /src/math/gamma_distribution.h | UTF-8 | 1,832 | 2.78125 | 3 | [
"MIT"
] | permissive | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file gamma_distribution.h
* \author Collin Johnson
*
* Definition of GammaDistribution.
*/
#ifndef MATH_GAMMA_DISTRIBUTION_H
#define MATH_GAMMA_DISTRIBUTION_H
#include <math/univariate_distribution.h>
namespace vulcan
{
namespace math
{
const std::string kGammaType{"gamma"};
/**
* GammaDistribution is a distribution defined in the interval (0, inf] and parameters {k, theta}
*
* G(x) = (1/(gamma(k)*theta^k)) * x^(k-1) * e^(-x / theta)
*
* where gamma() is the gamma function and k > 0, theta > 0
*/
class GammaDistribution : public UnivariateDistribution
{
public:
/**
* Constructor for GammaDistribution.
*
* \param k k-parameter
* \param theta theta-parameter
*/
explicit GammaDistribution(double k = 1.0, double theta = 1.0);
// Observers for the parameters
double k(void) const { return k_; }
double theta(void) const { return theta_; }
// UnivariateDistribution interface
virtual std::string name (void) const override { return kGammaType; }
virtual double sample (void) const override;
virtual double likelihood(double value) const override;
virtual bool save (std::ostream& out) const override;
virtual bool load (std::istream& in) override;
private:
double k_;
double theta_;
double normalizer_;
};
}
}
#endif // MATH_GAMMA_DISTRIBUTION_H
| true |
28096cbb094d2dad5ff79fa602bc0ed274a8f821 | C++ | yanjunp-cmu/LeetCode | /221. Maximal Square.cpp | UTF-8 | 1,733 | 3.609375 | 4 | [] | no_license | /*
* 2D dynamic programming
* dp matrix is (nR+1) x (nC+1)
* dp[i][j] represents the longest sqr_len cornered at (i-1,j-1)
* the new corner is the right corner of the square with length min(left, up, left_up) + 1
*/
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty())
return 0;
int nR = matrix.size(), nC = matrix[0].size();
vector<vector<int>> dp(nR + 1, vector<int>(nC + 1, 0));
int maxsqlen = 0;
for (int i = 1; i <= nR; i++){
for (int j = 1; j <= nC; j++){
if (matrix[i-1][j-1] == '1'){
dp[i][j] = min( min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
maxsqlen = max(maxsqlen, dp[i][j]);
}
}
}
return maxsqlen * maxsqlen;
}
};
/*
* 1D dynamic programming
* dp array is nC+1 long
* use a prev to keep track of dp[i-1][j-1] as if in 2D DP solution
*/
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty())
return 0;
int nR = matrix.size(), nC = matrix[0].size();
vector<int> dp(nC + 1, 0);
int prev = 0;
int maxsqlen = 0;
for (int i = 1; i <= nR; i++){
for (int j = 1; j <= nC; j++){
int temp = dp[j];
if (matrix[i - 1][j - 1] == '1') {
dp[j] =min(min(dp[j - 1], prev), dp[j]) + 1;
maxsqlen = max(maxsqlen, dp[j]);
} else {
dp[j] = 0;
}
prev = temp;
}
}
return maxsqlen * maxsqlen;
}
}; | true |
d19e127b6fdbc49c6680e3c3c734c286658143e6 | C++ | haitomns4173/c_practice | /login_system.cpp | UTF-8 | 3,418 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
#include <conio.h>
using namespace std;
// Function for printing the top Part of Program
void topPrint()
{
system("cls");
cout << " Haitomns System!" << endl
<< endl;
}
//Function for setting the pointer location
void setPointer(short int xpnt, short int ypnt)
{
COORD position = {xpnt, ypnt};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), position);
}
// Class Used for Login of the registered users
class Login : public Registeration
{
protected:
string username, password;
public:
void inputUsernamePasword()
{
topPrint();
cout << " Username : ";
cout << " Password : ";
setPointer(18, 8);
cin >> username;
setPointer(18, 8);
cin >> password;
checkPassword(username, password);
}
void checkPassword(string username, string password)
{
string temp_username, temp_password;
temp_username = username;
temp_password = password;
fstream regFileRead;
// Registeration regReadData;
regFileRead.open("Registeration.txt", ios::in | ios::binary);
while ((regFileRead.read((char *)®First, sizeof(regFirst))))
{
if (temp_username.compare(username) == 0 && temp_password.compare(password))
{
cout << endl
<< endl
<< "Logined!";
}
}
regFileRead.close();
}
};
// Derived Class for registeration of users from the login
class Registeration : public Login
{
protected:
string first_name, last_name, age, address, phone_no, email;
public:
void inputRegisterationData()
{
topPrint();
cout << " 1. First Name : " << endl;
cout << " 2. Last Name : " << endl;
cout << " 3. Age : " << endl;
cout << " 4. Address : " << endl;
cout << " 5. Phone : " << endl;
cout << " 6. Emaill : " << endl;
cout << " 7. Username : " << endl;
cout << " 9. Password : " << endl;
setPointer(18, 2);
cin >> first_name;
setPointer(18, 3);
cin >> last_name;
setPointer(18, 4);
cin >> age;
setPointer(18, 5);
cin >> address;
setPointer(18, 6);
cin >> phone_no;
setPointer(18, 7);
cin >> email;
setPointer(18, 8);
cin >> username;
setPointer(18, 9);
cin >> password;
}
void writeToRegfile()
{
fstream regFile;
Registeration regAddData;
regFile.open("Registeration.txt", ios::app | ios::binary);
regAddData.inputRegisterationData();
regFile.write((char *)®AddData, sizeof(regAddData));
regFile.close();
int main();
}
};
int main()
{
int select_menu;
Login loginFirst;
Registeration regFirst;
// Menu of Program
topPrint();
cout << " 1. Login" << endl
<< " 2. Registeration" << endl
<< " 3. Exit" << endl
<< endl
<< " Enter the number : ";
cin >> select_menu;
// Selection of Menu
switch (select_menu)
{
case 1:
loginFirst.inputUsernamePasword();
break;
case 2:
regFirst.writeToRegfile();
break;
}
return 0;
}
| true |
165464d5fa48f3fb54595db3d343d9d3489ecf3c | C++ | kdoda/Efficient-Algorithms | /Data Structures and Algorithm Analysis Book/U 2.28 a.cpp | UTF-8 | 641 | 3.453125 | 3 | [] | no_license | //Design efficient algorithms that take an array of positive numbers a, and determine:
//a. the maximum value of a[j]+a[i], with j≥i
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
vector<int> v(7);
for(int i=0;i<7;i++)
cin>>v[i];
int max1,max2,min=v[0];
if(v[0]>v[1])
{
max1=v[0];
max2=v[1];
}
else{
max1=v[1];
max2=v[0];
}
for(int i=1;i<7;i++)
{
if(v[i]>max1)
{
max2=max1;
max1=v[i];
}
else if(v[i]>max2)
max2=v[i];
}
cout<<endl<<max1+max2;
cout<<endl<<max1*max2;
}
| true |
5176247c7542a9fec501943610423690011daa59 | C++ | alr0cks/CollegeStuff | /HPC/Vector_Addition.cpp | UTF-8 | 640 | 3.296875 | 3 | [] | no_license | #include<iostream>
//#include<omp.h>
# define MAX 10000
using namespace std;
void populate(int arr[],int n){
for(int i=0;i<n;i++)
{
arr[i]=i;
}
}
int *sum(int arr1[], int arr2[],int n)
{
int * temp;
for(int i =0;i<n;i++)
{
temp[i] = arr1[i]+arr2[i];
}
return temp;
}
int main()
{
int n,arr1[MAX],arr2[MAX];
cout<<"Enter the No. of Elements in Vector:";
cin>>n;
populate(arr1,n);
populate(arr2,n);
for(int i=0;i<n;i++)
{
cout<<"1:"<<arr1[i]<<" "<<"2:"<<arr2[i];
cout<<"\n";
}
int * add=sum(arr1,arr2,n);
//cout<<"Sum:";
for(int i=0;i<n;i++)
{
cout<<add[i]<<"\n";
}
}
| true |
63ecfd0ca75598b99cce0ac06953eaf04a954b85 | C++ | zgpio/OJ | /lc_main/83_删除排序链表中的重复元素.cc | UTF-8 | 863 | 3.296875 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <lc/list.h>
#include <vector>
using namespace std;
// 使用相邻双指针解决有序重复元素问题
ListNode *deleteDuplicates(ListNode *head)
{
if (head == nullptr) return nullptr;
ListNode *i = head, *j = head->next;
while (j) {
if (i->val == j->val) {
i->next = j->next;
delete j;
j = i->next;
}
else {
i = i->next;
j = j->next;
}
}
return head;
}
int main(int argc, char *argv[])
{
vector<pair<initializer_list<int>, initializer_list<int>>> cases = {
{{1, 1, 2}, {1, 2}}, {{1, 1, 2, 3, 3}, {1, 2, 3}}};
for (auto c : cases) {
ListNode *l = buildList(c.first);
printL(l);
ListNode *rl = deleteDuplicates(l);
printL(rl);
}
return 0;
}
| true |
47e07f2d3439c7607c996e4ed057f282da47f240 | C++ | krishnashah921/Stack | /infix to postfix done.....cpp | UTF-8 | 2,296 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define SIZE 100
char stack[SIZE];
int top=-1;
void push(char item)
{
if (top==SIZE-1)
{
printf("overflow\n");
}
else
{
top++;
stack[top]=item;
}
}
char pop()
{
char item;
if (top==-1)
{
printf("underflow\n");
}
else
{
item=stack[top];
top--;
return (item);
}
}
int isoperator(char symbol)
{
if (symbol=='^'||symbol=='*'||symbol=='/'||symbol=='+'||symbol=='-')
{
return 1;
}
else
{
return 0;
}
}
int precedence(char symbol)
{
if (symbol=='^')
{
return 3;
}
else if (symbol=='*'|| symbol=='/')
{
return 2;
}
else if (symbol=='+'|| symbol=='-')
{
return 1;
}
else
{
return 0;
}
}
int infixtopostfix(char infixexp[],char postfixexp[])
{
int i=0,j=0;
char item;
char x;
push('(');
strcat(infixexp,")");
item=infixexp[i];
while(item != '\0') /* run loop till end of infix expression */
{
// item=infixexp[i];
if (item=='(')
{
push(item);
}
else if(item>='A'&& item<='Z' || item>='a' && item<='z')
{
postfixexp[j]=item;
j++;
}
else if (isoperator(item)==1)
{
x=pop();
while (isoperator(x)==1 && precedence(x)>precedence(item))
{
postfixexp[j]=x;
j++;
x=pop();
}
push(x);
push(item);
}
else if (item==')')
{
x=pop();
while (x!='(')
{
postfixexp[j]=x;
j++;
x=pop();
}
}
else
{
printf("invalid expression\n");
getchar();
exit(1);
}
i++;
item=infixexp[i];
}
}
int main()
{
char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */
/* why we asked the user to enter infix expression
* in parentheses ( )
* What changes are required in porgram to
* get rid of this restriction since it is not
* in algorithm
* */
printf("ASSUMPTION: The infix expression contains single letter variables and single digit constants only.\n");
printf("\nEnter Infix expression : ");
gets(infix);
infixtopostfix(infix,postfix); /* call to convert */
printf("Postfix Expression: ");
puts(postfix); /* print postfix expression */
return 0;
}
| true |
c5b361e840c4d4c6ced15c41cdc293ab24e9144b | C++ | JosiahCraw/OpenGL-Ray-Tracer | /Cone.cpp | UTF-8 | 1,462 | 2.9375 | 3 | [] | no_license | //
// Created by joscraw on 5/31/19.
//
#include "Cone.h"
#include <math.h>
float Cone::intersect(glm::vec3 posn, glm::vec3 dir)
{
float an = posn.x - centre.x;
float bn = posn.z - centre.z;
float dn = height - posn.y + centre.y;
float tan = (radius / height) * (radius / height);
float a = (dir.x * dir.x) + (dir.z * dir.z) - (tan*(dir.y * dir.y));
float b = (2*an*dir.x) + (2*bn*dir.z) + (2*tan*dn*dir.y);
float c = (an*an) + (bn*bn) - (tan*(dn*dn));
float delta = b*b - 4*(a*c); // Quadratic complex comonent
if(fabs(delta) < 0.001) return -1.0; // Return no object if complex part is close to zero
if(delta < 0.0) return -1.0;
// Full quadratic
float t1 = (-b - sqrt(delta))/(2*a);
float t2 = (-b + sqrt(delta))/(2*a);
float t;
if (t1>t2) t = t2;
else t = t1;
float r = posn.y + t*dir.y;
if ((r > centre.y) and (r < centre.y + height)) {
return t;
}
else return -1; // No intercestion
}
glm::vec3 Cone::normal(glm::vec3 pt)
{
float temp = sqrt((pt.x-centre.x)*(pt.x-centre.x) + (pt.z-centre.z)*(pt.z-centre.z));
glm::vec3 n = glm::vec3(pt.x-centre.x, temp*(radius/height), pt.z-centre.z);
n = glm::normalize(n);
return n;
}
std::vector<float> Cone::texCoord(glm::vec3 pt) {
std::vector<float> out;
out.push_back(0);
out.push_back(0);
return out;
}
glm::vec3 Cone::procedCol(glm::vec3 pt) {
return glm::vec3(0);
}
| true |
e78fcf082d51f2d20f0dddea261d7a7fb279f1b4 | C++ | mortenoj/mathematics | /mathforgamedev/movement/Point.h | UTF-8 | 624 | 3.546875 | 4 | [] | no_license | class Point {
public:
// Values
float x;
float y;
float z;
// Constructors
Point(float x, float y, float z);
Point();
// Operators
Vector operator-(Point a);
// Methods
Point addVector(Vector v);
};
Point::Point() {
}
Point::Point(float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
}
// Operator overloading
Vector Point::operator-(Point a) {
return Vector(
x - a.x,
y - a.y,
z - a.z
);
}
// Methods
Point Point::addVector(Vector v) {
return Point(
x + v.x,
y + v.y,
z + v.z
);
} | true |
4f134eced7fd3d2177dd2d275a4f12a63bb73a76 | C++ | brian-stack/Database | /stokenizer.h | UTF-8 | 1,142 | 2.9375 | 3 | [] | no_license | #ifndef STOKENIZER_H
#define STOKENIZER_H
#include <cstring>
#include <cassert>
#include <iostream>
#include "table_util.h"
#include "token.h"
#include "map.h"
class STokenizer
{
//extract one token (very similar to the way cin >> works)
friend STokenizer& operator >> (STokenizer& s, Token& t);
public:
STokenizer();
STokenizer(char str[]);
bool done(); //true: there are no more tokens
bool more(); //true: there are more tokens
void setString(char str[]); //set a new string as the input string
private:
//create table for all the tokens we will recognize
// (e.g. doubles, words, etc.)
void makeTable();
void initInterpreterMaps();
//returns true if a token is found, otherwise false.
bool getToken(int start_state, string& token);
void removeQuotes(string& token);
char buffer[MAX_BUFFER];
size_t bufferSize;
size_t pos; //current position in the string
int _table[MAX_ROWS][MAX_COLUMNS]; //adjacency matrix
static Map<string,typeID> _typeMap;
};
#endif //STOKENIZER_H
| true |
077d6fb5643ba32408d1e22a8dcd9a5be67c10c0 | C++ | realdubb/OS-Project-2 | /Wachira_P2/Wachira_P2/main.cpp | UTF-8 | 2,350 | 3.203125 | 3 | [] | no_license | #include "header.h"
#include <string>
void main(void)
{
link ptr, firstptr, lastptr;
firstptr = NULL;
HANDLE file;
char sel;
firstptr = readdb();
//if no file exists create one, otherwise read it in
if (!firstptr)
file = createdb(firstptr);
else
firstptr = readdb();
while(true)
{
printf("\nSelect Option:\n");
printf("(1) Add Item\n");
printf("(2) Remove Item\n");
printf("(3) Display all items\n");
printf("(4) Save and exit\n");
sel=_getch();
switch(sel)
{
case '1':
firstptr = NULL; //set pointers to nothing.
lastptr = NULL;
while (true)
{
if ((ptr = newflt()) == NULL) //if ptr is NULL, database entry is finished
{
free(ptr); //release memory for bogus allocation
break; //get out of input loop
}
if (!firstptr) firstptr = ptr; //for first object only, assign firstptr
else lastptr->next = ptr; //for all other objects, point last to this one
ptr->last = lastptr; //for all, point to prevfious object
lastptr = ptr; //update last pointer to point to this object
}
dispdb(firstptr);
writedb(firstptr);
break;
case '2':
firstptr = deleteItem();
break;
case '3':
//firstptr=delflt(firstptr);
dispdb(firstptr);
break;
case '4':
writedb(firstptr);
exit(0);
default:
printf("This was an invalid option. Try again");
}
}
}
void insert(link firstptr){
DWORD count;
HANDLE file;
link ptr;
TCHAR fname[] = TEXT("OrderData.dat");
file = CreateFile(fname, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
firstptr = newflt();
WriteFile(file, firstptr, sizeof(struct item), &count, NULL);
CloseHandle(file);
return;
}
link newflt(void)
{
char indat[64]; //inout line to be parsed
char *pindat; //pointer to input line
link ptr; //pointer to parsed data structure
ptr = (link)malloc(sizeof(struct item)); //allocate memory for structure
//ptr->last = NULL;
//ptr->next = NULL;
printf("\nProvide the following or enter x to exit.\n");
printf("itemID quantity price description \n"); //request input data
gets_s(indat); //get input data
pindat = indat; //set pointer to start of input data
if (indat[0] == 'x' || indat[0] == 'X') return NULL;
ptr = parse(pindat, ptr);
ptr->next = NULL;
ptr->last = NULL;
return ptr;
}
| true |
28a79b7eb22d45477a71fd64dc8f91f44aad7586 | C++ | ivysnow/virtuanes | /NES/Mapper/Mapper244.cpp | UTF-8 | 510 | 2.53125 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////
// Mapper244 //
//////////////////////////////////////////////////////////////////////////
void Mapper244::Reset()
{
SetPROM_32K_Bank( 0 );
}
void Mapper244::Write( WORD addr, BYTE data )
{
if( addr>=0x8065 && addr<=0x80A4 ) {
SetPROM_32K_Bank( (addr-0x8065)&0x3 );
}
if( addr>=0x80A5 && addr<=0x80E4 ) {
SetVROM_8K_Bank( (addr-0x80A5)&0x7 );
}
}
| true |
629feb5d242e00c1ac0e037c2508df498a766b79 | C++ | bulacu-magda/Alemia | /data/raw/train/student_48/2083/2081/InputProcesser.h | UTF-8 | 2,283 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Transform.h"
#include "Sprite.h"
#include "MouseHandler.h"
#define MOUSE_CLICK 0
#define MOUSE_MOVE 1
#define MOUSE_DOUBLE_CLICK 2
template <class Interactable>
class InputProcesser :
public Component
{
MouseHandler& localMouseHandler;
Interactable& parent;
const Transform& parentTransform;
public:
InputProcesser() = delete;
InputProcesser(const InputProcesser&) = delete;
InputProcesser& operator=(const InputProcesser&) = delete;
InputProcesser(Interactable& parent) :
Component(Component::Type::INPUTPROCESSER, 0),
parent(parent),
parentTransform(parent._transform()),
localMouseHandler(MouseHandler::getInstance()) {}
InputProcesser(Interactable& parent,
bool isRemovable) :
Component(Component::Type::INPUTPROCESSER, isRemovable, 0),
parent(parent),
parentTransform(parent._transform()),
localMouseHandler(MouseHandler::getInstance()) {}
~InputProcesser()
{
localMouseHandler.releaseInstance();
}
C2D::Vector2 getMousePosition()
{
return C2D::Vector2(localMouseHandler.getPosX(), localMouseHandler.getPosY());
}
private:
void Start() override final {}
void Update() override final
{
processMouseInput();
}
void End() override final {}
void processMouseInput()
{
int result = localMouseHandler.getProcessedInput();
switch (result)
{
case MOUSE_CLICK:
{
if (isMouseInRange())
parent.onMouseClick();
else
parent.onClickOutOfRange();
break;
}
case MOUSE_MOVED:
{
if (isMouseInRange())
parent.onMouseHover();
else
parent.tryReset();
break;
}
case MOUSE_DOUBLE_CLICK:
{
if (isMouseInRange())
parent.onMouseDoubleClick();
break;
}
default:
{
break;
}
}
}
bool isMouseInRange()
{
int mousePosX = localMouseHandler.getPosX();
int mousePosY = localMouseHandler.getPosY();
int thisPosX = parentTransform.getPosition().getX();
int thisPosY = parentTransform.getPosition().getY();
int thisWidth = parentTransform.getSize().getX();
int thisHeight = parentTransform.getSize().getY();
if (mousePosX < thisPosX)
return false;
if (mousePosY > thisPosY)
return false;
if (mousePosX >= thisPosX + thisWidth)
return false;
if (mousePosY <= thisPosY - thisHeight)
return false;
return true;
}
};
| true |
5fa951819d19982345c95f89a8301699c8430aee | C++ | JoseManuelAlcaldeLlergo/Algoritmica | /Reinas/ClaseTiempo.cpp | UTF-8 | 1,138 | 3 | 3 | [] | no_license | #include "ClaseTiempo.hpp"
Clock::Clock ()
{
memset(&_start,0,sizeof(timespec));
memset(&_stop,0,sizeof(timespec));
_isStarted=false;
}
/*!\brief Starts the clock.
* \pre not isStarted()
* \post isStarted()
*/
void Clock::start ()
{
assert (!isStarted());
clock_gettime (CLOCK_REALTIME, &_start);
_isStarted=true;
}
/*!\brief Re-starts the clock.
* \post isStarted()
*/
void Clock::restart ()
{
clock_gettime (CLOCK_REALTIME, &_start);
_isStarted=true;
}
/*!\brief Stops the clock.
* \pre isStarted()
* \post not isStarted()
*/
void Clock::stop ()
{
assert (_isStarted);
clock_gettime (CLOCK_REALTIME, &_stop);
_isStarted=false;
}
/*!\brief Is the clock started?
* \return true if the clock is started currently.
*/
bool Clock::isStarted() const
{
return _isStarted;
}
/*!\brief Return the elapsed time in mcs.*/
uint64_t Clock::elapsed() const
{
assert (!_isStarted);
uint64_t startT = (uint64_t)_start.tv_sec * 1000000LL + (uint64_t)_start.tv_nsec / 1000LL;
uint64_t stopT = (uint64_t)_stop.tv_sec * 1000000LL + (uint64_t)_stop.tv_nsec / 1000LL;
return stopT-startT;
} | true |
1f0d97915597fe35da5387983d41b81fe9765913 | C++ | countryhu/algorithm | /now_coder/cracking_the_code_interview/9_recursion/7_floodFill.cc | UTF-8 | 5,011 | 3.578125 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <list>
#include <vector>
#include <map>
/**
题目描述
在一个nxm矩阵形状的城市里爆发了洪水,洪水从(0,0)的格子流到这个城市,
在这个矩阵中有的格子有一些建筑,洪水只能在没有建筑的格子流动。
请返回洪水流到(n - 1,m - 1)的最早时间(洪水只能从一个格子流到其相邻的格子且洪水单位时间能从一个格子流到相邻格子)。
给定一个矩阵map表示城市,其中map[i][j]表示坐标为(i,j)的格子,值为1代表该格子有建筑,0代表没有建筑。
同时给定矩阵的大小n和m(n和m均小于等于100),请返回流到(n - 1,m - 1)的最早时间。保证洪水一定能流到终点。
-------
题目分析
**/
class Flood {
public:
int floodFill(std::vector<std::vector<int> > map, int n, int m) {
return myFloodFill(map, n, m);
}
private:
int myFloodFill(const std::vector<std::vector<int> >& map, int n, int m) {
// 只有一个点,起点即是终点。
if (n == 1 && m == 1) {
return 0;
}
// 初始化图访问状态
std::map<size_t, std::map<size_t, Node*> > bfsMap_;
for (size_t i = 0; i < map.size(); ++i) {
for (size_t j = 0; j < map[i].size(); ++j) {
Node* node = new Node(i, j);
bfsMap_[i][j] = node;
}
}
// bfs
std::list<Node*> visitingList;
visitingList.push_back(bfsMap_[0][0]); // 上
bfsMap_[0][0]->visitState_ = Node::Visiting;
while (!visitingList.empty()) {
Node* node = visitingList.front();
visitingList.pop_front();
// std::cout << "====" << node->x_ << ":" << node->y_ << std::endl;
// 邻点入栈: 左
if (node->y_ - 1 >= 0 // 边界
&& map[node->x_][node->y_ - 1] == 0 // 没有阻碍物
&& bfsMap_[node->x_][node->y_ - 1]->visitState_ == Node::UnVisit) { // 未访问过
Node* nearNode = bfsMap_[node->x_][node->y_ - 1];
nearNode->dis_ = node->dis_ + 1;
// 是否到达终点
if (nearNode->x_ == n - 1 && nearNode->y_ == m - 1) {
return nearNode->dis_;
}
nearNode->visitState_ = Node::Visiting;
visitingList.push_back(nearNode);
// std::cout << "push :" << nearNode->x_ << ":" << nearNode->y_ << std::endl;
}
// 邻点入栈: 右
if (node->y_ + 1 <= m - 1 // 边界
&& map[node->x_][node->y_ + 1] == 0 // 没有阻碍物
&& bfsMap_[node->x_][node->y_ + 1]->visitState_ == Node::UnVisit) { // 未访问过
Node* nearNode = bfsMap_[node->x_][node->y_ + 1];
nearNode->dis_ = node->dis_ + 1;
// 是否到达终点
if (nearNode->x_ == n - 1 && nearNode->y_ == m - 1) {
return nearNode->dis_;
}
nearNode->visitState_ = Node::Visiting;
visitingList.push_back(nearNode);
// std::cout << "push :" << nearNode->x_ << ":" << nearNode->y_ << std::endl;
}
// 邻点入栈: 上
if (node->x_ - 1 >= 0 // 边界
&& map[node->x_ - 1][node->y_] == 0 // 没有阻碍物
&& bfsMap_[node->x_ - 1][node->y_]->visitState_ == Node::UnVisit) { // 未访问过
Node* nearNode = bfsMap_[node->x_ - 1][node->y_];
nearNode->dis_ = node->dis_ + 1;
// 是否到达终点
if (nearNode->x_ == n - 1 && nearNode->y_ == m - 1) {
return nearNode->dis_;
}
nearNode->visitState_ = Node::Visiting;
visitingList.push_back(nearNode);
// std::cout << "push :" << nearNode->x_ << ":" << nearNode->y_ << std::endl;
}
// 邻点入栈: 下
if (node->x_ + 1 <= n - 1 // 边界
&& map[node->x_ + 1][node->y_] == 0 // 没有阻碍物
&& bfsMap_[node->x_ + 1][node->y_]->visitState_ == Node::UnVisit) { // 未访问过
Node* nearNode = bfsMap_[node->x_ + 1][node->y_];
nearNode->dis_ = node->dis_ + 1;
// 是否到达终点
if (nearNode->x_ == n - 1 && nearNode->y_ == m - 1) {
return nearNode->dis_;
}
nearNode->visitState_ = Node::Visiting;
visitingList.push_back(nearNode);
// std::cout << "push :" << nearNode->x_ << ":" << nearNode->y_ << std::endl;
}
// 访问完毕
node->visitState_ = Node::Visited;
}
return -1; // 没找到终点
}
struct Node {
Node(int x, int y) {
x_ = x;
y_ = y;
dis_ = 0;
visitState_ = UnVisit;
}
int x_;
int y_;
int dis_;
enum VisitState {
UnVisit,
Visiting,
Visited,
};
VisitState visitState_;
};
};
int main() {
// 样例
{
Flood obj;
std::vector<std::vector<int> > map {{0,1,0}, {0,0,0},{0,0,0}};
std::cout << obj.floodFill(map, 3, 3) << std::endl;
}
{
Flood obj;
std::vector<std::vector<int> > map {{0,0,0}, {1,0,1},{0,0,0}, {0,1,0}};
std::cout << obj.floodFill(map, 4, 3) << std::endl;
}
return 0;
}
| true |
d6a0848024683d36cee3d64a9ad5511ac198535b | C++ | superweaver/leetcode | /p1383.cc | UTF-8 | 2,685 | 3.203125 | 3 | [] | no_license | #include "common.h"
class Solution {
// https://zxi.mytechroad.com/blog/greedy/leetcode-1383-maximum-performance-of-a-team/
public:
int maxPerformance(int n, vector<int> &speed, vector<int> &efficiency, int k) {
const int Mod = 1e9 + 7;
// !!!
// sort them according to desceding efficiency
vector<pair<int, int>> es; // efficiency, speed
for (int i = 0; i < n; ++i) {
es.push_back({efficiency[i], speed[i]});
}
// nice
sort(es.rbegin(), es.rend());
long long sum = 0; // sum of speed
priority_queue<int, vector<int>, greater<int>> q; // store speed
long long performance = 0;
// !!!! at most k engineers
// not exactly k engineers
for (int i = 0; i < k; ++i) {
sum += es[i].second;
q.push(es[i].second);
performance = max(performance, sum * es[i].first);
}
// this is wrong !!!
//long long performance = sum * es[k-1].first;
//// es[k-1] has the lowest efficiency
for (int i = k; i < n; ++i) {
// remove the shortest speed
sum -= q.top();
q.pop();
// for the new candidate
// 1) don't include, performace has no change
// 2) include it, the minimum efficiency must be es[i].frist;
// find the smallest speed, and replace it with es[i].second;
// add the new candidate
sum += es[i].second;
q.push(es[i].second);
performance = max(performance, sum * es[i].first);
}
return performance % Mod;
}
};
// Author: Huahua
class Solution_huahua {
public:
int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {
vector<pair<int, int>> es;
for (int i = 0; i < n; ++i)
es.push_back({efficiency[i], speed[i]});
sort(es.rbegin(), es.rend());
priority_queue<int, vector<int>, greater<int>> q;
long sum = 0;
long ans = 0;
for (int i = 0; i < n; ++i) {
if (i >= k) {
sum -= q.top();
q.pop();
}
sum += es[i].second;
q.push(es[i].second);
ans = max(ans, sum * es[i].first);
}
return ans % static_cast<int>(1e9 + 7);
}
};
int main() {
int n = 6;
vector<int> speed = {2,10,3,1,5,8};
vector<int> efficiency = {5,4,3,9,7,2};
int k = 2; // 60
n = 6, speed = {2, 10, 3, 1, 5, 8}, efficiency = {5, 4, 3, 9, 7, 2}, k = 3; // 68
n = 3,speed = {2,8,2}, efficiency = {2,7,1}, k = 2;
Solution s;
cout << s.maxPerformance(n, speed, efficiency, k) << endl;
{
Solution_huahua s;
cout << s.maxPerformance(n, speed, efficiency, k) << endl;
}
return 0;
}
| true |
26188edbff79abd17682a32a4ccbf207c06811ad | C++ | XiayangJin/GoAndDoIt | /CSearch.cpp | UTF-8 | 765 | 2.59375 | 3 | [] | no_license | #include "stdafx.h"
#include "CSearch.h"
CSearch::CSearch()
{
}
CSearch::~CSearch()
{
}
vector<int> CSearch::GetWordsTimes(vector<string> &m_vsCaughtWords, vector<string> &m_vsWords){
vector<int> vnWordsTimes;
int nCounter = 0;
for (int i = 0; i < m_vsWords.size(); i++){
nCounter = 0;
for (int j = 0; j < m_vsCaughtWords.size(); j++){
if (m_vsWords[i] == m_vsCaughtWords[j]){
nCounter++;
}
}
vnWordsTimes.push_back(nCounter);
}
return vnWordsTimes;
}
vector<double> CSearch::GetWordsRate(vector<string> &m_vsCaughtWords, vector<int> &m_vnWordsTimes){
vector<double> vdWordsRate;
for (int i = 0; i < m_vnWordsTimes.size(); i++){
vdWordsRate.push_back((double)m_vnWordsTimes[i]/m_vsCaughtWords.size());
}
return vdWordsRate;
}
| true |
cda6ddd7a4f132c62a98a3168d2d566bbdfe8c5f | C++ | AlexPax/AfelBot | /MotorDriver/MotorDriver.ino | UTF-8 | 4,588 | 2.875 | 3 | [] | no_license | // Прошивка драйвера двигателей. Версия 4.0.
#include <Servo.h>
const int LEFT_MOTOR_DIR_PIN = 7;
const int LEFT_MOTOR_PWM_PIN = 9;
const int RIGHT_MOTOR_DIR_PIN = 8;
const int RIGHT_MOTOR_PWM_PIN = 10;
// Этими константами можно выравнять движение вперед, если робот сремится завернуть вправо или влево из-за того, что двигатели разные.
const byte LEFT_MOTOR_SPEED = 100;
const byte RIGHT_MOTOR_SPEED = 100;
// Эти константы задают крайние положения для сервоприводов
const byte CAMERA_EXTREME_LEFT = 180;
const byte CAMERA_CENTER = 90;
const byte CAMERA_EXTREME_RIGHT = 0;
const byte CAMERA_EXTREME_DOWN = 42;
const byte CAMERA_STRAIGHT_FORWARD = 75;
const byte CAMERA_EXTREAM_UP = 180;
const byte CAMERA_STEP = 3;
Servo cameraLeftRight;
Servo cameraUpDown;
//----------------------------------------------------------
void setup()
{
// Setup the pins
pinMode( LEFT_MOTOR_DIR_PIN, OUTPUT );
pinMode( LEFT_MOTOR_PWM_PIN, OUTPUT );
pinMode( RIGHT_MOTOR_DIR_PIN, OUTPUT );
pinMode( RIGHT_MOTOR_PWM_PIN, OUTPUT );
cameraLeftRight.attach(12);
cameraLeftRight.write(CAMERA_CENTER);
cameraUpDown.attach(13);
cameraUpDown.write(CAMERA_STRAIGHT_FORWARD);
Serial.begin(9600, SERIAL_8N1);
while (!Serial) {}
}
//----------------------------------------------------------
void loop()
{
byte pos;
if(Serial.available() > 0){
// Чтение команды
int inByte = Serial.read();
// Обработка команд от малинки
switch(inByte){
case 'f':
// Двигаемся вперед
digitalWrite( LEFT_MOTOR_DIR_PIN, HIGH );
digitalWrite( RIGHT_MOTOR_DIR_PIN, HIGH );
analogWrite( LEFT_MOTOR_PWM_PIN, LEFT_MOTOR_SPEED );
analogWrite( RIGHT_MOTOR_PWM_PIN, RIGHT_MOTOR_SPEED );
break;
case 'r':
// Поворачиваем направо
digitalWrite( LEFT_MOTOR_DIR_PIN, LOW);
digitalWrite( RIGHT_MOTOR_DIR_PIN, HIGH );
analogWrite( LEFT_MOTOR_PWM_PIN, 128 );
analogWrite( RIGHT_MOTOR_PWM_PIN, 128 );
break;
case 'l':
// Поворачиваем налево
digitalWrite( LEFT_MOTOR_DIR_PIN, HIGH );
digitalWrite( RIGHT_MOTOR_DIR_PIN, LOW );
analogWrite( LEFT_MOTOR_PWM_PIN, 128 );
analogWrite( RIGHT_MOTOR_PWM_PIN, 128 );
break;
case 'b':
// Двигаемся назад
digitalWrite( LEFT_MOTOR_DIR_PIN, LOW );
digitalWrite( RIGHT_MOTOR_DIR_PIN, LOW );
analogWrite( LEFT_MOTOR_PWM_PIN, LEFT_MOTOR_SPEED );
analogWrite( RIGHT_MOTOR_PWM_PIN, RIGHT_MOTOR_SPEED );
break;
case 'u':
// Камера вверх
pos = cameraUpDown.read();
pos += CAMERA_STEP;
if(pos < CAMERA_EXTREAM_UP) {
cameraUpDown.write(pos);
}
Serial.println(pos);
break;
case 'd':
// Камера вверх
pos = cameraUpDown.read();
pos -= CAMERA_STEP;
if(pos > CAMERA_EXTREME_DOWN) {
cameraUpDown.write(pos);
}
Serial.println(pos);
break;
case 'q':
// Камера влево
pos = cameraLeftRight.read();
pos += CAMERA_STEP;
if(pos < CAMERA_EXTREME_LEFT) {
cameraLeftRight.write(pos);
}
Serial.println(pos);
break;
case 'e':
// Камера вправо
pos = cameraLeftRight.read();
pos -= CAMERA_STEP;
if(pos > CAMERA_EXTREME_RIGHT) {
cameraLeftRight.write(pos);
}
Serial.println(pos);
break;
case 'w':
// Камера по центру.
cameraLeftRight.write(CAMERA_CENTER);
cameraUpDown.write(CAMERA_STRAIGHT_FORWARD);
break;
case 's':
// Останавливаемся.
digitalWrite( LEFT_MOTOR_DIR_PIN, HIGH );
digitalWrite( RIGHT_MOTOR_DIR_PIN, HIGH);
analogWrite( LEFT_MOTOR_PWM_PIN, 0 );
analogWrite( RIGHT_MOTOR_PWM_PIN, 0 );
break;
}
Serial.write(inByte);
Serial.write('\n');
} else {
// Если никакая команда не пришла, то поспать немного, чтобы зря не расходовать батарею.
delay(10);
}
}
| true |
77b72a09602f9a1394c111ef1a26407a5ab8017e | C++ | AdamVerner/BI-PA2 | /semwork/vernead2/src/Interface/Selector.h | UTF-8 | 1,424 | 3.390625 | 3 | [] | no_license | //
// Created by vernead2 on 19.06.20.
//
#pragma once
#include <map>
#include <functional>
#include <climits>
/**
* Utility to prompt user for multiple selection.
*
* Input is sanitized. Upon invalid selection the user is re-prompted until viable option is selected.
* */
class Selector{
public:
Selector(std::ostream & out): out(out) { }
Selector(): Selector(std::cout) {}
/** Add an option prompt.
* @param id id the user will be able to select
* @param name description visible to the user
* @param callback function called upon option selection
* */
void Add(int id, const std::string & name, const std::function<void(void)> & callback );
/** Prompt the user with previously added options.
* The selected option is executed. */
void prompt(bool intro = true);
void promptCustom( const std::string & prompt);
private:
std::map<int, std::pair<std::string, const std::function<void(void)>>> options; /**< Option store */
/** Print available options to stdout */
void printPrompt(bool intro);
std::ostream & out;
};
/**
* Try to read an integer from CIN, if read fails, delete everything until newline.
* @param out[out] reference to output integer.
* @returns false on failure
* */
bool promptInteger( int & out );
/** Prompt user for integer and range verify it. */
int PromptIntegerValue( int min = INT_MIN, int max = INT_MAX);
| true |
45118a648a1497dfb6d2218c5e2d4bfcdac71e67 | C++ | blackPantherOS/FTXUI | /src/ftxui/component/event.cpp | UTF-8 | 2,414 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "ftxui/component/event.hpp"
#include <iostream>
#include "ftxui/screen/string.hpp"
namespace ftxui {
// static
Event Event::Character(const std::string& input) {
Event event;
event.input_ = input;
event.is_character_ = true;
event.character_ = to_wstring(input)[0];
return event;
}
// static
Event Event::Character(char c) {
return Character(wchar_t(c));
}
// static
Event Event::Character(wchar_t c) {
Event event;
event.input_ = {(char)c};
event.is_character_ = true;
event.character_ = c;
return event;
}
// static
Event Event::Special(const std::string& input) {
Event event;
event.input_ = std::move(input);
return event;
}
// --- Arrow ---
const Event Event::ArrowLeft = Event::Special("\x1B[D");
const Event Event::ArrowRight = Event::Special("\x1B[C");
const Event Event::ArrowUp = Event::Special("\x1B[A");
const Event Event::ArrowDown = Event::Special("\x1B[B");
const Event Event::Backspace = Event::Special({127});
const Event Event::Delete = Event::Special("\x1B[3~");
const Event Event::Escape = Event::Special("\x1B");
#if defined(_WIN32)
const Event Event::Return = Event::Special({13});
#else
const Event Event::Return = Event::Special({10});
#endif
const Event Event::Tab = Event::Special({9});
const Event Event::TabReverse = Event::Special({27, 91, 90});
const Event Event::F1 = Event::Special("\x1B[OP");
const Event Event::F2 = Event::Special("\x1B[OQ");
const Event Event::F3 = Event::Special("\x1B[OR");
const Event Event::F4 = Event::Special("\x1B[OS");
const Event Event::F5 = Event::Special("\x1B[15~");
const Event Event::F6 = Event::Special("\x1B[17~");
const Event Event::F7 = Event::Special("\x1B[18~");
const Event Event::F8 = Event::Special("\x1B[19~");
const Event Event::F9 = Event::Special("\x1B[20~");
const Event Event::F10 = Event::Special("\x1B[21~");
const Event Event::F11 = Event::Special("\x1B[21~"); // Doesn't exist
const Event Event::F12 = Event::Special("\x1B[24~");
const Event Event::Home = Event::Special({27, 91, 72});
const Event Event::End = Event::Special({27, 91, 70});
const Event Event::PageUp = Event::Special({27, 91, 53, 126});
const Event Event::PageDown = Event::Special({27, 91, 54, 126});
Event Event::Custom = Event::Special({0});
} // namespace ftxui
// Copyright 2020 Arthur Sonzogni. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
| true |
abe8412e58f1e4a07509d6ac74a3cd3533c24633 | C++ | liushengxi13689209566/Data-structures-algorithm | /tree/ 重建二叉树.cpp | UTF-8 | 1,836 | 3.859375 | 4 | [] | no_license | /*************************************************************************
> File Name: 重建二叉树.cpp
> Author: Liu Shengxi
> Mail: 13689209566@163.com
> Created Time: Thu 13 Dec 2018 12:25:39 PM CST
************************************************************************/
#include <stream>
#include <vector>
// struct TreeNode
// {
// int val;
// TreeNode *left;
// TreeNode *right;
// TreeNode(int x) : val(x), left(NULL), right(NULL){}
// };
/*题意:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回
思路:前序遍历的第一个节点就是根节点,于是我们在中序遍历中找到该节点,于是该节点就把树划分成了左子树和右子树,之后递归求解即可
*/
class Solution
{
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
auto pre_size = preorder.size();
auto in_size = inorder.size();
if (pre_size != in_size || pre_size == 0 || in_size == 0)
return nullptr;
return fun(preorder, 0, pre_size - 1, inorder, 0, in_size - 1);
}
TreeNode *fun(vector<int> &preorder, int preL, int preR, vector<int> &inorder, int inderL, int inderR)
{
if (preL > preR)
// 找完所有的节点
return nullptr;
TreeNode *root = new TreeNode(preorder[preL]);
int i = inderL;
for (; i <= inderR; i++)
{
if (inorder[i] == preorder[preL])
break;
}
int left_size = i - inderL;
int right_size = inderR - i;
root->left = fun(preorder, preL + 1, preL + left_size, inorder, inderL, i - 1);
root->right = fun(preorder, preL + left_size + 1, preR, inorder, i + 1, inderR);
return root;
}
};
| true |
8e55f8a45355fb8b6aec33d96f6dd8a697defe43 | C++ | dmriser/analysis-main | /include/database/Parameters.h | UTF-8 | 916 | 2.8125 | 3 | [] | no_license | #ifndef PARAMETERS_H
#define PARAMETERS_H
#include <string>
#include <map>
#include "ParameterMetaData.h"
#include "ParameterSet.h"
class Parameters{
public:
Parameters();
~Parameters();
protected:
ParameterMetaData metaData;
std::map<std::string, ParameterSet> parameters;
public:
ParameterSet getParameter(std::string name);
ParameterMetaData getMetaData(){ return metaData; }
std::vector<std::string> parseLine(std::string);
std::vector<std::string> getListOfParameters();
void addParameterSet(ParameterSet inputParameterSet){ parameters[inputParameterSet.getName()] = inputParameterSet; }
void loadParameters(std::string inputFilename);
void saveParameters(std::string outputFilename);
void setNumberOfFiles(int numberOfFiles){ metaData.setNumberOfFilesUsed(numberOfFiles); }
bool hasParameter(std::string name) const {
return parameters.count(name);
}
};
#endif
| true |
f06880ca48ef515654fe0ed64a55fa363229a782 | C++ | prasko/parallel-adwt | /src/sysutil.cpp | UTF-8 | 2,654 | 2.921875 | 3 | [] | no_license | /*
Copyright: (c) 2011 Matija Osrecki <matija.osrecki@fer.hr>
*/
#include <vector>
#include "sysutil.h"
void Decimator::decimate(const Signal &s, Signal &re, Signal &ro) {
for(int i = 0; i < (int)s.size(); ++i) {
if(i % 2 == 0)
re.push_back(s[i] * constant_);
else
ro.push_back(s[i] * constant_);
}
}
template <typename T>
inline T vector_access(const std::vector<T> &array, const int i) {
return (i < 0 || i >= (int)array.size() ? 0 : array[i]);
}
void PolySystem::addMember(const int offset, const double coef) {
members_.push_back(std::make_pair(offset, coef));
}
void PolySystem::process(const Signal &s, Signal &res) {
for(int i = 0; i < (int)s.size(); ++i) {
double sum = 0;
for(int j = 0; j < (int)members_.size(); ++j)
sum += members_[j].second * vector_access(s, i - members_[j].first);
res.push_back(sum * constant_);
}
}
void Multiply2::multiply(const Signal &s1, const Signal &s2, Signal &res) {
for(int i = 0; i < (int)std::min(s1.size(), s2.size()); ++i) {
res.push_back(s1[i] * s2[i] * constant_);
}
res.resize(std::max(s1.size(), s2.size()));
}
void Add2::add(const Signal &s1, const Signal &s2, const double c2, Signal &r) {
int n = s1.size(), m = s2.size(), l = std::max(n, m);
for(int i = 0; i < l; ++i) {
if(i >= n) {
r.push_back(s2[i] * constant_);
} else if(i >= m) {
r.push_back(s1[i] * constant_);
} else {
r.push_back((s1[i] + s2[i] * c2) * constant_);
}
}
}
void Sumator::init(Signal &result) {
result_ = &result;
}
void Sumator::sumSignal(const Signal &signal, const double coef) {
if(signal.size() > result_->size())
result_->resize(signal.size());
for(int i = 0; i < (int)signal.size(); ++i)
*(result_->begin() + i) += coef * signal[i];
}
void Sumator::sumSignal(const Signal &signal, const bool prefix) {
if(signal.size() > result_->size())
result_->resize(signal.size());
if(prefix) {
for(int i = 0; i < (int)signal.size(); ++i) {
*(result_->begin() + i) += signal[i];
}
} else {
for(int i = 0; i < (int)signal.size(); ++i) {
*(result_->begin() + i) -= signal[i];
}
}
}
void Sumator::sumMultiply(const Signal &s1, const Signal &s2, bool prefix) {
if(s1.size() > result_->size() || s2.size() > result_->size())
result_->resize(std::max(s1.size(), s2.size()));
if(prefix) {
for(int i = 0; i < (int)std::min(s1.size(), s2.size()); ++i) {
*(result_->begin() + i) += s1[i] * s2[i];
}
} else {
for(int i = 0; i < (int)std::min(s1.size(), s2.size()); ++i) {
*(result_->begin() + i) -= s1[i] * s2[i];
}
}
}
| true |
4a82b5a00b10f29b1c6ca936af4c8387910ba75c | C++ | junjiek/OJcoding | /leetcode/stack/valid-parentheses.cpp | UTF-8 | 738 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <unordered_map>
using namespace std;
class Solution {
unordered_map<char, char> m;
public:
Solution() {
m[']'] = '[';
m[')'] = '(';
m['}'] = '{';
}
bool isValid(string s) {
std::stack<char> st;
for (int i = 0; i < (int)s.size(); i++) {
if (m.find(s[i]) == m.end()) {
st.push(s[i]);
} else {
if (st.empty() || st.top() != m[s[i]])
return false;
st.pop();
}
}
return st.empty();
}
};
int main() {
Solution s;
cout << s.isValid("{");
return 0;
} | true |
bb1393db49f0a6a35015ea8a97a39eab3115b069 | C++ | mdiazXV/CPP | /Project 4/Project 4/jobStack.h | UTF-8 | 505 | 2.875 | 3 | [] | no_license | #pragma once
#include <iostream>
struct job {
char jobType;
int processingTime;
int typeNumber;
int jobNumber;
int arrivalTime;
int waitTime = 0;
};
class jobStack
{
private:
job jobSet[5000];
int jobCount = 0;
public:
jobStack();
void push(job inputJob);
job pop();
bool isEmpty();
bool isFull();
void print();
int peekArrivalTime();
void quickSort(int low, int high);
void swap(job* a, job* b);
int partition(int low, int high);
int getCount() { return jobCount; }
~jobStack();
};
| true |
66ac6ab17e01d2ae8488d34840e0b4bb9b23760d | C++ | machadoprx/soq_sec | /socket_common.cpp | UTF-8 | 2,255 | 2.53125 | 3 | [] | no_license | #include "socket_common.h"
int make_soqueto(soqueto *res, enum socket_type type, const char* address, const uint16_t port) {
strcpy((char*)res->address, address);
res->type = type;
res->port = port;
res->socket_desc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (res->socket_desc < 0) {
return SOCKET;
}
res->channel.sin_family = AF_INET;
res->channel.sin_port = htons(port);
if (inet_aton(address, &res->channel.sin_addr) < 0) {
return CONVERSION;
}
if (type == SERVER) {
int on = 1;
setsockopt(res->socket_desc, SOL_SOCKET, SO_REUSEADDR, (char*) &on, sizeof(int));
if (bind(res->socket_desc, (struct sockaddr *) &res->channel, sizeof(res->channel)) < 0) {
return BIND;
}
}
return OK;
}
int send_wait(int sock, uint8_t *data, int len, int sleep_time, int tries) {
int success = -1;
for (int t = 0; t < tries; t++) {
success = send(sock, data, len, 0);
if (success < 0) {
usleep(sleep_time);
}
else if(success > 0) break;
}
return success;
}
int recv_wait(int sock, uint8_t *data, int len, int sleep_time, int tries) {
int success = -1;
for (int t = 0; t < tries; t++) {
success = recv(sock, data, len, 0);
if (success < 0) {
usleep(sleep_time);
}
else if(success > 0) break;
}
return success;
}
void catch_alarm (int sig) {
kill(0, SIGTERM);
}
int get_command(const char* command) {
if (strcmp(command, "/connect") == 0) {
return CON_SERVER;
}
else if (strcmp(command, "/quit") == 0) {
return QUIT;
}
else if (strcmp(command, "/ping") == 0) {
return PING;
}
else if (strcmp(command, "/join") == 0) {
return JOIN;
}
else if (strcmp(command, "/nickname") == 0) {
return NICKNAME;
}
else if (strcmp(command, "/kick") == 0) {
return KICK;
}
else if (strcmp(command, "/mute") == 0) {
return MUTE;
}
else if (strcmp(command, "/unmute") == 0) {
return UNMUTE;
}
else if (strcmp(command, "/whois") == 0) {
return WHOIS;
}
else {
return NOT_FOUND;
}
} | true |
824bd8d6bfee29667ba6bc96fc85fde962ebdd49 | C++ | shubarinv/3_Course_AR_CourseWork | /window.hpp | UTF-8 | 3,675 | 2.90625 | 3 | [] | no_license |
#ifndef CGLABS__WINDOW_HPP_
#define CGLABS__WINDOW_HPP_
#include "functions.hpp"
class Window {
private:
GLFWwindow *window= nullptr; ///< reference to glfw window
glm::vec2 windowSize{};
public:
/**
* @brief returns window size
* @return vec2<int>
*/
[[maybe_unused]] [[nodiscard]] const glm::vec2 &getWindowSize() const {
return windowSize;
}
/**
* @brief returns reference to glfwWindow
* @return GLFWwindow *
*/
[[nodiscard]] GLFWwindow *getGLFWWindow() const {
return window;
}
/**
* @brief init for window class
* @param size vec2<int>window size
*/
explicit Window(glm::vec2 size) {
windowSize = size;
// GLFW lib init
glfwSetErrorCallback(glfwErrorHandler);
if (!glfwInit()) {
LOG_S(FATAL) << "GLFW INIT - FAIL";
throw std::runtime_error("Failed to init glfw");
}
LOG_S(INFO) << "GLFW init - OK";
if (isMac()) {
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
LOG_S(INFO) << "System: MacOS";
}
glfwWindowHint(GLFW_FLOATING, GL_TRUE);
glfwWindowHint(GLFW_FOCUS_ON_SHOW, GL_TRUE);
// GLFW Window creation
bruteforceGLVersion();
glfwMakeContextCurrent(window);
// tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (window == nullptr) {
LOG_S(FATAL) << "GLFW was unable to create window";
glfwTerminate();
}
// GLAD lib init
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
LOG_S(FATAL) << "GLAD init Failed";
}
GLint maxShaderTextures;
GLint maxTotalTextures;
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxShaderTextures);
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTotalTextures);
glEnable(GL_MULTISAMPLE);
LOG_S(INFO) << "Status: Using OpenGL v" << glGetString(GL_VERSION);
LOG_S(INFO) << "Renderer: " << glGetString(GL_RENDERER); /* get renderer string */
LOG_S(INFO) << "Number of textures that can be accessed by the fragment shader: " << maxShaderTextures;
LOG_S(INFO) << "Total number of textures that can be used " << maxTotalTextures;
LOG_S(INFO) << "Init DONE!";
}
static void glfwErrorHandler(int error, const char *message) {
if (error != 65543)
LOG_S(ERROR) << "GLFW error: " << error << " " << message;
}
~Window() {
glfwDestroyWindow(window);
LOG_S(INFO) << "GLFW window destroyed";
LOG_S(INFO) << "Window(" << this << ") destroyed";
}
[[maybe_unused]] void updateFpsCounter() {
static double previous_seconds = glfwGetTime();
static int frame_count;
double current_seconds = glfwGetTime();
double elapsed_seconds = current_seconds - previous_seconds;
if (elapsed_seconds > 0.25) {
previous_seconds = current_seconds;
double fps = (double)frame_count / elapsed_seconds;
std::string tmp = "Marcusessssss courseWork @ fps: " + std::to_string(fps);
glfwSetWindowTitle(window, tmp.c_str());
frame_count = 0;
}
frame_count++;
}
private:
/**
* @brief this function attempts to load latest version of OpenGL
*/
void bruteforceGLVersion() {
LOG_S(INFO)<<"Getting latest OpenGL";
for (int major = 4; major > 2; major--) {
for (int minor = 9; minor > 0; minor--) {
if (major == 3 & minor == 1) { return; }
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
std::string tmp = "Trying OpenGL v" + std::to_string(major) + "." + std::to_string(minor);
window = glfwCreateWindow(windowSize.x, windowSize.y, "UNSET", nullptr, nullptr);
if (window == nullptr) {
LOG_S(INFO) << tmp << " - FAIL";
} else {
LOG_S(INFO) << tmp << " - OK";
return;
}
}
}
}
};
#endif//CGLABS__WINDOW_HPP_ | true |
2b0f58c8e9ccd78c1f3e1357f23e9e9c88fd5eea | C++ | changsongzhu/leetcode | /C++/seq_num/407_h.cpp | UTF-8 | 1,953 | 3.53125 | 4 | [] | no_license | /**
407[H]. Trapping Water II
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map:
[
[1,4,3,1,3,2],
[3,2,1,3,2,4],
[2,3,3,2,3,1]
]
Return 4.
The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
**/
class Solution {
public:
int trapRainWater(vector<vector<int>>& heightMap) {
if(heightMap.size()<3||heightMap[0].size()<3) return 0;
int m= heightMap.size(), n= heightMap[0].size();
priority_queue< pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;
vector<vector<bool> > visited(m, vector<bool>(n, false));
int res = 0, mx = INT_MIN;
vector<vector<int> > dirs = {{-1,0},{1,0},{0,-1},{0,1}};
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0||j==0||i==m-1||j==n-1)
{
q.push({heightMap[i][j], i*n+j});
visited[i][j] = true;
}
}
}
while(!q.empty())
{
auto t = q.top();q.pop();
int h = t.first, r= t.second/n, c = t.second%n;
mx = max(h, mx);
for(int i=0;i<dirs.size();i++)
{
int x = r+dirs[i][0], y=c+dirs[i][1];
if(x<0||x>=m||y<0||y>=n||visited[x][y]) continue;
visited[x][y]=true;
if(heightMap[x][y] < mx) res +=mx-heightMap[x][y];
q.push({heightMap[x][y], x*n+y});
}
}
return res;
}
};
| true |
3219b5dc84708a42a675b37b8a67b7082747ac01 | C++ | RobertBendun/egzamin-algebra | /polynomials_modulo.cc | UTF-8 | 5,199 | 3.28125 | 3 | [] | no_license | #include <algorithm>
#include <charconv>
#include <cstring>
#include <deque>
#include <iostream>
#include <iterator>
#include <memory_resource>
#include <memory>
#include <sstream>
#include <tuple>
#include <utility>
#include <vector>
auto modulo_inverse(int a, int n)
{
int t = 0, nt = 1;
int r = n, nr = a;
while (nr != 0) {
uint q = r / nr;
uint m = r - q * nr;
t = std::exchange(nt, t - q * nt);
r = std::exchange(nr, r - q * nr);
}
return
r > 1 ? 0 :
t < 0 ? t + n : t;
}
inline uint positive_modulo(int i, int n) {
return (i % n + n) % n;
}
struct Z_Mod
{
uint v = 0;
static uint base;
constexpr Z_Mod() noexcept = default;
constexpr Z_Mod(uint v) noexcept : v(v) {}
constexpr Z_Mod(Z_Mod const&) noexcept = default;
constexpr Z_Mod(Z_Mod &&) noexcept = default;
auto operator=(Z_Mod const&) -> Z_Mod& = default;
auto operator=(Z_Mod &&) -> Z_Mod& = default;
auto operator+(Z_Mod v) const { return *this + v.v; }
auto operator-(Z_Mod v) const { return *this - v.v; }
auto operator*(Z_Mod v) const { return *this * v.v; }
auto operator/(Z_Mod v) const { return *this / v.v; }
auto operator+(uint b) const -> Z_Mod { return (v + b) % base; }
auto operator-(uint b) const -> Z_Mod { return positive_modulo(v - b, base); }
auto operator*(uint b) const -> Z_Mod { return (v * b) % base; }
auto operator/(uint b) const -> Z_Mod { return (modulo_inverse(b, base) * v) % base; }
auto operator==(Z_Mod v) const -> bool { return *this == v.v; }
auto operator!=(Z_Mod v) const -> bool { return (*this != v.v); }
auto operator==(uint b) const -> bool { return v % base == b % base; }
auto operator!=(uint b) const -> bool { return v % base != b % base; }
};
auto operator<<(std::ostream &os, Z_Mod const& v) -> decltype(auto)
{
return os << (v.v % Z_Mod::base);
}
uint Z_Mod::base;
using Polynomial = std::deque<Z_Mod>;
auto simplify(Polynomial poly) -> Polynomial
{
while (!poly.empty() && poly.front() == 0)
poly.pop_front();
return poly;
}
auto operator<<(std::ostream& os, Polynomial const& poly) -> decltype(auto)
{
if (poly.size() == 0)
return os << "[ 0 ]";
os << "[ ";
for (auto x : poly)
os << x << ' ';
return os << ']';
}
auto operator+(Polynomial const& lhs, Polynomial const& rhs) -> Polynomial
{
Polynomial result;
auto lhs_begin = std::crbegin(lhs);
auto rhs_begin = std::crbegin(rhs);
auto const lhs_end = std::crend(lhs);
auto const rhs_end = std::crend(rhs);
for (; lhs_begin != lhs_end && rhs_begin != rhs_end; ++lhs_begin, ++rhs_begin)
result.push_front(*lhs_begin + *rhs_begin);
for (; lhs_begin != lhs_end; ++lhs_begin)
result.push_front(*lhs_begin);
for (; rhs_begin != rhs_end; ++rhs_begin)
result.push_front(*rhs_begin);
return simplify(result);
}
auto operator-(Polynomial const& lhs, Polynomial const& rhs) -> Polynomial
{
Polynomial result;
auto lhs_begin = std::crbegin(lhs);
auto rhs_begin = std::crbegin(rhs);
auto const lhs_end = std::crend(lhs);
auto const rhs_end = std::crend(rhs);
for (; lhs_begin != lhs_end && rhs_begin != rhs_end; ++lhs_begin, ++rhs_begin)
result.push_front(*lhs_begin - *rhs_begin);
for (; lhs_begin != lhs_end; ++lhs_begin)
result.push_front(*lhs_begin);
for (; rhs_begin != rhs_end; ++rhs_begin)
result.push_front(*rhs_begin);
return simplify(result);
}
auto operator*(Polynomial const& a, Polynomial const& b)
{
Polynomial result;
result.resize(a.size() + b.size() - 1);
for (uint i = 0; i < a.size(); ++i)
for (uint j = 0; j < b.size(); ++j)
result[i + j] = result[i + j] + a[i] * b[j];
return simplify(result);
}
auto operator==(Polynomial const& poly, typename Polynomial::value_type value)
{
switch (auto p = simplify(poly); p.size()) {
case 0: return value == 0;
case 1: return value == p.front();
default: return false;
}
}
auto operator!=(Polynomial const& poly, typename Polynomial::value_type value)
{
return !(poly == value);
}
auto operator/(Polynomial const& n, Polynomial const& d) -> std::pair<Polynomial, Polynomial>
{
auto q = Polynomial{ 0 };
auto r = simplify(n);
auto c = d.front();
while (r != 0 && r.size() >= d.size()) {
auto t = Polynomial { r.front() / c };
for (uint i = 0; i < r.size() - d.size(); ++i)
t.push_back(0);
q = simplify(std::move(q) + t);
r = simplify(r - d * t);
}
return { q, r };
}
auto main() -> int
{
std::cout << "Base: ";
(std::cin >> Z_Mod::base).get();
Polynomial poly[2];
for (size_t i = 0; i < 2; ++i) {
std::cout << (i + 1) << ": ";
std::string line;
std::getline(std::cin, line);
std::stringstream ss(line);
std::copy(std::istream_iterator<uint>(ss), {}, std::back_inserter(poly[i]));
}
char c;
std::cout << "Op (+, -, *, /): ";
std::cin >> c;
switch (c) {
case '+': std::cout << poly[0] << " + " << poly[1] << " = " << (poly[0] + poly[1]) << '\n'; break;
case '-': std::cout << poly[0] << " - " << poly[1] << " = " << (poly[0] - poly[1]) << '\n'; break;
case '*': std::cout << poly[0] << " * " << poly[1] << " = " << (poly[0] * poly[1]) << '\n'; break;
case '/': {
auto const [q, r] = poly[0] / poly[1];
std::cout << poly[0] << " = " << poly[1] << " * " << q << " + " << r << '\n';
}
}
}
| true |
ce65fa82359814cb5750329ff7a7f72f96773767 | C++ | Chaitanya-git/waymo-open-dataset | /waymo_open_dataset/math/polygon2d.h | UTF-8 | 5,825 | 2.90625 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-generic-cla"
] | permissive | /* Copyright 2019 The Waymo Open Dataset Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef WAYMO_OPEN_DATASET_MATH_POLYGON2D_H_
#define WAYMO_OPEN_DATASET_MATH_POLYGON2D_H_
#include <utility>
#include <vector>
#include "waymo_open_dataset/math/box2d.h"
#include "waymo_open_dataset/math/segment2d.h"
#include "waymo_open_dataset/math/vec2d.h"
namespace waymo {
namespace open_dataset {
// A class for *convex* polygons only.
//
// Used for computing intersections with other polygons only.
class Polygon2d {
public:
// Create an empty polygon.
Polygon2d() = default;
// Make sure this class remains movable and copiable.
Polygon2d(Polygon2d &&) = default;
Polygon2d(const Polygon2d &) = default;
Polygon2d &operator=(Polygon2d &&) = default;
Polygon2d &operator=(const Polygon2d &) = default;
// Create a polygon from the given box.
explicit Polygon2d(const Box2d &box) {
box.GetCornersInVectorCounterClockwise(&points_);
CHECK_EQ(points_.size(), 4);
BuildFromPoints();
}
// Create a convex polygon with the given circular array of 2d points. There
// should be at least three 2d points. 2d points must be in counter-clockwise
// order.
explicit Polygon2d(std::vector<Vec2d> points);
// Return the number of points.
int NumPoints() const { return num_points_; }
// Return the point array.
const std::vector<Vec2d> &points() const { return points_; }
// Performs a fast check to see if the two polygons are potentially
// intersecting. A false return value guarantees that there's no intersection.
bool MaybeHasIntersectionWith(const Polygon2d &other) const;
// Return the segments that make up this polygon. Each segment ii
// is between points ii -> (ii + 1) % num_points_.
Vec2d Segment(int ii) const {
DCHECK_LE(0, ii);
DCHECK_LT(ii, num_points_);
return points_[Next(ii)] - points_[ii];
}
// Return the index of the previous (or the next) point of the polygon.
int Prev(int index) const {
return index == 0 ? num_points_ - 1 : (index - 1);
}
int Next(int index) const {
return index == num_points_ - 1 ? 0 : (index + 1);
}
// The corners of the axis aligned bounding box for this polygon.
Vec2d bbox_bottom_left() const { return bbox_bottom_left_; }
Vec2d bbox_top_right() const { return bbox_top_right_; }
double Area() const { return AreaNoValidityCheck(); }
// Like Area(), but performs no check on the validity of the polygon/area. May
// return a negative area.
double AreaNoValidityCheck() const;
// Return true if the given point is inside the polygon. The implementation
// uses a check on how many times a ray originating from (x,y) intersects the
// polygon, and works with both convex and concave polygons.
bool PointInside(Vec2d p) const;
bool PointInside(double x, double y) const {
return PointInside(Vec2d(x, y));
}
// Returns the area of the intersection between this polygon and the given
// polygon.
double ComputeIntersectionArea(const Polygon2d &other) const;
void AxisAlignedBoundingBox(Vec2d *bottom_left, Vec2d *top_right) const;
// Checks whether the given set of points form a convex hull, and if yes
// return whether they are in clockwise or counter-clockwise order. It does
// not check whether the polygon is degenerate, has repeated points.
static bool IsConvexHull(const std::vector<Vec2d> &points,
bool *counter_clockwise = nullptr);
// Slides the polygon by the given (dx, dy) vector.
void ShiftCenter(Vec2d offset);
// Rotates the polygon around the given center, then shift by the given
// offset.
void Transform(double angle, Vec2d center, Vec2d offset);
// Debugging function for printing the polygon's vertices to a string.
static std::string PrintPointsToString(const std::vector<Vec2d> &points,
bool full_precision);
std::string DebugString() const;
// Epsilon used in this file to avoid double precision problem
// when we compare two numbers.
static constexpr double kEpsilon = 1e-10;
private:
// Construct other useful data, given the points_ vector is filled.
void BuildFromPoints();
// Return all vectices of the intersection between this polygon and the given
// one, which should form a convex polygon. Both this polygon and the given
// polygon must be convex ones. This function is used to either compute the
// intersection polygon or the intersection area.
std::vector<Vec2d> ComputeIntersectionVertices(const Polygon2d &other) const;
// The corners of the axis-aligned bounding box for this polygon.
Vec2d bbox_bottom_left_, bbox_top_right_;
// The polygon is parameterized by this circular array of 2d points (corners).
// The points are in counter-clockwise order.
int num_points_ = 0;
std::vector<Vec2d> points_;
};
namespace internal {
// Compute the intersection of two segments. Returns true if the segments
// intersect or coincide.
bool ExactSegmentIntersection(const Segment2d &s1, const Segment2d &s2,
Vec2d *intersection);
} // namespace internal
} // namespace open_dataset
} // namespace waymo
#endif // WAYMO_OPEN_DATASET_MATH_POLYGON2D_H_
| true |
89cce25822aa075a02b1f68767249393a9d711bd | C++ | robercano/cornerstone | /Source/Framework/Core/GameObjectOwner.hpp | UTF-8 | 892 | 2.8125 | 3 | [
"MIT"
] | permissive | //
// GameObjectOwner.hpp
//
// @author Roberto Cano
//
#pragma once
#include "Types.hpp"
namespace Framework
{
using namespace Types;
namespace Core
{
class GameObjectOwner
{
public:
GameObjectOwner() = default;
virtual ~GameObjectOwner() = default;
bool hasOwner() const;
const GameObject& getOwner() const;
GameObject& getOwner();
template<typename T>
const T& getOwner() const
{
static_assert(std::is_base_of<GameObject, T>::value, "Object must inherit from GameObject");
return dynamic_cast<const T&>(getOwner());
}
template<typename T>
T& getOwner()
{
static_assert(std::is_base_of<GameObject, T>::value, "Object must inherit from GameObject");
return dynamic_cast<T&>(getOwner());
}
virtual void _setOwner(Types::GameObject::WeakPtrType gameObject);
private:
Types::GameObject::WeakPtrType _gameObject;
};
}
} | true |
2c6da590a6fcf6a5440942b945dc32db34645a86 | C++ | afeinland/fuzzy-adventure | /polymorph.cpp | UTF-8 | 887 | 2.890625 | 3 | [] | no_license | // Course: CS 100 <Winter 2014>
//
// First Name: Alex
// Last Name: Feinland
// CS Login: afein001
// UCR email: afein001@ucr.edu
// SID: 861056485
//
// Lecture Section: <001>
// Lab Section: <021>
// TA: Bryan Marsh
//
// Assignment <HW5>
//
// I hereby certify that the code in this file
// is ENTIRELY my own original work.
#include <vector>
#include "Monster.h"
#include "Zombie.h"
#include "Ninja.h"
#include "Yeti.h"
using std::cout;
using std::endl;
using std::vector;
void addMonsters(vector<Monster*> & m)
{
m.push_back( new Zombie("Zafirah", 2) );
m.push_back( new Yeti("Yannis", 9) );
m.push_back( new Ninja("Noburu", 23) );
}
void monstersAttack(vector<Monster*> & m)
{
for(unsigned i = 0; i < m.size(); ++i)
m.at(i) -> attack();
}
int main()
{
vector<Monster*> monsters;
addMonsters(monsters);
monstersAttack(monsters);
return 0;
}
| true |
c74a2dfc59381cb8fe69290331a52d72ae9f0d81 | C++ | Hongbaekson/OOP345_Object-oriented-programming | /OOP_Project-master/Aid Management Application/Error.cpp | UTF-8 | 1,557 | 3.0625 | 3 | [] | no_license | // Name Hongback Son Date 19/09/22 Reason
/////////////////////////////////////////////////////////////////
#include "Error.h"
#include <iostream>
#include <string>
#include <cstring>
using namespace aid;
namespace aid {
Error::Error(const char* errorMessage) {
if (errorMessage == nullptr)
{
addMessage = nullptr;
}
else
{
char * c_str = nullptr;
c_str = new char[strlen(errorMessage) + 1];
strncpy(c_str, errorMessage, strlen(errorMessage));
this->addMessage = c_str;
this->addMessage[strlen(errorMessage)] = '\0';
if (this->addMessage[0] == '\0')
{
clear();
}
}
}
Error::~Error() {
clear();
}
void Error::clear() {
delete[] addMessage;
addMessage = nullptr;
}
bool Error::isClear() const {
return addMessage == nullptr;
}
void Error::message(const char* str) {
clear();
if (str != nullptr)
{
addMessage = new char[strlen(str) + 1];
strncpy(addMessage, str, strlen(str));
addMessage[strlen(str)] = '\0';
if (this->addMessage[0] == '\0')
{
clear();
}
}
else if (str == nullptr || str[0] == '\0')
{
clear();
}
}
const char* Error::message()const {
if (!isClear())
{
return this->addMessage;
}
else
{
return nullptr;
}
}
std::ostream& operator<<(std::ostream& out, const Error& errorMessage) {
if (!errorMessage.isClear()) {
return out << errorMessage.message();
}
else {
return out;
}
}
}
| true |
0df431f87eccba7bcc205c444b64f70956d9dbc0 | C++ | ashrwin/Spoj-Solutions | /solutions/MusicalChairs.cpp | UTF-8 | 344 | 2.65625 | 3 | [] | no_license | /**/
#include<iostream>
using namespace std;
inline int musicdp( int n , int d )
{
int ret = 0;
for ( int i = 2; i <= n; ++i )
ret= ( ret + d ) % i;
return ret+1 ;
}
int main()
{
int n , d;
while ( true )
{
scanf( "%d%d" , &n , &d );
if ( !n && !d ) return 0;
printf( "\n%d %d %d" , n , d , musicdp( n , d ) );
}
return 1;
}
| true |
a568ac53ae32fa46354e9521bd6c30df730b3ce2 | C++ | bcbro2021/consoleEdit | /main.cpp | UTF-8 | 724 | 2.671875 | 3 | [] | no_license | #include "lib.h"
using namespace std;
int main(){
//variables
bool run = true;
string result;
string text;
print(" ______ _______ _______ _______");
print("| ____|| _ | |__ __||__ __|");
print("| |____ | | | | | | | |");
print("| ____|| | | | | | | |");
print("| |____ | |_| | __| |__ | |");
print("|______||_______| |_______| |_|");
print("\n");
while(run){
text = input("Edit: ");
result += text + "\n";
if (text == "$save"){
string filename = input("file name: ");
createAndWrite(filename, result);
print("File Saved");
break;
}
else if(text == "$exit"){
print("\n");
print("Deleted Data!");
print("\n");
break;
}
}
return 0;
} | true |
8003086f8f1e17014c2bb5b7eb7bf79dd2d35969 | C++ | dlareau/cluster-counter | /Microcontroller/Microcontroller.ino | UTF-8 | 5,463 | 2.5625 | 3 | [] | no_license | /* code for max 7219 from maxim,
reduced and optimised for using more than one 7219 in a row,
______________________________________
Code History:
--------------
The original code was written for the Wiring board by:
* Nicholas Zambetti and Dave Mellis /Interaction Design Institute Ivrea /Dec 2004
* http://www.potemkin.org/uploads/Wiring/MAX7219.txt
First modification by:
* Marcus Hannerstig/ K3, malmö högskola /2006
* http://www.xlab.se | http://arduino.berlios.de
This version is by:
* tomek ness /FH-Potsdam / Feb 2007
* http://design.fh-potsdam.de/
* @acknowledgements: eric f.
-----------------------------------
General notes:
-if you are only using one max7219, then use the function maxSingle to control
the little guy ---maxSingle(register (1-8), collum (0-255))
-if you are using more than one max7219, and they all should work the same,
then use the function maxAll ---maxAll(register (1-8), collum (0-255))
-if you are using more than one max7219 and just want to change something
at one little guy, then use the function maxOne
---maxOne(Max you want to control (1== the first one), register (1-8),
column (0-255))
During initiation, be sure to send every part to every max7219 and then
upload it.
For example, if you have five max7219's, you have to send the scanLimit 5 times
before you load it-- otherwise not every max7219 will get the data. the
function maxInUse keeps track of this, just tell it how many max7219 you are
using.
*/
#include <stdio.h>
int dataIn = 4;
int load = 5;
int clock1 = 6;
int maxInUse = 1; //change this variable to set how many MAX7219's you'll use
int e = 0; // just a variable
// define max7219 registers
byte max7219_reg_noop = 0x00;
byte max7219_reg_decodeMode = 0x09;
byte max7219_reg_intensity = 0x0a;
byte max7219_reg_scanLimit = 0x0b;
byte max7219_reg_shutdown = 0x0c;
byte max7219_reg_displayTest = 0x0f;
byte disp_map[9] = {0,4,3,5,1,2,7,8,6};
// DP, LBottom, Middle, RTop, Bottom, RBottom, Top, LTop.
int constants[10] = {
0b01011111,
0b00010100,
0b01111010,
0b00111110,
0b00110101,
0b00101111,
0b01101111,
0b00010110,
0b01111111,
0b00111111
};
void putByte(byte data) {
byte i = 8;
byte mask;
while(i > 0) {
mask = 0x01 << (i - 1); // get bitmask
digitalWrite( clock1, LOW); // tick
if (data & mask){ // choose bit
digitalWrite(dataIn, HIGH);// send 1
}else{
digitalWrite(dataIn, LOW); // send 0
}
digitalWrite(clock1, HIGH); // tock
--i; // move to lesser bit
}
}
void maxSingle( byte reg, byte col) {
//maxSingle is the "easy" function to use for a single max7219
reg = disp_map[reg];
digitalWrite(load, LOW); // begin
putByte(reg); // specify register
putByte(col);//((data & 0x01) * 256) + data >> 1); // put data
digitalWrite(load, LOW); // and load da stuff
digitalWrite(load,HIGH);
}
void maxAll (byte reg, byte col) { // initialize all MAX7219's in the system
int c = 0;
digitalWrite(load, LOW); // begin
for ( c =1; c<= maxInUse; c++) {
putByte(reg); // specify register
putByte(col);//((data & 0x01) * 256) + data >> 1); // put data
}
digitalWrite(load, LOW);
digitalWrite(load,HIGH);
}
void setup () {
pinMode(dataIn, OUTPUT);
pinMode(clock1, OUTPUT);
pinMode(load, OUTPUT);
digitalWrite(13, HIGH);
//initiation of the max 7219d
maxAll(max7219_reg_scanLimit, 0x07);
maxAll(max7219_reg_decodeMode, 0x00); // using an led matrix (not digits)
maxAll(max7219_reg_shutdown, 0x01); // not in shutdown mode
maxAll(max7219_reg_displayTest, 0x00); // no display test
for (e=1; e<=8; e++) { // empty registers, turn all LEDs off
maxAll(e,0);
}
maxAll(max7219_reg_intensity, 0x0f & 0x0f); // the first 0x0f is the value you can set
// range: 0x00 to 0x0f
}
byte char_val(char in_char){
switch(in_char) {
case 'A':
return 0x77;
case 'B':
return 0x6D;
case 'C':
return 0x4B;
case 'D':
return 0x7C;
case 'E':
return 0x6B;
case 'F':
return 0x63;
case 'G':
return 0x3F;
case 'H':
return 0x75;
case 'I':
return 0x04;
case 'J':
return 0x5C;
case 'L':
return 0x49;
case 'N':
return 0x64;
case 'O':
return 0x5F;
case 'P':
return 0x73;
case 'R':
return 0x60;
case 'S':
return 0x2F;
case 'T':
return 0x69;
case 'U':
return 0x5D;
case 'Y':
return 0x35;
default:
return 0b00000000;
}
}
void disp_word(char in_word[]){
for(int i = 0; i < 8; i++){
maxSingle(8-i, char_val(in_word[i]));
}
}
void disp_num(int num, int start_seg){
if(start_seg == 9){
return;
}
if(start_seg == 1 && num == 0){
maxSingle(start_seg, constants[0]);
}
else if(num == 0){
maxSingle(start_seg, 0b00000000);
} else{
maxSingle(start_seg, constants[num%10]);
}
disp_num(num/10, start_seg+1);
}
void loop () {
//FILE* file = fopen ("/sketch/temp.txt", "r");
FILE *file = popen("curl http://jlareau.club.cc.cmu.edu:8000/query", "r");
int i = 0;
fscanf (file, "%d", &i);
fclose (file);
if(i % 1000 == 989){
disp_word(" CLUSTER");
} else if (i % 1000 == 990){
disp_word(" COUNTER");
} else {
disp_num(i, 1);
}
delay(200);
}
| true |
36c54b46fef4ca634ff8e800fd9f767d8e6859f1 | C++ | roba1234/hsm | /HSM/Action.cpp | UTF-8 | 2,446 | 2.984375 | 3 | [] | no_license | #include "pch.h"
#include "Action.h"
Action* Action::GetLast()
{
if (m_pNext == nullptr)
return this;
// Find the end iteratively
Action* pCurr = this;
Action* pNext = m_pNext;
while (pNext)
{
pCurr = pNext;
pNext = pNext->m_pNext;
}
return pCurr;
}
void Action::DeleteList()
{
if (m_pNext == nullptr)
{
m_pNext->DeleteList();
}
delete this;
}
void Action::Act()
{
std::cout << "Data: " << m_nData << std::endl;
}
bool Action::CanInterrupt()
{
return false;
}
bool Action::CanDoBoth(const Action* pOther) const
{
return false;
}
bool Action::IsComplete()
{
return true;
}
#if 0
ActionManager::ActionManager()
: m_nActivePriority(0)
, m_pActionQueue(nullptr)
, m_pActiveAction(nullptr)
{
}
void ActionManager::ScheduleAction(Action* pNewAction)
{
Action** pPrev = &m_pActionQueue;
Action* pNext = m_pActionQueue;
while (pNext != nullptr)
{
// if we found a lower priority, we go here.
//
// Note that this will be much quicker with a >=, but
// it means in the absence of priority ordering the queue
// defaults to FIFO, which isn't very useful.
if (pNewAction->m_nPriority > pNext->m_nPriority)
{
break;
}
// When we get here, we have either found the location mid-list
// or reached the end of the list, so add it on.
pPrev = &pNext->m_pNext;
pNext = pNext->m_pNext;
}
}
void ActionManager::Execute()
{
// check if we need to interrupt the currently active actions
CheckInterrupts();
AddAllToActive();
RunActive();
}
void ActionManager::CheckInterrupts()
{
Action** previous = &m_pActionQueue;
Action* next = m_pActionQueue;
while (next != nullptr)
{
// If we drop below the active priority, give up
if (next->m_nPriority < m_nActivePriority)
{
break;
}
// Otherwise we're beating for priority, so check if we
// need to interrupt.
if (next->CanInterrupt())
{
// So we have to interrupt. Initially just replace the
// active set.
// Delete the previous active list
if (m_pActiveAction != nullptr) m_pActiveAction->DeleteList();
// Add the new one
m_pActiveAction = next;
m_nActivePriority = m_pActiveAction->m_nPriority;
// Rewire the queue to extract our action
*previous = next->m_pNext;
next->m_pNext = nullptr;
// And stop looking (the highest priority interrupter wins).
break;
}
// Check the next one
previous = &next->m_pNext;
next = next->m_pNext;
}
}
#endif
| true |
8472e70b742bdbf64e5673bc278d77e07df3b724 | C++ | bMorgan01/Javatocpp | /D2_power.cpp | UTF-8 | 547 | 3.984375 | 4 | [] | no_license | #include <iostream>
int power(int n, int e) {
if (n < 0 || e < 0) return -1;
else if (e > 0) return n * power(n, e - 1);
else return 1;
}
int main() {
int n, e;
std::cout << "Enter number: ";
std::cin >> n;
std::cout << "Enter exponent: ";
std::cin >> e;
std::cout << "Ans: " << power(n, e) << std::endl;
return 0;
/*
* Example:
*
* 5^4
*
* 5 * 5^3 =
* 5 * 5 * 5^2 =
* 5 * 5 * 5 * 5^1 =
* 5 * 5 * 5 * 5 * 5^0 = 625
*/
}
| true |
d9b1f5fdf2cc00d085518421d0e936d97e6206c4 | C++ | shiv-jetwal90/Coding-Practice | /Arrays/sign_of_the_product.cpp | UTF-8 | 716 | 3.140625 | 3 | [] | no_license | ## https://www.geeksforgeeks.org/array-product-c-using-stl/
class Solution {
public:
int arraySign(vector<int>& v) {
int c=0;
for(int i=0;i<v.size();i++)
{
if(v[i]==0)
return 0;
if(v[i]<0)
c++;
}
if(c%2==0)
return 1;
else
return -1;
// long long ans = accumulate(v.begin(), v.end(), 1, multiplies<int>());
// int multi = 1;
// for (auto& e: v)
// multi *= e;
// if(ans>0)
// return 1;
// else if(ans<0)
// return -1;
// else
// return 0;
}
};
| true |
86cb002ea15f22386345f3e562867dc56213f3e2 | C++ | giranath/epic-tv-fighting | /src/gamestates/VictoryState.h | UTF-8 | 1,342 | 2.90625 | 3 | [] | no_license | /**
* FICHIER: VictoryState.h
* PROJET: TP3
* AUTHEUR: Nathan Giraldeau
*
* DESCRIPTION;
* État dans lequel on dévoile le vainqueur du combat
*/
#ifndef __TP3__VictoryState__
#define __TP3__VictoryState__
#include "GameState.h"
#include "Player.h"
#include "Scene.h"
#include "Game.h"
namespace beat {
class VictoryState : public GameState {
public:
VictoryState(Game &game, Player* players[2], int victorious, Scene &scene);
virtual void onStart();
/**
* Appelée à chaque frame
*/
virtual void onUpdate(unsigned int delta);
/**
* Appelée à l'affichage de l'état
*/
virtual void onDraw(sf::RenderTarget &target);
/**
* Appelé à la reception d'évènements
*/
virtual void onEvent(sf::Event const& event);
/**
* Appelée à la fermeture
*/
virtual void onClose();
private:
Player* _players[2];
Scene &_scene;
AnimationSequence _sequences[2];
// L'index du vainqueur
int _victoriousIndex;
sf::Font _victoryFont;
sf::Text _victoryText;
sf::Sound _winner;
sf::Sound _wins;
bool _sayWins;
bool _sayName;
};
}
#endif
| true |
af04a2f70b31fd16bbe708e3f1d9644c772940d0 | C++ | amorilio/TestSources | /LRUCache.h | UTF-8 | 1,289 | 2.984375 | 3 | [] | no_license | #pragma once
class LRUCache
{
public:
LRUCache(void);
~LRUCache(void);
// A Queue Node (Queue is implemented using Doubly Linked List)
typedef struct QNode
{
struct QNode *prev, *next;
unsigned pageNumber; // the page number stored in this QNode
} QNode;
// A Queue (A FIFO collection of Queue Nodes)
typedef struct Queue
{
unsigned count; // Number of filled frames
unsigned numberOfFrames; // total number of frames
QNode *front, *rear;
} Queue;
// A hash (Collection of pointers to Queue Nodes)
typedef struct Hash
{
int capacity; // how many pages can be there
QNode* *array; // an array of queue nodes
} Hash;
QNode* newQNode( unsigned pageNumber );
Queue* createQueue( int numberOfFrames );
Hash* createHash( int capacity );
int isQueueFull( Queue* queue );
int isQueueEmpty( Queue* queue );
void deQueue( Queue* queue );
void enQueue( Queue* queue, Hash* hash, unsigned pageNumber );
void ReferencePage( Queue* queue, Hash* hash, unsigned pageNumber );
};
// Driver program to test above functions
int TestLRUCache();
void TestLRUCacheSTL(); | true |
5798d0ddc18dc5596dcbbffa7031c4b499d4e59c | C++ | PA2FA17/pa2fa17-helloojj | /assignments/3/todo_item.cpp | UTF-8 | 1,796 | 3.875 | 4 | [] | no_license | /*
* Name : todo_item.cpp
* Author : Luke Sathrum
* Description : Implementation file for TodoItem class
*/
#include "todo_item.h"
TodoItem::TodoItem(string description, int priority, bool completed)
: description_(description),
priority_(priority),
completed_(completed) {
}
TodoItem::~TodoItem() {
}
string TodoItem::description() {
return description_;
}
int TodoItem::priority() {
return priority_;
}
bool TodoItem::completed() {
return completed_;
}
void TodoItem::set_description(string description) {
description_ = description;
}
void TodoItem::set_priority(int priority) {
if (priority < 1 || priority > 5) {
priority_ = 5;
} else {
priority_ = priority;
}
}
void TodoItem::set_completed(bool completed) {
completed_ = completed;
}
string TodoItem::ToFile() {
stringstream ss;
ss << Scrub(description_) << "@" << priority_ << "@" << completed_;
return ss.str();
}
ostream& operator <<(ostream &out, const TodoItem &todo_item) {
out.setf(std::ios::left);
// Place the TodoItem values on the ostream
out << setw(50) << todo_item.description_ << " "
<< todo_item.priority_ << " ";
// Handle the fact that booleans output as 1s and 0s
if (todo_item.completed_)
out << "Yes";
else
out << "No";
// Return the ostream object to allow for chaining of <<
return out;
}
/*
* Takes a string and returns a copy of that string where all instances of the @
* symbol has been replaced by backticks (`)
* @param string to_scrub - The string to change @ -> `
* @return string - A string where @ have been converted to `
*/
string TodoItem::Scrub(string to_scrub) {
for (unsigned int i = 0; i < to_scrub.length(); i++)
if (to_scrub.at(i) == '@')
to_scrub.at(i) = '`';
return to_scrub;
}
| true |
ae6a7202003e0fc0682809a6e1552d8b4a013d09 | C++ | lvshq/Image-Stitching | /Image-Stitching/image-stitching.cpp | UTF-8 | 10,183 | 2.765625 | 3 | [] | no_license | #include <opencv2/opencv.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/stitching/detail/blenders.hpp>
#include <algorithm>
using namespace cv;
using namespace std;
// Functions prototypes
void Homography(const vector<Mat> &Images, vector<Mat> &transforms);
void FindOutputLimits(const vector<Mat> &Images, vector<Mat> &transforms, int &xMin, int &xMax, int &yMin, int &yMax);
void warpMasks(const vector<Mat> &Images, vector<Mat> &masks_warped, const vector<Mat> &transforms, const Mat &panorama);
void warpImages(const vector<Mat> &Images, const vector<Mat> &masks_warped, const vector<Mat> &transforms, Mat &panorama);
void BlendImages(const vector<Mat> &Images, Mat &pano_feather, Mat &pano_multiband, const vector<Mat> &masks_warped, const vector<Mat> &transforms);
int main()
{
// Initialize OpenCV nonfree module
initModule_nonfree();
// Set the dir/name of each image
const int NUM_IMAGES = 6;
const string IMG_NAMES[] = { "img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg", "img5.jpg", "img6.jpg" };
//uncomment for reordered test
//const string IMG_NAMES[] = { "img1.jpg", "img6.jpg", "img5.jpg", "img2.jpg", "img3.jpg", "img4.jpg" };
// Load the images
vector<Mat> Images;
for (int i = 0; i < NUM_IMAGES; i++)
{
Images.push_back(imread(IMG_NAMES[i]));
//uncomment to show images
//imshow("check", Images[i]);
//waitKey(1);
}
// 1. Initialize all the transforms to the identity matrix
vector<Mat> transforms;
for (int i = 0; i < NUM_IMAGES; i++) {
transforms.push_back(Mat::eye(3, 3, CV_64F));
}
// 2. Calculate the transformation matrices
Homography(Images, transforms);
// 3. Compute the min and max limits of the transformations
int xMin, xMax, yMin, yMax;
FindOutputLimits(Images, transforms, xMin, xMax, yMin, yMax);
// 4/5. Initialize the panorama image
Mat panorama = Mat::zeros(yMax - yMin + 1, xMax - xMin + 1, CV_64F);
cout << "X total = " << xMax - xMin + 1 << endl;
cout << "Y total = " << yMax - yMin + 1 << endl;
cout << "panorama height = " << panorama.size().height << endl;
cout << "panorama width = " << panorama.size().width << endl;
// 6. Initialize warped mask images
vector<Mat> masks_warped(NUM_IMAGES);
//masks_warped.reserve(NUM_IMAGES);
// 7. Warp image masks
warpMasks(Images, masks_warped, transforms, panorama);
// 8. Warp the images
warpImages(Images, masks_warped, transforms, panorama);
// 9. Initialize the blended panorama images
Mat pano_feather = Mat::zeros(panorama.size(),CV_64F);
Mat pano_multiband = Mat::zeros(panorama.size(), CV_64F);
// 10. Blend
BlendImages(Images, pano_feather, pano_multiband, masks_warped, transforms);
return 0;
}
void Homography(const vector<Mat> &Images, vector<Mat> &transforms)
{
//get number of images
int num_images = Images.size();
//generate key points and match images
for (int i = 1; i < num_images; i++) {
//sift detector and extractor
Ptr<FeatureDetector> feature_detector = FeatureDetector::create("SIFT");
Ptr<DescriptorExtractor> descriptor_extract = DescriptorExtractor::create("SIFT");
//matcher
Ptr<DescriptorMatcher> desc_matcher = DescriptorMatcher::create("BruteForce");
//keypoints/dexscriptors for first image
vector<KeyPoint> store_kp_first;
Mat current_d_first;
//keypoints/dexscriptors for second image
vector<KeyPoint> store_kp_sec;
Mat current_d_sec;
//vector for match data
vector<DMatch> match_data;
Mat image_out;
//points for first and second image
vector<Point2d> first;
vector<Point2d> second;
//detect and extract for both images
feature_detector->detect(Images[i], store_kp_first);
descriptor_extract->compute(Images[i], store_kp_first, current_d_first);
feature_detector->detect(Images[i - 1], store_kp_sec);
descriptor_extract->compute(Images[i - 1], store_kp_sec, current_d_sec);
//matcha and draw matches
desc_matcher->match(current_d_first, current_d_sec, match_data);
drawMatches(Images[i], store_kp_first, Images[i - 1], store_kp_sec, match_data, image_out, DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
//uncomment to save images
/*std:ostringstream os;
os << "Dmatched_image_" << i << ".jpg";
imwrite(os.str(), image_out)*/;
//process for removing our of range matches
double min_dist = DBL_MAX;
for (int j = 0; j < match_data.size(); j++) {
double distance = match_data[j].distance;
if (distance < min_dist)
min_dist = distance;
}
//needs to be modified depending on data set
min_dist *= 3.2;
//delete bad matches
match_data.erase(
std::remove_if(
match_data.begin(), match_data.end(),
[min_dist](DMatch remove) {return (remove.distance > min_dist); }
),
match_data.end()
);
//extra the coordinates
for (int j = 0; j < match_data.size(); j++) {
first.push_back(store_kp_first[match_data[j].queryIdx].pt);
second.push_back(store_kp_sec[match_data[j].trainIdx].pt);
}
//compute transform
transforms[i] = findHomography(first, second, RANSAC);
}
//uncomment for direct comparison
/*Mat transform_extra = transforms[0] * transforms[5];
std::cout << transform_extra << endl;*/
//finish computing transforms between images
for (int i = 1; i < num_images; i++) {
transforms[i] = transforms[i - 1] * transforms[i];
}
//uncomment ro display 5th tranform
//std::cout << transforms[5] << endl;
}
void FindOutputLimits(const vector<Mat> &Images, vector<Mat> &transforms, int &xMin, int &xMax, int &yMin, int &yMax)
{
int num_images = Images.size();
//std::cout << "length of vector: " << Images.size() << std::endl;
//initalize min amd max values
xMin = INT_MAX;
yMin = INT_MAX;
xMax = INT_MIN;
yMax = INT_MIN;
//printf("[xMin xMax yMin yMax] = [%d, %d, %d, %d]\n", xMin, xMax, yMin, yMax);
//initialize matrices for operations
Mat proj = Mat::ones(3, 1, CV_64F);
Mat corn = Mat::ones(3, 1, CV_64F);
Mat trans = Mat::eye(3, 3, CV_64F);
vector<Mat> corners(4);
//intialize corners
for (int i = 0; i < corners.size(); i++) {
corners[i] = Mat::ones(3, 1, CV_64F);
}
//fill in corner vector
for (int i = 0; i < num_images; i++) {
corners[0].at<double>(0, 0) = 0;
corners[0].at<double>(1, 0) = 0;
corners[1].at<double>(0, 0) = 0;
corners[1].at<double>(1, 0) = Images[i].size().height - 1;
corners[2].at<double>(0, 0) = Images[i].size().width - 1;;
corners[2].at<double>(1, 0) = 0;
corners[3].at<double>(0, 0) = Images[i].size().width - 1;;
corners[3].at<double>(1, 0) = Images[i].size().height - 1;
//for the corners compute projection and keep track of max and min
for (int j = 0; j < corners.size(); j++) {
corn.at<double>(0, 0) = corners[j].at<double>(0, 0);
corn.at<double>(1, 0) = corners[j].at<double>(1, 0);
//compute proj and noramilze
proj = transforms[i] * corn;
proj /= proj.at<double>(2,0);
//updat max and min values for x and y
if (proj.at<double>(0, 0) > xMax) {
xMax = proj.at<double>(0, 0);
}
if(proj.at<double>(0,0) < xMin){
xMin = proj.at<double>(0, 0);
}
if (proj.at<double>(1, 0) > yMax) {
yMax = proj.at<double>(1, 0);
}
if (proj.at<double>(1, 0) < yMin) {
yMin = proj.at<double>(1, 0);
}
}
}
//fill translation matrix
trans.at<double>(0, 2) = -xMin;
trans.at<double>(1, 2) = -yMin;
//update transformation matrices
for (int i = 0; i < num_images; i++) {
transforms[i] = trans * transforms[i];
}
//cout << trans << endl;
//printf("[xMin xMax yMin yMax] = [%d, %d, %d, %d]\n", xMin, xMax, yMin, yMax);
}
void warpMasks(const vector<Mat> &Images, vector<Mat> &masks_warped, const vector<Mat> &transforms, const Mat &panorama)
{
int num_images = Images.size();
//std::cout << "length of vector: " << Images.size() << std::endl;
//initilaize masks
vector<Mat> masks(num_images);
for (int i = 0; i < num_images; i++) {
//create masks and make warped masks
masks[i] = Mat::ones(Images[i].size().height, Images[i].size().width, CV_8U);
masks[i].setTo(cv::Scalar::all(255));
warpPerspective(masks[i], masks_warped[i], transforms[i], panorama.size());
//uncomment to save warped masks
/*std::ostringstream os;
os << "warped_masks_" << i << ".jpg";
imwrite(os.str(), masks_warped[i]);*/
}
}
void warpImages(const vector<Mat> &Images, const vector<Mat> &masks_warped, const vector<Mat> &transforms, Mat &panorama)
{
int num_images = Images.size();
//initialize image out matrices
vector<Mat> Images_out(num_images);
for (int i = 0; i < num_images; i++) {
//create warped images
warpPerspective(Images[i],Images_out[i],transforms[i],panorama.size(), INTER_LINEAR, BORDER_CONSTANT,1);
//copy to panorama
Images_out[i].copyTo(panorama,masks_warped[i]);
//uncomment to save warped images
/*std::ostringstream os;
os << "warped_image_" << i << ".jpg";
imwrite(os.str(), Images_out[i]);*/
}
//uncomment to save panorama
//imwrite("panorma_warped.jpg", panorama);
}
void BlendImages(const vector<Mat> &Images, Mat &pano_feather, Mat &pano_multiband, const vector<Mat> &masks_warped, const vector<Mat> &transforms)
{
//create blenders
detail::FeatherBlender f_blend;
detail::MultiBandBlender mb_blend;
//prepare blenders
f_blend.prepare(Rect(0, 0, pano_feather.cols, pano_feather.rows));
mb_blend.prepare(Rect(0, 0, pano_feather.cols, pano_feather.rows));
for (int i = 0; i < Images.size(); i++) {
Mat image_warped;
//warp images, and convert
warpPerspective(Images[i], image_warped, transforms[i], pano_feather.size(), INTER_LINEAR, BORDER_REPLICATE, 1);
image_warped.convertTo(image_warped, CV_16S);
//feed images to blender
f_blend.feed(image_warped, masks_warped[i], Point(0, 0));
mb_blend.feed(image_warped, masks_warped[i], Point(0, 0));
}
//create empty masks
Mat f_empty = Mat::zeros(pano_feather.size(), CV_8U);
Mat mb_empty = Mat::zeros(pano_multiband.size(), CV_8U);
//blend and convert
f_blend.blend(pano_feather, f_empty);
mb_blend.blend(pano_multiband, mb_empty);
pano_feather.convertTo(pano_feather, CV_8U);
pano_multiband.convertTo(pano_multiband, CV_8U);
//uncomment to display blended images
//imwrite("pano_feather.jpg", pano_feather);
//imwrite("pano_multiband.jpg", pano_multiband);
} | true |