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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d615e9edcc1783c987ad287a1f2bd6803c2394b9 | C++ | lipan6461188/icSHAPE-pipe | /PsBL/src/pan_type.h | UTF-8 | 6,355 | 2.65625 | 3 | [] | no_license |
#ifndef PAN_TYPE_H
#define PAN_TYPE_H
#include <unordered_map>
#include <vector>
#include <iostream>
#include <string>
#include <functional>
#include <memory>
#include <cstring>
#define PsBL_LIB_VERSION "PsBL 1.1.0(2018-11-2)"
using std::unordered_map;
using std::vector;
using std::string;
using std::pair;
using std::ostream;
using std::shared_ptr;
namespace pan{
using uINT = unsigned int;
using uLONG = unsigned long;
using uLONGLONG = unsigned long long;
using StringArray = vector<string>;
using StringMatrix = vector<vector<string>>;
using IntArray = vector<int>;
using uIntArray = vector<unsigned int>;
using uLONGArray = vector<unsigned long>;
using uLONGLONGArray = vector<unsigned long long>;
using FloatArray = vector<float>;
using DoubleArray = vector<double>;
using MapStringString = unordered_map<string, string>;
using MapStringuLONG = unordered_map<string, uLONG>;
using MapStringDouble = unordered_map<string, double>;
//using Region = pair<uLONG, uLONG>;
//using Point = pair<uLONG, uLONG>;
//using PointF = pair<double, double>;
struct Region
{
uLONG first;
uLONG second;
//bool is_null(){ return first<=second?false:true; };
Region(pair<uLONG, uLONG>init_pair):first(init_pair.first), second(init_pair.second){}
Region(uLONG first, uLONG second):first(first), second(second){}
Region()=default;
};
inline bool operator==(const Region &r_1, const Region &r_2){ return (r_1.first==r_2.first and r_1.second==r_2.second) ? true : false; }
inline bool operator!=(const Region &r_1, const Region &r_2){ return not(r_1==r_2); }
inline ostream& operator<<(ostream& OUT, const Region& r){ OUT << r.first << "-" << r.second; return OUT; }
bool operator<(const Region &r_1, const Region &r_2);
uLONG overlap(const Region &r_1, const Region &r_2);
vector<Region> operator+(const Region &r_1, const Region &r_2);
vector<Region> operator-(const Region &r_1, const Region &r_2);
struct Point
{
uLONG first;
uLONG second;
Point(pair<uLONG, uLONG>init_pair):first(init_pair.first), second(init_pair.second){}
Point(uLONG first, uLONG second):first(first), second(second){}
Point()=default;
};
inline bool operator==(const Point &p_1, const Point &p_2){ return (p_1.first==p_2.first and p_1.second==p_2.second) ? true : false; }
inline bool operator!=(const Point &p_1, const Point &p_2){ return not(p_1==p_2); }
inline Point operator+(const Point &p_1, const Point &p_2){ return Point( p_1.first+p_2.first, p_1.second+p_2.second ); }
inline Point operator-(const Point &p_1, const Point &p_2){ return Point( p_1.first-p_2.first, p_1.second-p_2.second ); }
inline ostream& operator<<(ostream& OUT, const Point& p){ OUT << "(" << p.first << "," << p.second << ")"; return OUT; }
struct PointF
{
double first;
double second;
PointF(pair<double, double>init_pair):first(init_pair.first), second(init_pair.second){}
PointF(uLONG first, uLONG second):first(first), second(second){}
PointF()=default;
};
inline bool operator==(const PointF &p_1, const PointF &p_2){ return (p_1.first==p_2.first and p_1.second==p_2.second) ? true : false; }
inline bool operator!=(const PointF &p_1, const PointF &p_2){ return not(p_1==p_2); }
inline PointF operator+(const PointF &p_1, const PointF &p_2){ return PointF( p_1.first+p_2.first, p_1.second+p_2.second ); }
inline PointF operator-(const PointF &p_1, const PointF &p_2){ return PointF( p_1.first-p_2.first, p_1.second-p_2.second ); }
inline ostream& operator<<(ostream& OUT, const PointF& p){ OUT << "(" << p.first << ", " << p.second << ")"; return OUT; }
using RegionArray = vector<Region>;
bool sorted(const RegionArray &ra);
bool sorted_no_overlap(const RegionArray &ra);
//typedef template unordered_map<string, T> MapStringT<T>;
template<typename T>
using MapStringT = unordered_map<string, T>;
// =========== MATRIX ===========
template<typename T>
using Matrix = vector<vector<T>>;
template<typename F_T, typename S_T>
ostream& operator<<(ostream& OUT, const pair<F_T, S_T> &cur_pair);
template<typename T>
ostream& operator<<(ostream& OUT, const vector<T> &cur_vec);
template<typename T>
ostream& operator<<(ostream& OUT, const vector<vector<T>> &cur_matrix);
template<typename K_T, typename V_T>
ostream& operator<<(ostream& OUT, const unordered_map<K_T, V_T> &cur_map);
/* ========================
Pointer
======================== */
template<typename T>
using sp = shared_ptr<T>;
template<typename T>
ostream& operator<<(ostream& OUT, const vector<T> &cur_vec)
{
for(auto iter=cur_vec.cbegin(); iter!=cur_vec.cend(); iter++)
{
OUT << *iter;
if(iter!=cur_vec.cend()-1)
OUT << "\t";
}
return OUT;
}
template<typename F_T, typename S_T>
ostream& operator<<(ostream& OUT, const pair<F_T, S_T> &cur_pair)
{
OUT << cur_pair.first << "-" << cur_pair.second;
return OUT;
}
template<typename T>
ostream& operator<<(ostream& OUT, const vector<vector<T>> &cur_matrix)
{
for(auto iter_1=cur_matrix.cbegin(); iter_1!=cur_matrix.cend(); iter_1++)
{
for(auto iter_2=iter_1->cbegin(); iter_2!=iter_1->cend(); iter_2++)
{
OUT << *iter_2;
if(iter_2!=iter_1->cend()-1)
OUT << "\t";
}
OUT << "\n";
}
return OUT;
}
template<typename K_T, typename V_T>
ostream& operator<<(ostream& OUT, const unordered_map<K_T, V_T> &cur_map)
{
for(auto iter=cur_map.cbegin(); iter!=cur_map.cend(); iter++)
{
OUT << iter->first << "\t" << iter->second << "\n";
}
return OUT;
}
template<typename T>
void init_matrix(Matrix<T> &matrix, typename Matrix<T>::size_type size, T init_value=T())
{
matrix.clear();
vector<T> row;
T t(init_value);
row.resize(size, t);
matrix.resize(size, row);
for_each(matrix.begin(), matrix.end(), [](vector<T> &cur_row)->void{ cur_row.shrink_to_fit(); });
}
template<typename T>
using Rect = vector<vector<T>>;
template<typename T>
void init_rect(Rect<T> &matrix, typename Rect<T>::size_type row_num, typename Rect<T>::size_type col_num, T init_value=T())
{
matrix.clear();
vector<T> row;
T t(init_value);
row.resize(col_num, t);
matrix.resize(row_num, row);
for_each(matrix.begin(), matrix.end(), [](vector<T> &cur_row)->void{ cur_row.shrink_to_fit(); });
}
}
#endif | true |
68d0e94869b754988327461d987038bdd96d01db | C++ | nmai/esp32-tft-progress-bar-clock | /src/classes/Screen.cpp | UTF-8 | 8,614 | 2.578125 | 3 | [] | no_license |
#include <classes/Screen.h>
// I believe this will create it outside the scope of the class instance itself, sort of a singleton
TFT_eSPI tft = TFT_eSPI(135, 240);
// const int CHOSEN_FONT = &FreeSansBold9pt7b;
const int FONT_DEFAULT_WIDTH = 6;
const int FONT_DEFAULT_HEIGHT = 8;
const int FONT_PT9_WIDTH = 11;
const int FONT_PT9_HEIGHT = 30;
const int CHAR_WIDTH = SCALE * FONT_DEFAULT_WIDTH;
Screen::Screen() {
sprintf(clock_lastHour, "%s", "00");
sprintf(clock_lastMinute, "%s", "11");
sprintf(clock_lastSecond, "%s", "22");
}
void Screen::initialize() {
tft.init();
tft.setRotation(-1);
tft.fillScreen(TFT_BLACK);
tft.setTextSize(2);
tft.setTextColor(TFT_GREEN);
tft.setCursor(0, 0);
tft.setTextDatum(MC_DATUM); // (this is a guess) sets the "origin" of text to the middle of the char
tft.setTextSize(1);
if (TFT_BL > 0) { // TFT_BL has been set in the TFT_eSPI library in the User Setup file TTGO_T_Display.h
pinMode(TFT_BL, OUTPUT); // Set backlight pin to output mode
digitalWrite(TFT_BL, TFT_BACKLIGHT_ON); // Turn backlight on. TFT_BACKLIGHT_ON has been set in the TFT_eSPI library in the User Setup file TTGO_T_Display.h
}
tft.drawString("LeftButton:", tft.width() / 2, tft.height() / 2 - 16);
tft.drawString("[Get Time]", tft.width() / 2, tft.height() / 2 );
tft.drawString("RightButton:", tft.width() / 2, tft.height() / 2 + 16);
tft.drawString("[WiFi Connect]", tft.width() / 2, tft.height() / 2 + 32 );
tft.setTextDatum(TL_DATUM); // (this is a guess) sets the "origin" of text to the top left of the char
}
// Deprecated
void Screen::DemoIntro() {
// the bitmap
tft.setSwapBytes(true); // if colors in images are wrong, setting this will "correct for the endianess of the byte order"
tft.pushImage(0, 0, 240, 135, ttgo);
espDelay(5000);
// now the random colors
tft.setRotation(0);
tft.fillScreen(TFT_RED);
espDelay(1000);
tft.fillScreen(TFT_BLUE);
espDelay(1000);
tft.fillScreen(TFT_GREEN);
espDelay(1000);
tft.fillScreen(TFT_BLACK);
tft.setTextDatum(MC_DATUM);
}
void Screen::WifiScan_P1() {
tft.setTextColor(TFT_GREEN, TFT_BLACK);
tft.fillScreen(TFT_BLACK);
tft.setTextDatum(MC_DATUM);
tft.setTextSize(1);
tft.drawString("Scan Network", tft.width() / 2, tft.height() / 2);
}
void Screen::WifiScan_P2(int16_t results) {
tft.fillScreen(TFT_BLACK);
if (results == 0) {
tft.drawString("no networks found", tft.width() / 2, tft.height() / 2);
} else {
tft.setTextDatum(TL_DATUM);
tft.setCursor(0, 0);
for (int i = 0; i < results; ++i) {
sprintf(buff,
"[%d]:%s(%d)",
i + 1,
WiFi.SSID(i).c_str(),
WiFi.RSSI(i));
tft.println(buff);
}
}
}
void Screen::WifiConnect_P1() {
tft.fillScreen(TFT_BLACK);
tft.drawString("Connecting...", 0, tft.height() / 2);
}
void Screen::WifiConnect_P2() {
tft.fillScreen(TFT_BLACK);
tft.drawString("Connected to: guest wifi", 0, tft.height() / 2);
}
void Screen::ClockBar(String timestamp) {
Serial.println(timestamp);
char b[timestamp.length()];
timestamp.toCharArray(b, timestamp.length() + 1);
tft.fillRect(0, 0, tft.width(), 10, 0xF800);
tft.drawString(b, 0, 0);
// tft.setCursor(0, 0);
// tft.fillScreen(TFT_BLACK);
// tft.drawString(b, 0, tft.height() / 2);
// tft.println(b);
}
void Screen::TextTester() {
tft.fillScreen(TFT_BLACK);
tft.setFreeFont(&FreeSansBold9pt7b);
tft.setTextSize(1);
tft.drawString("1234abcgABCG", 0, tft.height() / 2);
tft.setCursor(0, 0);
tft.println("1234abcgABCG");
tft.println("1234abcgABCG");
tft.println("1234abcgABCG");
int height = (int32_t)(tft.height());
int width = (int32_t)(tft.width());
tft.drawLine( 12 * FONT_PT9_WIDTH, 0, 12 * FONT_PT9_WIDTH, height, 0xFFFFFF );
tft.drawLine( 0, 3 * FONT_PT9_HEIGHT, width, 3 * FONT_PT9_HEIGHT, 0xFFFFFF );
}
void Screen::Home() {
}
/** @todo - let's redraw smarter, we only really need to draw 2 lines every cycle once the initial painting is in place */
const bool DRAW_MARKERS = true;
const bool DRAW_LABELS = false;
void Screen::ProgressBarClock() {
const uint8_t ogDatum = tft.getTextDatum();
const uint8_t ogTextSize = tft.textsize;
tft.fillRect(0, tft.height() / 2, tft.width(), tft.height(), 0x000000);
DateTimeParts parts = DateTime.getParts();
int hours = parts.getHours();
int minutes = parts.getMinutes();
float percent = (hours + (minutes / 60.0)) / 24.0;
int rx = tft.width() / 10; // start 10% away from the left of the screen
int ry = tft.height() / 2; // start halfway down the screen
int rw = tft.width() - rx * 2; // end 10% away from right of screen
int rh = (tft.height() / 2) - tft.height() / 10; // end 10% away from bottom of screen
int hy = ry - tft.height() / 20 * 3; // start the marker line 15% higher than the top of the rect
int hw = tft.height() / 20 * 2; // end the line 5% above the top of the rect
int hx8 = rx + rw / 24 * 8;
int hx10 = rx + rw / 24 * 10;
int hx12 = rx + rw / 24 * 12;
int hx14 = rx + rw / 24 * 14;
int hx16 = rx + rw / 24 * 16;
// Draw bounding box and progress bar
int nowX = (int32_t)(percent * rw);
tft.fillRect(rx, ry, nowX, rh, 0xFFFFFF);
tft.drawRect(rx, ry, rw, rh, TFT_SKYBLUE);
if (DRAW_MARKERS) {
tft.drawFastVLine(hx8, hy, hw, 0xFFFFFF);
tft.drawFastVLine(hx10, hy + hw / 2, hw / 2, 0xFFFFFF);
tft.drawFastVLine(hx12, hy, hw, 0xFFFFFF);
tft.drawFastVLine(hx14, hy + hw / 2, hw / 2, 0xFFFFFF);
tft.drawFastVLine(hx16, hy, hw, 0xFFFFFF);
}
if (DRAW_LABELS) {
const float LABEL_SCALE_FACTOR = 0.5;
tft.setTextSize(SCALE * LABEL_SCALE_FACTOR);
int ty = ry - tft.height() / 20 * 5; // draw the char 25% above the rect
// tft.setTextDatum(MC_DATUM);
tft.drawString("8", hx8 - CHAR_WIDTH/2 * LABEL_SCALE_FACTOR, ty);
tft.drawString("12", hx12 - CHAR_WIDTH * LABEL_SCALE_FACTOR, ty);
tft.drawString("4", hx16 - CHAR_WIDTH/2 * LABEL_SCALE_FACTOR, ty);
}
tft.setTextDatum(ogDatum); // cleanup
tft.setTextSize(ogTextSize); // cleanup
}
void Screen::Clock() {
const int ogTextSize = tft.textsize;
const int ogTextColor = tft.textcolor;
int len = 8; // "00:00:00"
int x = tft.width() / 2 - (len * CHAR_WIDTH) / 2;
int y = tft.height() / 10;
tft.setTextSize(SCALE);
DateTimeParts parts = DateTime.getParts();
int hours = parts.getHours();
if (hours == 0) // 12hr conversion - midnight thru 1am
hours = 12;
if (hours >= 13) // 12hr conversion - all PM hours, except noon ... 12hr format sure is strange
hours -= 12;
int minutes = parts.getMinutes();
int seconds = parts.getSeconds();
const bool redrawHours = atoi(clock_lastHour) != hours;
const bool redrawMinutes = atoi(clock_lastMinute) != minutes;
const bool redrawSeconds = atoi(clock_lastSecond) != seconds;
// blackout w/ smart redraw
tft.setTextColor(TFT_BLACK);
if (redrawHours) tft.drawString(clock_lastHour, x, y);
// tft.drawString(":", x + CHAR_WIDTH * 2, y);
if (redrawMinutes) tft.drawString(clock_lastMinute, x + CHAR_WIDTH * 3, y);
// tft.drawString(":", x + CHAR_WIDTH * 5, y);
if (redrawSeconds) tft.drawString(clock_lastSecond, x + CHAR_WIDTH * 6, y);
// generate the new time segments (btw this is so disgusting)
if (hours > 9) itoa(hours, clock_lastHour, 10);
else {
itoa(hours, clock_lastHour, 10);
clock_lastHour[1] = clock_lastHour[0];
clock_lastHour[0] = '0';
}
if (minutes > 9) itoa(minutes, clock_lastMinute, 10);
else {
itoa(minutes, clock_lastMinute, 10);
clock_lastMinute[1] = clock_lastMinute[0];
clock_lastMinute[0] = '0';
}
if (seconds > 9) itoa(seconds, clock_lastSecond, 10);
else {
itoa(seconds, clock_lastSecond, 10);
clock_lastSecond[1] = clock_lastSecond[0];
clock_lastSecond[0] = '0';
}
// now draw in the new time w/ smart redraw
tft.setTextColor(TFT_WHITE);
if (redrawHours)
tft.drawString(clock_lastHour, x, y);
if (redrawMinutes)
tft.drawString(clock_lastMinute, x + CHAR_WIDTH * 3, y);
if (redrawSeconds)
tft.drawString(clock_lastSecond, x + CHAR_WIDTH * 6, y);
// we don't really need to draw this every time since they're static, but leaving for now
tft.drawString(":", x + CHAR_WIDTH * 2, y);
tft.drawString(":", x + CHAR_WIDTH * 5, y);
tft.setTextSize(ogTextSize);
tft.setTextColor(ogTextColor);
}
void Screen::Clear() {
tft.fillScreen(TFT_BLACK);
// tft.setFreeFont(&FreeSansBold9pt7b);
tft.setTextColor(TFT_WHITE);
}
| true |
f0b2d64a03caf885585d48d02d26fe0ff7a4f7d3 | C++ | dabibbit/keyvadb-cc | /db/db.h | UTF-8 | 4,746 | 2.53125 | 3 | [] | no_license | #pragma once
#include <string>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <system_error>
#include "db/memory.h"
#include "db/file.h"
#include "db/buffer.h"
#include "db/tree.h"
#include "db/log.h"
namespace keyvadb {
template <class Storage, class Log = NullLog>
class DB {
using util = detail::KeyUtil<Storage::Bits>;
using key_store_type = typename Storage::KeyStorage;
using value_store_type = typename Storage::ValueStorage;
using key_value_type = KeyValue<Storage::Bits>;
using buffer_type = Buffer<Storage::Bits>;
using journal_type = std::unique_ptr<Journal<Storage::Bits>>;
using tree_type = Tree<Storage::Bits>;
using key_value_func =
std::function<void(std::string const &, std::string const &)>;
private:
enum { key_length = Storage::Bits / 8 };
Log log_;
key_store_type keys_;
value_store_type values_;
tree_type tree_;
buffer_type buffer_;
std::atomic<bool> close_;
std::thread thread_;
public:
explicit DB(std::uint32_t const degree)
: log_(Log{}),
keys_(Storage::CreateKeyStore(degree)),
values_(Storage::CreateValueStore()),
tree_(tree_type(keys_)),
buffer_(),
close_(false),
thread_(&DB::flushThread, this) {}
DB(std::string const &valueFileName, std::string const &keyFileName,
std::uint32_t const blockSize, std::uint32_t const cacheLevels)
: log_(Log{}),
keys_(Storage::CreateKeyStore(valueFileName, blockSize, cacheLevels)),
values_(Storage::CreateValueStore(keyFileName)),
tree_(tree_type(keys_)),
buffer_(),
close_(false),
thread_(&DB::flushThread, this) {}
DB(DB const &) = delete;
DB &operator=(DB const &) = delete;
~DB() {
close_ = true;
try {
thread_.join();
if (auto err = values_->Close())
if (log_.error)
log_.error << "Closing values file: " << err.message();
if (auto err = keys_->Close())
if (log_.error)
log_.error << "Closing keys file: " << err.message();
} catch (std::exception &ex) {
if (log_.error)
log_.error << "Destructor exception: " << ex.what();
}
}
// Not threadsafe
std::error_condition Open() {
if (auto err = keys_->Open())
return err;
if (auto err = tree_.Init(true))
return err;
return values_->Open();
}
// Not threadsafe
std::error_condition Clear() {
if (auto err = keys_->Clear())
return err;
if (auto err = tree_.Init(true))
return err;
return values_->Clear();
}
std::error_condition Get(std::string const &key, std::string *value) {
if (key.length() != key_length)
return db_error::key_wrong_length;
auto k = util::FromBytes(key);
std::uint64_t valueId;
if (!buffer_.Get(k, &valueId)) {
std::error_condition err;
std::tie(valueId, err) = tree_.Get(k);
if (err)
return err;
if (log_.debug)
log_.debug << "Get: " << util::ToHex(k) << ":" << valueId;
} else {
if (log_.debug)
log_.debug << "Buffer Get: " << util::ToHex(k) << ":" << valueId;
}
return values_->Get(valueId, value);
}
std::error_condition Put(std::string const &key, std::string const &value) {
if (key.length() != key_length)
return db_error::key_wrong_length;
key_value_type kv;
if (auto err = values_->Set(key, value, kv))
return err;
buffer_.Add(kv.key, kv.value);
if (log_.debug)
log_.debug << "Put: " << util::ToHex(kv.key) << ":" << kv.value;
return std::error_condition();
}
// Returns keys and values in insertion order
std::error_condition Each(key_value_func f) { return values_->Each(f); }
private:
std::error_condition flush() {
auto snapshot = buffer_.GetSnapshot();
if (snapshot->Size() == 0)
return std::error_condition();
if (log_.info)
log_.info << "Flushing: " << snapshot->Size() << " keys";
journal_type journal;
std::error_condition err;
std::tie(journal, err) = tree_.Add(snapshot);
if (err)
return err;
if (auto err = journal->Commit(keys_))
return err;
buffer_.ClearSnapshot(snapshot);
if (log_.info)
log_.info << "Flushed: " << snapshot->Size() << " keys into "
<< journal->Size() << " nodes";
return std::error_condition();
}
void flushThread() {
for (;;) {
std::this_thread::sleep_for(std::chrono::seconds(1));
bool stop = close_;
if (auto err = flush())
if (log_.error)
log_.error << "Flushing Error: " << err.message() << ":"
<< err.category().name();
if (stop)
break;
}
// thread exits
}
};
} // namespace keyvadb
| true |
838cbdbf1efa9f3fd79dc0080ff173031bc7e0c2 | C++ | jmkim/algorithm_and_practice-pknu-2016 | /excercise04/sort/merge_sort.cpp | UTF-8 | 891 | 3.734375 | 4 | [
"MIT"
] | permissive | #include <string.h> /* memcpy() */
#include "merge_sort.hpp"
void merge_sort(int *data, const int size_of_data)
{
return merge(data, 0, size_of_data - 1);
}
void merge(int *data, const int start, const int end)
{
int size = end - start + 1;
if(size <= 1) return; /* base case */
/* divide */
int s1 = start, e1 = s1 + size / 2 - 1,
s2 = e1 + 1, e2 = end;
merge(data, s1, e1);
merge(data, s2, e2);
/* conquer */
int temp[size] = {0, };
int pt = 0, p1 = s1, p2 = s2;
while(p1 <= e1 && p2 <= e2)
{
while(p1 <= e1 && data[p1] <= data[p2]) temp[pt++] = data[p1++];
while(p2 <= e2 && data[p1] >= data[p2]) temp[pt++] = data[p2++];
}
while(p1 <= e1) temp[pt++] = data[p1++];
while(p2 <= e2) temp[pt++] = data[p2++];
/* copy the sorted data */
memcpy(data + start, temp, sizeof(int) * size);
}
| true |
702ac3df21061e95aa1a678f01c8c7d2b96a9ebc | C++ | SpookyScaryDev/Jem | /Engine/Source/Core/Game/Game.h | UTF-8 | 1,079 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <Core/Window/Window.h>
#include <Core/Event/Event.h>
namespace Jem {
// ===============================================================================
//
// Base Game Class.
// To be subclassed by the client and run by Jem Engine.
// Game is a singleton - you can use the GetGame method to return the instance.
//
// ===============================================================================
class Game {
public:
Game(const char* name, int width, int height); // Calls Init.
virtual ~Game(); // Calls Shutdown.
virtual void OnEvent(Event* event); // Event callback.
static Game* GetGame(); // Retrieve the static game instance.
void Run();
protected:
virtual void Update(double deltaTime) {};
bool mIsRunning;
private:
void Init(const char* name, int width, int height) const;
void Shutdown() const;
static Game* mGame;
};
} | true |
2325a178ba691671b0d339acc899dbe0b7d24a6b | C++ | hulcyp/GuildhallProjects | /QTProjects/MonkyMaterialEditor/GraphLayoutParser.cpp | UTF-8 | 4,331 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "GraphLayoutParser.h"
#include "Node.h"
#include "MaterialGraphWidget.h"
#include "NodeType.h"
#include "Link.h"
void GraphLayoutParser::ParseGraphLayout( const char* layoutBuffer, int size, MaterialGraphWidget* graph )
{
char* currPos = const_cast<char*>( layoutBuffer );
if( size > 0 )
{
char* bufferEnd = currPos + size;
int versionNumber = *reinterpret_cast< int* >( currPos );
currPos += sizeof( int );
if( versionNumber == MATERIAL_VERSION_NUMBER )
{
int numNodes = *reinterpret_cast< int* >( currPos );
currPos += sizeof( int );
std::map< int, NodeData* > nodeMap;
for( int i = 0; i < numNodes && currPos < bufferEnd; ++i )
{
Node* node = ConstructNode( currPos, graph );
if( node != nullptr )
{
graph->scene()->addItem( node );
NodeData* nodeData = new NodeData( node );
nodeMap[ node->GetNodeID() ] = nodeData;
unsigned int numConnectors = node->InputConnectors().size();
for( unsigned int c = 0; c < numConnectors; ++c )
{
nodeData->inputConnectorIDs.push_back( *reinterpret_cast< const int* >( currPos ) );
currPos += sizeof( int );
nodeData->outputConnectorIDs.push_back( *reinterpret_cast< const int* >( currPos ) );
currPos += sizeof( int );
}
}
}
for( auto iter = nodeMap.begin(); iter != nodeMap.end(); ++iter )
{
ReconnectNode( iter->second, nodeMap, graph );
}
graph->scene()->update();
}
}
}
//---------------------------------------------------------------------------
Node* GraphLayoutParser::ConstructNode( char*& currPosInLayoutBuffer, MaterialGraphWidget* graph )
{
int nodeID = *reinterpret_cast< int* >( currPosInLayoutBuffer );
currPosInLayoutBuffer += sizeof( int );
NodeType::NodeTypeID typeID = (NodeType::NodeTypeID)(*reinterpret_cast< int* >( currPosInLayoutBuffer ));
currPosInLayoutBuffer += sizeof( int );
float xPos = *reinterpret_cast< float* >( currPosInLayoutBuffer );
currPosInLayoutBuffer += sizeof( float );
float yPos = *reinterpret_cast< float* >( currPosInLayoutBuffer );
currPosInLayoutBuffer += sizeof( float );
Node* newNode = NodeType::ConstructNodeFromType( NodeType::GetStringTypeFromID( typeID ), graph );
if( newNode != nullptr )
{
newNode->setPos( (qreal)xPos, (qreal)yPos );
newNode->SetNodeID( nodeID );
if( typeID == NodeType::NT_OUTPUT_CHANNELS )
graph->m_outputChannels = newNode;
QList< std::pair< QString, QString > >& attributes = newNode->Attributes();
unsigned int numAttribs = attributes.size();
for( unsigned int i = 0; i < numAttribs; ++i )
{
int attribLen = *reinterpret_cast< int* >( currPosInLayoutBuffer );
currPosInLayoutBuffer += sizeof( int );
if( attribLen > 0 )
{
char* attrib = new char[ attribLen + 1 ];
std::memcpy( attrib, currPosInLayoutBuffer, attribLen );
currPosInLayoutBuffer += attribLen;
attrib[ attribLen ] = '\0';
attributes[i].second = attrib;
delete attrib;
}
}
newNode->AttributesUpdated();
}
return newNode;
}
//---------------------------------------------------------------------------
void GraphLayoutParser::ReconnectNode( NodeData* nodeData, std::map< int, NodeData* >& nodeMap, MaterialGraphWidget* graph )
{
for( unsigned int i = 0; i < nodeData->inputConnectorIDs.size(); ++i )
{
if( nodeData->inputConnectorIDs[i] != -1 && nodeData->outputConnectorIDs[i] != -1 )
{
NodeData* otherNode = nodeMap[ nodeData->inputConnectorIDs[i] ];
Link* newLink = new Link( otherNode->node->OuputConnectors()[ nodeData->outputConnectorIDs[i] ], nodeData->node->InputConnectors()[i] );
if( newLink != nullptr )
graph->scene()->addItem( newLink );
}
}
}
| true |
daf37af266b499a6b6f7c5711fb438905260e1dc | C++ | BlackWind001/C_plus_plus_trial | /04_user_defined_types_01_structs.cpp | UTF-8 | 1,103 | 3.984375 | 4 | [] | no_license | #include <iostream>
struct Custom_Vector{
int size;
double* array;
};
void Custom_Vector_init(Custom_Vector& ref_v, int size){
ref_v.size = size;
double* arr = new double [size];
ref_v.array = arr;
}
void assign(Custom_Vector& ref_v){
int size = ref_v.size;
auto arr_pointer = ref_v.array;
double temp;
while(size>0){
std::cin>>temp;
*(arr_pointer + (size-1) ) = temp;
size--;
}
}
double find_sum(Custom_Vector v){
auto size = v.size;
auto array = v.array;
double sum = 0;
while(size > 0){
sum = sum + *(array + (size - 1) );
size--;
}
return sum;
}
int main(){
int size = 2;
//Take size input here if necessary
std::cout<<"Enter size value here : ";
std::cin>>size;
//Initializing the Custom_Vector
Custom_Vector v;
Custom_Vector_init(v, size);
//Assigning values
std::cout<<"Enter values"<<std::endl;
assign(v);
//Calculating sum
std::cout<<"The sum is : "<<find_sum(v)<<std::endl;
return 0;
} | true |
a715fb5d8f7b4269229b9bd8597cd1db6cc8298f | C++ | HiroshiNohara/Recognition-Algorithm | /C++/Algorithm/Algorithm/traintest.cpp | UTF-8 | 7,858 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
std::vector<Mat> _histograms;
Mat _labels;
extern Mat lbp(Mat src);
extern Mat elbp(Mat src, int radius, int neighbors);
extern Mat DCP1(Mat src, int Rin, int Rex);
extern Mat DCP2(Mat src, int Rin, int Rex);
extern Mat LTP1(Mat src, int radius, int neighbors, float threshold, bool adaption);
extern Mat LTP2(Mat src, int radius, int neighbors, float threshold, bool adaption);
extern Mat spatial_histogram(Mat src, int min, int numPatterns, int grid_x, int grid_y);
void read_csv_image(string fileName, char separator, int lines, int _grid_x, int _grid_y){
int j = 0;
ifstream file(fileName, ifstream::in);
string line, path, label;
while (getline(file, line)){
stringstream lines(line);
getline(lines, path, separator);
getline(lines, label);
if (!path.empty() && !label.empty()){
cout << "COMPUTING NUM" << j + 1 << " PIC`S FEATURES..." << endl;
Mat src = imread(path);
resize(src, src, cv::Size(128, 128));
cvtColor(src, src, CV_BGR2GRAY);
equalizeHist(src, src);
/* If you use Original LBP algorithm, calculate the characteristic histogram using below method:*/
Mat lbp_image = lbp(src);
Mat p1 = spatial_histogram(lbp_image, 0, (int)pow(2, 8), _grid_x, _grid_y);
Mat p = Mat::zeros(1, p1.cols, CV_32FC1);
for (int i = 0; i < p1.cols; i++){
p.at<float>(i) = p1.at<float>(i);
}
/* If you use LBP algorithm, calculate the characteristic histogram using below method
(You need to define radius and neighbors in functions first): */
//Mat elbp_image = elbp(src, radius, neighbors);
//Mat p1 = spatial_histogram(elbp_image, 0, (int)pow(2, neighbors), _grid_x, _grid_y);
//Mat p = Mat::zeros(1, p1.cols, CV_32FC1);
//for (int i = 0; i < p1.cols; i++) {
// p.at<float>(i) = p1.at<float>(i);
//}
/* If you use DCP algorithm, calculate the characteristic histogram using below method
(You need to define Rin and Rex in functions first):*/
//Mat dcp_image1 = DCP1(src, Rin, Rex);
//Mat dcp_image2 = DCP2(src, Rin, Rex);
//Mat p1 = spatial_histogram(dcp_image1, 0, (int)pow(2, 8), _grid_x, _grid_y);
//Mat p2 = spatial_histogram(dcp_image2, 0, (int)pow(2, 8), _grid_x, _grid_y);
//Mat p = Mat::zeros(1, p1.cols + p2.cols, CV_32FC1);
//for (int index1 = 0; index1 < p1.cols; index1++){
// p.at<float>(index1) = p1.at<float>(index1);
//}
//for (int index2 = p1.cols; index2 < p1.cols + p2.cols; index2++){
// p.at<float>(index2) = p2.at<float>(index2 - p1.cols);
//}
/* If you use LTP algorithm, calculate the characteristic histogram using below method
(If the adaptation is set to true, then the value of the threshold parameter is invalid):*/
//Mat ltp_image1 = LTP1(src, radius, neighbors, 5.0, false);
//Mat ltp_image2 = LTP2(src, radius, neighbors, 5.0, false);
//Mat p1 = spatial_histogram(ltp_image1, 0, (int)pow(2, neighbors), _grid_x, _grid_y);
//Mat p2 = spatial_histogram(ltp_image2, 0, (int)pow(2, neighbors), _grid_x, _grid_y);
//Mat p = Mat::zeros(1, p1.cols + p2.cols, CV_32FC1);
//for (int index1 = 0; index1 < p1.cols; index1++){
// p.at<float>(index1) = p1.at<float>(index1);
//}
//for (int index2 = p1.cols; index2 < p1.cols + p2.cols; index2++){
// p.at<float>(index2) = p2.at<float>(index2 - p1.cols);
//}
_histograms.push_back(p);
}
j++;
}
file.close();
}
void read_csv_label(string fileName, char separator, int lines){
ifstream file(fileName, ifstream::in);
string line, path, label;
while (getline(file, line)){
stringstream lines(line);
getline(lines, path, separator);
getline(lines, label);
if (!path.empty() && !label.empty()){
_labels.push_back(atoi(label.c_str()));
}
}
file.close();
}
void train(string fileName, char separator, int lines, int _grid_x, int _grid_y){
cout << "READING TRAIN DATA..." << endl;
read_csv_image(fileName, separator, lines, _grid_x, _grid_y);
read_csv_label(fileName, separator, lines);
cout << "OPERATING DONE" << endl;
}
void predict(string fileName, char separator, int lines, int _grid_x, int _grid_y){
int j = 0;
int count = 0;
ifstream file(fileName, ifstream::in);
string line, path, label;
while (getline(file, line)){
stringstream lines(line);
getline(lines, path, separator);
getline(lines, label);
if (!path.empty() && !label.empty()){
Mat src = imread(path);
resize(src, src, cv::Size(128, 128));
cvtColor(src, src, CV_BGR2GRAY);
equalizeHist(src, src);
/* If you use Original LBP algorithm, calculate the characteristic histogram using below method:*/
Mat lbp_image = lbp(src);
Mat q1 = spatial_histogram(lbp_image, 0, (int)pow(2, 8), _grid_x, _grid_y);
Mat query = Mat::zeros(1, q1.cols, CV_32FC1);
for (int i = 0; i < q1.cols; i++){
query.at<float>(i) = q1.at<float>(i);
}
/* If you use LBP algorithm, calculate the characteristic histogram using below method
(You need to define radius and neighbors in functions first): */
//Mat elbp_image = elbp(src, radius, neighbors);
//Mat q1 = spatial_histogram(elbp_image, 0, (int)pow(2, neighbors), _grid_x, _grid_y);
//Mat query = Mat::zeros(1, q1.cols, CV_32FC1);
//for (int i = 0; i < q1.cols; i++) {
// query.at<float>(i) = q1.at<float>(i);
//}
/* If you use DCP algorithm, calculate the characteristic histogram using below method
(You need to define Rin and Rex in functions first):*/
//Mat dcp_image1 = DCP1(src, Rin, Rex);
//Mat dcp_image2 = DCP2(src, Rin, Rex);
//Mat q1 = spatial_histogram(dcp_image1, 0, (int)pow(2, 8), _grid_x, _grid_y);
//Mat q2 = spatial_histogram(dcp_image2, 0, (int)pow(2, 8), _grid_x, _grid_y);
//Mat query = Mat::zeros(1, q1.cols + q2.cols, CV_32FC1);
//for (int index1 = 0; index1 < q1.cols; index1++){
// query.at<float>(index1) = q1.at<float>(index1);
//}
//for (int index2 = q1.cols; index2 < q1.cols + q2.cols; index2++){
// query.at<float>(index2) = q2.at<float>(index2 - q1.cols);
//}
/* If you use LTP algorithm, calculate the characteristic histogram using below method
(If the adaptation is set to true, then the value of the threshold parameter is invalid):*/
//Mat ltp_image1 = LTP1(src, radius, neighbors, 5.0, false);
//Mat ltp_image2 = LTP2(src, radius, neighbors, 5.0, false);
//Mat q1 = spatial_histogram(ltp_image1, 0, (int)pow(2, neighbors), _grid_x, _grid_y);
//Mat q2 = spatial_histogram(ltp_image2, 0, (int)pow(2, neighbors), _grid_x, _grid_y);
//Mat query = Mat::zeros(1, q1.cols + q2.cols, CV_32FC1);
//for (int index1 = 0; index1 < q1.cols; index1++){
// query.at<float>(index1) = q1.at<float>(index1);
//}
//for (int index2 = q1.cols; index2 < q1.cols + q2.cols; index2++){
// query.at<float>(index2) = q2.at<float>(index2 - q1.cols);
//}
double minDist = DBL_MAX;
int minClass = -1;
for (size_t sampleIdx = 0; sampleIdx < _histograms.size(); sampleIdx++){
double dist = compareHist(_histograms[sampleIdx], query, HISTCMP_CHISQR_ALT);
if (dist < minDist){
minDist = dist;
minClass = _labels.at<int>((int)sampleIdx);
}
}
cout << j + 1 << " " << minClass << " " << atoi(label.c_str()) << endl;
if (minClass == atoi(label.c_str())){
count++;
}
}
j++;
}
file.close();
cout << "Accuracy = " << (double)(count * 100 / (double)lines) << "%";
cout << " (" << count << "/" << lines << ") (classification)" << endl;
}
int getlinenum(string fileName, char separator){
int j = 0;
ifstream file(fileName, ifstream::in);
string line, path, label;
while (getline(file, line)){
stringstream lines(line);
getline(lines, path, separator);
getline(lines, label);
if (!path.empty() && !label.empty()){
j++;
}
}
file.close();
return j;
}
| true |
bf076da8bb678a0653d3bcf329ea24ec00de33f0 | C++ | sancherie/docker-compose-multistage | /src/app/docker/builder/ComposeBuilder.cpp | UTF-8 | 1,721 | 2.6875 | 3 | [] | no_license | //
// Created by clementsanchez on 4/19/20.
//
#include <iostream>
#include "ComposeBuilder.hpp"
Docker::Builder::ComposeBuilder::ComposeBuilder(Vector<String> files) :
files(std::move(files))
{
}
Docker::Compose Docker::Builder::ComposeBuilder::build()
{
this->parseComposeConfig();
return Compose(this->parseServices());
}
void Docker::Builder::ComposeBuilder::parseComposeConfig()
{
FILE *process = popen(this->getComposeCommand().c_str(), "r");
std::ostringstream stream;
char buffer[1024] = {0};
while (fgets(buffer, 1024, process) != nullptr) {
stream << buffer;
memset(buffer, 0, 1024);
}
pclose(process);
this->config = YAML::Load(stream.str());
}
String Docker::Builder::ComposeBuilder::getComposeCommand()
{
std::ostringstream stream;
stream << "docker-compose";
std::for_each(this->files.begin(), this->files.end(), [&stream](const String &file) {
stream << " -f " << file;
});
stream << " config";
return stream.str();
}
Vector<Docker::Service> Docker::Builder::ComposeBuilder::parseServices()
{
Vector<Service> services;
const Map<String, YAML::Node> &servicesMap = this->config["services"].as<Map<String, YAML::Node>>();
std::for_each(servicesMap.begin(), servicesMap.end(), [this, &services](const Pair<String, YAML::Node> &service) {
if (this->isServiceBuildable(service.second)) {
services.push_back(ServiceBuilder(service.first, service.second).build());
}
});
return services;
}
bool Docker::Builder::ComposeBuilder::isServiceBuildable(const YAML::Node &service) const
{
return service["image"].IsDefined() && service["build"].IsDefined();
}
| true |
6052188bca8d437c19628c17746f1b173f84ec60 | C++ | jamalhsargana/Assignment-2 | /ownedPointer.cpp | UTF-8 | 3,784 | 4.03125 | 4 | [] | no_license | #include <iostream>
class STRING_BUFFER
{
public:
char* stringbuff;
int stringlength;
bool owner;
public:
STRING_BUFFER();
STRING_BUFFER(char*, int);
char charAt(int) const;
int length() const;
void reserve(int);
void append(char);
void print() {
for (int i = 0; i < stringlength; i++) {
std::cout << stringbuff[i];
}
std::cout << std::endl;
std::cout << "Length: " << stringlength << std::endl;
}
STRING_BUFFER& operator=( STRING_BUFFER&b)
{
delete[] this->stringbuff;
this->stringlength = b.stringlength;
this->stringbuff = b.stringbuff;
this->owner = 1;
std::cout << "BLAH";
return *this;
}
STRING_BUFFER(const STRING_BUFFER&b){
delete[] this->stringbuff;
this->stringlength = b.stringlength;
this->stringbuff = b.stringbuff;
this->owner = 1;
std::cout << "BLAH";
}
STRING_BUFFER::~STRING_BUFFER()
{
//destructor; would delete the allocated buffer
if (this->owner)
{
delete[] this->stringbuff;
}
else
{
std::cout << "Invalid pointer used for deletion";
}
}
};
STRING_BUFFER::STRING_BUFFER()
{
stringbuff = new char();
stringlength = 0;
owner = 0;
}
STRING_BUFFER::STRING_BUFFER(char* newString, int length)
{ //constructor to convert a char* to
this->stringbuff = newString;
this->stringlength = length;
}
char STRING_BUFFER::charAt(int index) const
{ //returns the character at the passed index
if (stringlength == 0 || index >= stringlength || index < 0)
{
std::cout << "Invalid index accessed." << std::endl;
return ' ';
}
else
return stringbuff[index];
}
int STRING_BUFFER::length() const
{ //returns the length of the buffer
return stringlength;
}
void STRING_BUFFER::reserve(int length)
{
//allocates memory for the string, according to the passed character length
char* mystring = new char[length];
delete[] stringbuff;
stringbuff = new char[length];
stringlength = length;
for (int i = 0; i < stringlength; i++)
{
stringbuff[i] = mystring[i];
}
delete[] mystring;
}
void STRING_BUFFER::append(char newChar)
{
//appends a single character at the end
char* mystring = new char[stringlength + 1];
for (int i = 0; i < stringlength; i++)
{
mystring[i] = stringbuff[i];
}
mystring[stringlength] = newChar;
delete[] stringbuff;
stringbuff = new char[stringlength + 1];
stringlength++;
for (int i = 0; i < stringlength; i++)
{
stringbuff[i] = mystring[i];
}
delete[] mystring;
}
int main(void)
{
STRING_BUFFER *newString = new STRING_BUFFER();
newString->print();
std::cout << "Appending 'c'..." << std::endl;
newString->append('c');
newString->print();
newString->append('f');
newString->print();
newString->append('g');
newString->print();
newString->append('h');
newString->print();
newString->append('i');
newString->print();
std::cout << std::endl;
std::cout << newString->charAt(0) << std::endl;
std::cout << newString->charAt(1) << std::endl;
std::cout << newString->charAt(2) << std::endl;
std::cout << newString->charAt(3) << std::endl;
std::cout << newString->charAt(4) << std::endl;
std::cout << newString->charAt(5) << std::endl;
std::cout << newString->stringlength << std::endl;
std::cout << newString->stringlength << std::endl;
STRING_BUFFER *b = new STRING_BUFFER(*newString);
std::cout << b->charAt(0) << std::endl;
std::cout << b->charAt(1) << std::endl;
delete b;
}
| true |
7fcf5160c4a5ac872314c057a124f11b432c9951 | C++ | sameer-h/CSCE121 | /Homeworks/HW8/School.cpp | UTF-8 | 4,647 | 3.21875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <iomanip>
#include "School.h"
#include "AttendanceRecord.h"
using namespace std;
/* Sameer Hussain - CSCE 121 - Attendance */
// need a helper function for validity that a value exists within vector
bool School::containsVal(vector<string> v, string val) {
for (size_t i = 0; i < v.size(); i++) {
if (val == v.at(i)) {
return true;
}
}
return false;
}
void School::addStudents(string filename) {
ifstream ifs(filename);
if (!ifs.is_open()) {
cout << "Unable to open file: " << filename << endl;
return;
}
string line, stuID, stName;
vector<string> studentIDs;
while (!ifs.eof()) {
getline(ifs, line);
stringstream ss(line);
if (line == "" && ifs.eof()) {
break;
}
getline(ss, stuID, ',');
if (containsVal(studentIDs, stuID)) {
continue;
}
getline(ss, stName);
Student stu(stuID, stName);
students.push_back(stu); // adding to vector
studentIDs.push_back(stuID);
}
ifs.close();
}
void School::listStudents() {
if (students.size() == 0) {
cout << "No Students\n";
}
else {
for (size_t i = 0; i < students.size(); ++i)
{
cout << students.at(i).get_id() << "," << students.at(i).get_name() << "\n";
}
}
}
void School::addCourses(string filename) {
ifstream ifs(filename);
if (!ifs.is_open()) {
cout << "Unable to open file: " << filename << endl;
return;
}
string line, stuID, titleT, hour, min, endHr, endMin;
vector<string> courseIDs;
while (!ifs.eof()) {
getline(ifs, line);
stringstream ss(line);
if (line == "" && ifs.eof()) {
break;
}
getline(ss, stuID, ',');
if (containsVal(courseIDs, stuID)) {
continue;
}
getline(ss, hour, ':');
getline(ss, min, ',');
getline(ss, endHr, ':');
getline(ss, endMin, ',');
getline(ss, titleT);
Date tempStart(stoi(hour), stoi(min)); // string to int
Date tempEnd(stoi(endHr), stoi(endMin));
Course tcourse(stuID, titleT, tempStart, tempEnd); //add to courses
courses.push_back(tcourse);
courseIDs.push_back(stuID);
}
ifs.close();
}
void School::listCourses() {
if (courses.size() == 0) {
cout << "No Courses\n";
}
else {
for (size_t i = 0; i < courses.size(); i++) {
cout << courses.at(i).getID() << "," << courses.at(i).getStartTime().getTime(false) << ",";
cout << courses.at(i).getEndTime().getTime(false) << "," << courses.at(i).getTitle() << "\n";
}
}
}
void School::addAttendanceData(string filename) {
ifstream ifs(filename);
if (!ifs.is_open()) {
cout << "Unable to open file: " << filename << endl;
return;
}
string line, yr, month, day, tempHr, tMin, secs, tcourse, stuID;
while (!ifs.eof()) {
getline(ifs, line);
stringstream ss(line);
if (line == "" && ifs.eof()) {
break;
}
getline(ss, yr, '-');
getline(ss, month, '-');
getline(ss, day, ' ');
getline(ss, tempHr, ':');
getline(ss, tMin, ':');
getline(ss, secs, ',');
getline(ss, tcourse, ',');
getline(ss, stuID);
Date swipeT(stoi(yr), stoi(month), stoi(day), stoi(tempHr), stoi(tMin), stoi(secs));
for (size_t i = 0; i < courses.size(); i++) {
if (courses.at(i).getID() == tcourse) {
if (swipeT >= courses.at(i).getStartTime() && swipeT <= courses.at(i).getEndTime()) {
AttendanceRecord tempRecord(tcourse, stuID, swipeT); // adding to attendance record
courses.at(i).addAttendanceRecord(tempRecord);
} else {
cout << "did not save this record.\n";
}
break;
}
}
}
ifs.close();
}
void School::outputCourseAttendance (string course_id) {
bool valid = false;
for (size_t i = 0; i < courses.size(); i++) {
if (courses.at(i).getID() == course_id) {
courses.at(i).outputAttendance();
valid = true;
break;
}
}
if (!valid) {
cout << "No Records\n";
}
}
void School::outputStudentAttendance(string student_id, string course_id) {
bool valid = false;
for (size_t i = 0; i < courses.size(); i++) {
if (courses.at(i).getID() == course_id) {
courses.at(i).outputAttendance(student_id);
valid = true;
break;
}
}
if (!valid) {
cout << "No Records\n";
}
}
| true |
a9579f1975ff2c5a6cb295e44eeca37a70fca575 | C++ | Gorvillio/mobiledragon | /src/include/md_tl/iterator.h | UTF-8 | 1,312 | 3.109375 | 3 | [
"MIT"
] | permissive | /** \file
* Basic template iterators. <br>
*
* Copyright 2005-2006 Herocraft Hitech Co. Ltd.<br>
* Version 1.0 beta.
*/
#ifndef __MD_ITERATOR_H__
#define __MD_ITERATOR_H__
namespace mdragon
{
template <class BackInsertionSequence>
class back_insert_iterator
{
public:
typedef back_insert_iterator<BackInsertionSequence> self;
inline back_insert_iterator ( BackInsertionSequence & sequence_ ) :
sequence(sequence_) { ; }
inline back_insert_iterator ( self & src ) :
sequence(src.sequence) { ; }
inline self & operator = ( const self & src)
{ sequence = src.sequence; }
inline self & operator * ()
{ return *this; }
inline self & operator = (
const typename BackInsertionSequence::value_type & t )
{ sequence.push_back( t ); return *this; }
inline self & operator ++ (){ return *this; }
inline self & operator ++ ( int) { return *this; }
private:
BackInsertionSequence & sequence;
};
template<class BackInsertionSequence> inline
back_insert_iterator<BackInsertionSequence>
back_inserter( BackInsertionSequence & sequence )
{
return back_insert_iterator<BackInsertionSequence>( sequence );
}
template <class T> inline T* value_type( const T* )
{
return (T*)NULL;
}
} // namespace mdragon
#endif // __MD_ITERATOR_H__
| true |
dc73364b5bbb8f56ad79ec3539d508e4b68b7287 | C++ | xingangshi/study_exec | /design_pattern/8_composite/composite.cpp | UTF-8 | 1,456 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include "composite.h"
void compont::add(compont* child)
{
}
void compont::remove(compont* child)
{
}
compont* compont::getChild(int index)
{
return NULL;
}
void leaf::operation()
{
std::cout << "operation by leaf" << std::endl;
}
composite::~composite()
{
std::list<compont*>::const_iterator temp;
for (std::list<compont*>::const_iterator iter = m_listOfCompont.begin();
iter != m_listOfCompont.end(); ++iter)
{
temp = iter;
delete (*temp);
}
}
void composite::add(compont* child)
{
m_listOfCompont.push_back(child);
}
void composite::remove(compont* child)
{
std::list<compont*>::iterator ite;
ite = std::find(m_listOfCompont.begin(), m_listOfCompont.end(), child);
if (m_listOfCompont.end() != ite)
m_listOfCompont.erase(ite);
}
compont* composite::getChild(int index)
{
if (index < 0 || index > m_listOfCompont.size())
return NULL;
int i = 0;
std::list<compont*>::const_iterator iter;
for (iter = m_listOfCompont.begin();
iter != m_listOfCompont.end(); ++iter)
{
if ( i == index)
break;
++i;
}
return (*iter);
}
void composite::operation()
{
std::cout << "operation by composite" << std::endl;
for (std::list<compont*>::iterator iter = m_listOfCompont.begin();
iter != m_listOfCompont.end(); ++iter)
(*iter)->operation();
}
| true |
a6fafdff97c07bbf63494f628d47d6e8c6456351 | C++ | Caspar-Chen-hku/C-practices | /palindrome2.cpp | UTF-8 | 801 | 3.3125 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool charAndNum(char text){
if ((text>='a' && text<='z') || (text>='A' && text<='Z')
|| (text>='0' && text<='9')){
return true;
}
return false;}
string makeFixed (){
string fixed = "";
char text;
while (cin >> text){
if (charAndNum (text) == true){
fixed += text;
}
}
return fixed;
}
int main(){
string fixed = makeFixed();
int lth = fixed.length();
for (int i=0; i<lth; i++){
if (fixed[i]>='A' && fixed[i]<='Z'){
fixed[i] -= ('A'-'a');
}
}
for (int i=0; i<lth/2; i++){
if (fixed[i] != fixed[lth-1-i]){
cout << "No";
return 0;
}
}
cout << "Yes";
return 0;
} | true |
057fa2529dd5a00bca3b5fd7a1949ed83ca0b8b9 | C++ | KarthikeyaYadav/Competitive-Programming | /PRAC/dec_to_bin.cpp | UTF-8 | 455 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <bitset>
#include <string>
#include <bits/stdc++.h>
int main()
{
std::string binary = std::bitset<32>(2147483647).to_string(); //to binary
std::cout<<binary<<"\n";
unsigned long decimal = std::bitset<32>(binary).to_ulong();
std::cout<<decimal<<"\n";
std::string bin="10101010";
unsigned long decimaal = std::bitset<32>(bin).to_ulong();
std::cout<<decimaal<<"\n";
return 0;
}
| true |
9ff6e6d68a31a93d3c15172538593050a080f763 | C++ | harshitgupta2019/khatarnakcoder | /codeforces/62A-A student's Dream.cpp | UTF-8 | 198 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
cin>>a>>b>>c>>d;
if((d-2*a<3)&&(a-d<=1)||(c-2*b<3)&&(b-c<=1))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
| true |
aaf12c5d0849ddedc17b049870a783fd40df2099 | C++ | carexoid/os-critical-region | /demo/demoDekkerLock.cpp | UTF-8 | 3,904 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <thread>
#include "DekkerLock.hpp"
constexpr std::size_t THREAD_OPERATION_REPEATS = 100000;
constexpr std::size_t RUNS_NUMBER = 10;
template <class Subtraction, class Addition>
void subtraction_addition_counter_demonstration(Subtraction subtraction, Addition addition)
{
for (int i = 0; i < RUNS_NUMBER; ++i) {
std::int32_t counter = 0;
std::thread addition_thread(addition, std::ref(counter)); // running addition in a new thread
subtraction(counter); // running subtraction in this thread
addition_thread.join();
std::cout << std::setfill('.') << std::setw(5) << std::left << i + 1
<< "Additions and Subtractions made: " << THREAD_OPERATION_REPEATS
<< "\n Resulting counter: " << counter << "\n";
}
}
void inc(std::int32_t& arg)
{
++arg;
}
void dec(std::int32_t& arg)
{
--arg;
}
template <class Function>
class BaseDecorator {
public:
explicit BaseDecorator(Function&& function) : _function(std::move(function)) {};
protected:
Function _function;
};
template <class Function>
class CycleDecorator : public BaseDecorator<Function> {
public:
explicit CycleDecorator(Function function) : BaseDecorator<Function>(std::move(function)) {};
using BaseDecorator<Function>::_function;
void operator()(std::int32_t& arg)
{
for (std::size_t i = 0; i < THREAD_OPERATION_REPEATS; ++i) {
_function(std::ref(arg));
}
}
};
void demonstrate_data_race()
{
std::cout << "\n***Demonstrating results of additions"
" and subtractions with no mutual exclusion primitives (data race demo)***\n";
subtraction_addition_counter_demonstration(CycleDecorator{dec}, CycleDecorator{inc});
}
template <class Function>
class ThreadSafeDecorator : public BaseDecorator<Function> {
public:
explicit ThreadSafeDecorator(Function function) : BaseDecorator<Function>(std::move(function)) {};
using BaseDecorator<Function>::_function;
template <class Lock>
void operator()(Lock& lock, std::int32_t& arg)
{
std::scoped_lock lk(lock);
_function(arg);
}
};
void avoid_data_race_with_dekker_lock()
{
std::cout << "\n***Demonstrating results of additions and subtractions using DekkerLock.lock()***\n";
lab::DekkerLock dekker_lock;
subtraction_addition_counter_demonstration(
CycleDecorator{
std::bind(ThreadSafeDecorator{dec}, std::ref(dekker_lock), std::placeholders::_1)
},
CycleDecorator{
std::bind(ThreadSafeDecorator{inc}, std::ref(dekker_lock), std::placeholders::_1)
}
);
}
template <class Function>
class ThreadSafeTryDecorator : BaseDecorator<Function> {
public:
explicit ThreadSafeTryDecorator(Function function) : BaseDecorator<Function>(std::move(function)) {};
using BaseDecorator<Function>::_function;
template <class Lock>
void operator()(Lock& lock, std::int32_t& arg)
{
while(!lock.try_lock());
_function(arg);
lock.unlock();
}
};
void avoid_data_race_with_dekker_lock_try()
{
std::cout << "\n***Demonstrating results of additions and subtractions using DekkerLock.try_lock()***\n";
lab::DekkerLock dekker_lock;
subtraction_addition_counter_demonstration(
CycleDecorator{
std::bind(ThreadSafeTryDecorator{dec}, std::ref(dekker_lock), std::placeholders::_1)
},
CycleDecorator{
std::bind(ThreadSafeTryDecorator{inc}, std::ref(dekker_lock), std::placeholders::_1)
}
);
}
auto main(int argc, char** argv) -> int
{
demonstrate_data_race();
avoid_data_race_with_dekker_lock();
avoid_data_race_with_dekker_lock_try();
return 0;
}
| true |
7fb9e053775378e24ea06a158d776054db17f1ff | C++ | Jokeswar/Bee-Engine | /include/Sprite.h | UTF-8 | 588 | 2.5625 | 3 | [] | no_license | #ifndef SPRITE_H
#define SPRITE_H
#include "Utility.h"
#include "Component.h"
#include <SDL2/SDL.h>
class Sprite: public Component
{
public:
Sprite();
Sprite(void*);
~Sprite();
void update() override;
int getWidth();
int getHeight();
void setNumberOfFrames(int);
void loadImage(const char*, Vector3);
bool show;
bool isValid;
private:
SDL_Texture* texture;
int imageWidth;
int imageHeight;
int currentFrame;
int numberOfFrames;
};
#endif // SPRITE_H
| true |
abb5c71254b5e79b116d9d783fb99f484f75705f | C++ | lkolezhuk/AdvancedImageAnalysisUNICAS | /project2/image_management.cpp | UTF-8 | 2,410 | 2.96875 | 3 | [] | no_license |
#include "image_management.h"
#include "aia/aiaConfig.h"
#include "ucas/ucasConfig.h"
#include <iostream>
using namespace std;
ImageManagement::ImageManagement(void)
{
}
ImageManagement::~ImageManagement(void)
{
}
std::vector<cv::Mat> ImageManagement :: LoadAllInDir(std::string folder, std::string ext, bool force_gray)
{
//check folders exist
if(!ucas::isDirectory(folder))
throw aia::error(aia::strprintf("in getImagesInFolder(): cannot open folder at \"%s\"", folder.c_str()));
// get all files within folder
std::vector < cv::String > files;
try{
cv::glob(folder, files);
}
catch(const std::exception& e){
std::cout << e.what() <<std::endl;
}
//// open files that contains 'ext'
std::vector < cv::Mat > images;
for(auto & f : files)
{
if(f.find(ext) == std::string::npos)
continue;
images.push_back(cv::imread(f, force_gray ? CV_LOAD_IMAGE_GRAYSCALE : CV_LOAD_IMAGE_UNCHANGED));
}
std :: cout << "Loaded " << images.size() << " from dataset" << std :: endl;
return images;
}
std::vector<cv::Mat> ImageManagement :: ApplyMasks(vector<cv::Mat> images, vector<cv::Mat> masks){
if(images.size() != masks.size()) throw std::runtime_error("ApplyMasks: The number of images and masks is not the same");
try
{
std::vector<cv::Mat> result;
for(unsigned int i = 0; i < images.size(); i++){
cv::Mat img;
result.push_back(img);
images[i].copyTo(result[i], masks[i]);
std :: cout << "Applied Masks to " << images.size() << " images" << std :: endl;
return result;
}
}
catch(exception e){
std::cout << "Apply Masks of ImageManagement ERROR : "<< e.what() << std :: endl;
throw e;
}
}
std::vector<cv::Mat> ImageManagement :: ExtractChanell(vector<cv::Mat> images, int channelNo){
cv::vector<cv::Mat> result;
for (int i = 0; i < images.size(); i++)
{
cv :: Mat channel[3];
// The actual splitting.
split(images[i], channel);
result.push_back(channel[channelNo]);
}
return result;
}
cv::Mat ImageManagement :: BlendImages(vector<cv::Mat> images){
cv::Mat mergedImage(images[0].size(), images[0].type());
cout<< "B" <<endl;
//Add each image from a vector<Mat> inputImages with weight 1.0/n where n is number of images to merge
for (cv::Mat mat : images) {
cout<< "B" <<endl;
cv::addWeighted(mergedImage, 5./6, mat, 1.0/6, 0, mergedImage);
cout<< "B" <<endl;
}
cout<< "b" <<endl;
return mergedImage;
}
| true |
7bc8e1bdb064b00a4ce2b303d0a1a7538fde5990 | C++ | DuPengFei-du/Cpp--Learning | /Cpp(36)/Cpp(36)/main.cpp | GB18030 | 15,073 | 3.875 | 4 | [] | no_license | //#include<iostream>
//using namespace std;
//struct Student
//{
// char name[20];
// int age;
// char gender;
//};
////CеĽṹ壬ֻܷݣܷźģCԵǰ
////ṹзźôʱǻģܷ֮
////ΪC̵ģݺͷǷ뿪
////C++УstructĽṹ壬ԷݻǿԷź
////Ҳ˵C++ЩݺͲЩݵķһ
//int main()
//{
// return 0;
//}
//#include<iostream>
//using namespace std;
//class Student
//{
//public:
// void SteDate(int year,int month,int day)
// {
// _year = year;
// _month = month;
// _day = day;
// }
//
// void DisPlay()
// {
// cout << _year << "." << _month << "." << _day << endl;
// }
//private:
// int _year;
// int _month;
// int _day;
//};
//int main()
//{
// return 0;
//}
//#include<iostream>
//#include<string.h>
//using namespace std;
//struct Student
//{
// void InitStudent(const char* name, int age, const char* gender)
// {
// strcpy(_name, name);
// _age = age;
// strcpy(_gender, gender);
// }
//
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//
// char _name[20];
// int _age;
// char _gender[3];
//};
//int main()
//{
// Student s1, s2, s3; //ѧ(ѧʵ)
// s1.InitStudent("wq", 35, "");
// s1.PrintStudnet();
//
// s2.InitStudent("ouhou", 5, "Ů");
// s2.PrintStudnet();
//
// s3.InitStudent("aha", 15, "");
// s3.PrintStudnet();
//
// return 0;
//}
////Person.cpp
//
//#include"Person.h"
//
//#include<string.h>
//#include<iostream>
//using namespace std;
//
//void Person::InitPerson(char* name, char* gender, int age)
//{
// strcpy_s(_name, name);
// _age = age;
// strcpy_s(_gender, gender);
//}
//void Person::PrintPerson()
//{
// cout << _name << "-" << _age << "-" << _gender << endl;
//}
//#include<iostream>
//#include<string>
//using namespace std;
//class Student
//{
// //Ա(ҲΪΪ)
//public:
// void InitStudent(const char* name, int age, const char* gender)
// {
// strcpy(_name, name);
// _age = age;
// strcpy(_gender, gender);
// }
//
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//private:
// //(ҲΪ)
// char _name[20];
// int _age;
// char _gender[3];
//};
//int main()
//{
// Student s1, s2, s3; //ѧ(ѧʵ)
// s1.InitStudent("wq", 35, "");
// s1.PrintStudnet();
//
// s2.InitStudent("nana", 5, "Ů");
// s2.PrintStudnet();
//
// s3.InitStudent("aha", 15, "");
// s3.PrintStudnet();
//
// return 0;
//}
//class A1
//{
//public:
// void f1()
// {
//
// }
//private:
// int _a;
//};
//// нгԱ
//class A2
//{
//public:
// void f2()
// {
//
// }
//};
//// ʲôû---
//class A3
//{
//
//};
//#include<iostream>
//#include<string.h>
//using namespace std;
//class Date
//{
//public:
// void Display()
// {
// cout << _year << "-" << _month << "-" << _day << endl;
// }
// void SetDate(int year, int month, int day)
// {
// _year = year;
// _month = month;
// _day = day;
// }
//private:
// int _year; //
// int _month; //
// int _day; //
//};
//int main()
//{
// Date d1, d2;
// d1.SetDate(2018, 5, 1);
// d2.SetDate(2018, 7, 1);
// d1.Display();
// d2.Display();
// return 0;
//}
//class Student
//{
//public:
// //this: Student* const thisָͣȻthisָǿĵģthisDzԱĵ
// void InitStudent(char* _name, int age, char* gender)
// {
// //this = nullptr;
// strcpy(this->_name, _name);
// _age = age;
// strcpy(_gender, gender);
// }
//
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//
//private:
// char _name[20];
// int _age;
// char _gender[3];
//};
//int main()
//{
// Student s1;
// s1.InitStudent("Peter", 35, "");
// s1.PrintStudnet();
//
// Student s2;
// s2.InitStudent("jingjing", 36, "Ů");
// s2.PrintStudnet();
// return 0;
//}
////CԵķʽģ
//#include<iostream>
//#include<string.h>
//using namespace std;
//struct Student
//{
// char _name[20];
// int _age;
// char _gender[3];
//};
//
//void StudentInit(Student* ps, char* name, int age, char* gender)
//{
// strcpy(ps->_name, name);
// ps->_age = age;
// strcpy(ps->_gender, gender);
//}
//
//void PrintStudent(Student* ps)
//{
// printf("%s %d %s", ps->_name, ps->_age, ps->_gender);
//}
//
//int main()
//{
// return 0;
//}
//struct Student
//{
// char _name[20];
// int _age;
// char _gender[3];
//};
//
//void InitStudent(Student* this, char* name, int age, char* gender)
//{
// strcpy(this->_name, name);
// this->_age = age;
// strcpy(this->_gender, gender);
//}
//
//void PrintStudent(Student* this)
//{
// printf("%s %d %s", this->_name, this->_age, this->_gender);
//}
//
//int main()
//{
// return 0;
//}
///*
//¹̣
//1. ʶ
//2. ʶгԱ
//3. ʶеijԱ&д
//*/
//
//#if 0
//class Student
//{
//public:
// /*
// void InitStudent(Student* const this, char* name, int age, char* gender)
// { ԱʵĸģΪһthisָ
// strcpy(this->_name, name);
// this->_age = age;
// strcpy(this->_gender, gender);
// }
// */
// void InitStudent(char* _name, int age, char* gender);
// // {
// // strcpy(this->_name, _name); ڱʵʵ
// // _age = age;
// // strcpy(_gender, gender);
// // }
//
// void TestFunc(...);
// // {
// // }
//
// /*
// // thisDZԼά(ά)
// void PrintStudnet(Student* const this)
// {
// cout << this->_name << "-" << this->_age << "-" << this->_gender << endl;
// }
// */
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//
//private:
// char _name[20];
// int _age;
// char _gender[3];
//};
//int main()
//{
// Student s1;
// s1.TestFunc();
// s1.TestFunc(10);
// s1.TestFunc(10, 20);
// // Student::InitStudent(&s1, "Peter", 35, "")
// s1.InitStudent("Peter", 35, "");
// // Student::PrintStudnet(&s1);
// s1.PrintStudnet();
//
// Student s2;
// s2.InitStudent("jingjing", 36, "Ů");
// s2.PrintStudnet();
// return 0;
//}
//class Test
//{
//public:
// void TestFunc()
// {
// //cout << &this << endl;
// Test* const& p = this; //仰൱ڴӡthisָĵַ
// //Ϊthisָ벻ֱӴӡַΪthisָһԴӡ
// //thisָĵַ
// cout << &p << endl;
// }
//
//public:
// int _t;
//};
//
//int main()
//{
// int* p = nullptr; //ɿ
// int*& q = p;
//
// cout << &q << endl;
// cout << &p << endl;
// //ӡ֮ĵַһģpqĵַͬ
//
// Test t;
// t.TestFunc(); //ͨȥú
//
// return 0;
//}
////Ȼ֮ȥebpespĴĵַthisĵַպebpesp
////Ĵĵַ֮
//thisָջ
//namespace N2
//{
// int a = 10;
// int b = 20;
// int c = 30;
// int Sub(int left, int right)
// {
// return left - right;
// }
// //ռ仹Ƕ
// namespace N3
// {
// int a = 10;
// int b = 20;
// int Mul(int left, int right)
// {
// return left * right;
// }
// }
//}
//printf("%d\n", N2::N3::a); //не
//void TestFunc(int a = 20);
//
//void TestFunc(int a = 20)
//{
//
//}
////ӵĴͻԭλͬʱĻܻIJһ
////ܾͻ˵ˣλûȽϺһЩΪʱҪõ⣬ҪʹãIJijֵһͻңȱʡֵֻdzȫֱ
//int main()
//{
// return 0;
//}
//void TestFunc()
//{}
//void TestFunc(int a = 0)
//{}
//int main()
//{
// TestFunc(10); //ǿͨģĸ
// TestFunc(); //Dzͨ
// //غĵòȷһԵãڶҲԵ
// return 0;
//}
//int main()
//{
// int a = 10;
// int& ra = a; //raaı
// cout << &ra << "=" << &a << endl;
// ra = 20; //ıraͬʱôaֵҲǻᷢı
//
// int& rb = a; //rbҲa һж
// rb = 30; //ôrbͬʱraaҲ˸ı
//
// int& rra = ra;
// rra = 40; //ôᷢı
// //ΪõĶͬһռ
//
// cout << a << " " << ra << " " << rb << " " << rra << " " << endl;
//
// return 0;
//}
//void Swap(int& ra, int& rb) //raaırbbı
//{
// int temp = ra;
// ra = rb;
// rb = temp;
// //ͨβΣҲ൱ǽʵ
//}
//int main()
//{
// int a = 1;
// int b = 2;
// Swap(a, b);
// cout << a << " " << b << " " << endl;
// return 0;
//}
////ҪпգҲҪãʹʮֵķ㣬ЧʱȽϸ
//// F.h
//#include <iostream>
//using namespace std;
//inline void f(int i);
//// F.cpp
//#include "F.h"
//void f(int i)
//{
// cout << i << endl;
//}
//// main.cpp
//#include "F.h"
//int main()
//{
// f(10);
// return 0;
//}
//// Ӵmain.obj : error LNK2019: ⲿ "void __cdecl f(int)" (?
////f@@YAXH@Z)÷ں _main бñ
////inlineεƾļҲ˵ֻڵǰļãֻԼĵǰļڲstatic,һ㲻Ͷֿ
//#include<iostream>
//using namespace std;
//int main()
//{
// auto a = 10; //ǽ (Ҫȥa)
// auto b = 12.34; ////ǽǸ
// auto c = a + b; //Լȥ
// cout << typeid(a).name() << endl;
// cout << typeid(b).name() << endl;
// cout << typeid(c).name() << endl;
// return 0;
//}
//void TestFor()
//{
// int array[] = { 1, 2, 3, 4, 5 };
// for (auto& e : array)
// {
// e *= 2;
// }
// for (auto e : array)
// {
// cout << e << endl;
// }
// return 0;
//}
//#include<iostream>
//using namespace std;
//struct Student
//{
// char name[20];
// int age;
// char gender;
//};
////CеĽṹ壬ֻܷݣܷźģCԵǰ
////ṹзźôʱǻģܷ֮
////ΪC̵ģݺͷǷ뿪
////C++УstructĽṹ壬ԷݻǿԷź
////Ҳ˵C++ЩݺͲЩݵķһ
//int main()
//{
// return 0;
//}
//#include<iostream>
//#include<string>
//using namespace std;
//struct Student
//{
// void InitStudent(const char* name, int age, const char* gender)
// {
// strcpy(_name, name);
// _age = age;
// strcpy(_gender, gender);
// }
//
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//
// char _name[20];
// int _age;
// char _gender[3];
//};
//int main()
//{
// Student s1, s2, s3; //ѧ(ѧʵ)
// s1.InitStudent("wq", 35, "");
// s1.PrintStudnet();
//
// s2.InitStudent("ouhou", 5, "Ů");
// s2.PrintStudnet();
//
// s3.InitStudent("aha", 15, "");
// s3.PrintStudnet();
//
// return 0;
//}
//class Student
//{
// //Ա(ҲΪΪ)
// void InitStudent(const char* name, int age, const char* gender)
// {
// strcpy(_name, name);
// _age = age;
// strcpy(_gender, gender);
// }
//
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//
// //(ҲΪ)
// char _name[20];
// int _age;
// char _gender[3];
//};
//class A1
//{
//public:
// void f1()
// {
//
// }
//private:
// int _a;
//};
//// нгԱ
//class A2
//{
//public:
// void f2()
// {
//
// }
//};
//// ʲôû---
//class A3
//{
//
//};
//#include<iostream>
//#include<string.h>
//using namespace std;
//class Date
//{
//public:
// void Display()
// {
// cout << _year << "-" << _month << "-" << _day << endl;
// }
// void SetDate(int year, int month, int day)
// {
// _year = year;
// _month = month;
// _day = day;
// }
//private:
// int _year; //
// int _month; //
// int _day; //
//};
//int main()
//{
// Date d1, d2;
// d1.SetDate(2018, 5, 1);
// d2.SetDate(2018, 7, 1);
// d1.Display();
// d2.Display();
// return 0;
//}
////CԵķʽģ
//#include<iostream>
//#include<string.h>
//using namespace std;
//struct Student
//{
// char _name[20];
// int _age;
// char _gender[3];
//};
//
//void StudentInit(Student* ps, char* name, int age, char* gender)
//{
// strcpy(ps->_name, name);
// ps->_age = age;
// strcpy(ps->_gender, gender);
//}
//
//void PrintStudent(Student* ps)
//{
// printf("%s %d %s", ps->_name, ps->_age, ps->_gender);
//}
//
//int main()
//{
// return 0;
//}
//struct Student
//{
// char _name[20];
// int _age;
// char _gender[3];
//};
//
//void InitStudent(Student* this, char* name, int age, char* gender)
//{
// strcpy(this->_name, name);
// this->_age = age;
// strcpy(this->_gender, gender);
//}
//
//void PrintStudent(Student* this)
//{
// printf("%s %d %s", this->_name, this->_age, this->_gender);
//}
//
//int main()
//{
// return 0;
//}
///*
//¹̣
//1. ʶ
//2. ʶгԱ
//3. ʶеijԱ&д
//*/
//
//#if 0
//class Student
//{
//public:
// /*
// void InitStudent(Student* const this, char* name, int age, char* gender)
// { ԱʵĸģΪһthisָ
// strcpy(this->_name, name);
// this->_age = age;
// strcpy(this->_gender, gender);
// }
// */
// void InitStudent(char* _name, int age, char* gender);
// // {
// // strcpy(this->_name, _name); ڱʵʵ
// // _age = age;
// // strcpy(_gender, gender);
// // }
//
// void TestFunc(...);
// // {
// // }
//
// /*
// // thisDZԼά(ά)
// void PrintStudnet(Student* const this)
// {
// cout << this->_name << "-" << this->_age << "-" << this->_gender << endl;
// }
// */
// void PrintStudnet()
// {
// cout << _name << "-" << _age << "-" << _gender << endl;
// }
//
//private:
// char _name[20];
// int _age;
// char _gender[3];
//};
//int main()
//{
// Student s1;
// s1.TestFunc();
// s1.TestFunc(10);
// s1.TestFunc(10, 20);
// // Student::InitStudent(&s1, "Peter", 35, "")
// s1.InitStudent("Peter", 35, "");
// // Student::PrintStudnet(&s1);
// s1.PrintStudnet();
//
// Student s2;
// s2.InitStudent("jingjing", 36, "Ů");
// s2.PrintStudnet();
// return 0;
//} | true |
f8c453085963c1bd2fe6941938431289c8f360e8 | C++ | BhishmDaslaniya/Operating-System-Algorithms | /sjf_p.cpp | UTF-8 | 2,700 | 3.078125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef struct process
{
char name[5];
int bt;
int at;
int wt, ta;
int flag;
int prt;
} processes;
void b_sort(processes temp[], int n)
{
processes t;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < n - 1; j++)
{
if (temp[j].at > temp[j + 1].at)
{
t = temp[j];
t = temp[j];
temp[j] = temp[j + 1];
temp[j + 1] = t;
}
}
}
}
int accept(processes P[])
{
int i, n;
printf("\n Enter total no. of processes : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\n PROCESS [%d]", i + 1);
printf(" Enter process name : ");
scanf("%s", &P[i].name);
printf(" Enter burst time : ");
scanf("%d", &P[i].bt);
printf(" Enter arrival time : ");
scanf("%d", &P[i].at);
printf(" Enter priority : ");
scanf("%d", &P[i].prt);
}
printf("\n PROC.\tB.T.\tA.T.\tPRIORITY");
for (i = 0; i < n; i++)
printf("\n %s\t%d\t%d\t%d", P[i].name, P[i].bt, P[i].at, P[i].prt);
return n;
}
void SJF_P(processes P[], int n)
{
int i, t_total = 0, tcurr, b[10], min_at, j, x, min_bt;
int sumw = 0, sumt = 0;
float avgwt = 0.0, avgta = 0.0;
processes temp[10], t;
for (i = 0; i < n; i++)
{
temp[i] = P[i];
t_total += P[i].bt;
}
b_sort(temp, n);
for (i = 0; i < n; i++)
b[i] = temp[i].bt;
i = j = 0;
printf("\n GANTT CHART\n\n %d %s", i, temp[i].name);
for (tcurr = 0; tcurr < t_total; tcurr++)
{
if (b[i] > 0 && temp[i].at <= tcurr)
b[i]--;
if (i != j)
printf(" %d %s", tcurr, temp[i].name);
if (b[i] <= 0 && temp[i].flag != 1)
{
temp[i].flag = 1;
temp[i].wt = (tcurr + 1) - temp[i].bt - temp[i].at;
temp[i].ta = (tcurr + 1) - temp[i].at;
sumw += temp[i].wt;
sumt += temp[i].ta;
}
j = i;
min_bt = 999;
for (x = 0; x < n; x++)
{
if (temp[x].at <= (tcurr + 1) && temp[x].flag != 1)
{
if (min_bt != b[x] && min_bt > b[x])
{
min_bt = b[x];
i = x;
}
}
}
}
printf(" %d", tcurr);
avgwt = (float)sumw / n;
avgta = (float)sumt / n;
printf("\n\n Average waiting time = %0.2f\n Average turn-around = %0.2f.", avgwt, avgta);
}
int main()
{
processes p[10];
int n;
n = accept(p);
SJF_P(p, n);
return 0;
} | true |
d84173bd238bb89bc64a6ba94c122363c4ceb003 | C++ | longluo/leetcode | /Cpp/leetcode/editor/cn/1855_maximum-distance-between-a-pair-of-values.cpp | UTF-8 | 2,905 | 2.90625 | 3 | [
"MIT"
] | permissive | //给你两个 非递增 的整数数组 nums1 和 nums2 ,数组下标均 从 0 开始 计数。
//
// 下标对 (i, j) 中 0 <= i < nums1.length 且 0 <= j < nums2.length 。如果该下标对同时满足 i <=
//j 且 nums1[i] <= nums2[j] ,则称之为 有效 下标对,该下标对的 距离 为 j - i 。
//
// 返回所有 有效 下标对 (i, j) 中的 最大距离 。如果不存在有效下标对,返回 0 。
//
// 一个数组 arr ,如果每个 1 <= i < arr.length 均有 arr[i-1] >= arr[i] 成立,那么该数组是一个 非递增 数组。
//
//
//
//
// 示例 1:
//
//
//输入:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
//输出:2
//解释:有效下标对是 (0,0), (2,2), (2,3), (2,4), (3,3), (3,4) 和 (4,4) 。
//最大距离是 2 ,对应下标对 (2,4) 。
//
//
// 示例 2:
//
//
//输入:nums1 = [2,2,2], nums2 = [10,10,1]
//输出:1
//解释:有效下标对是 (0,0), (0,1) 和 (1,1) 。
//最大距离是 1 ,对应下标对 (0,1) 。
//
// 示例 3:
//
//
//输入:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
//输出:2
//解释:有效下标对是 (2,2), (2,3), (2,4), (3,3) 和 (3,4) 。
//最大距离是 2 ,对应下标对 (2,4) 。
//
//
//
//
// 提示:
//
//
// 1 <= nums1.length <= 10⁵
// 1 <= nums2.length <= 10⁵
// 1 <= nums1[i], nums2[j] <= 10⁵
// nums1 和 nums2 都是 非递增 数组
//
// Related Topics 贪心 数组 双指针 二分查找 👍 25 👎 0
// 2022-04-11 11:58:54
// By Long Luo
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
// BF time: O(m * n) space: O(1)
// TimeOut
int maxDistance_bf(vector<int> &nums1, vector<int> &nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int max = 0;
for (int i = 0; i < len1; i++) {
for (int j = i; j < len2; j++) {
if (nums1[i] <= nums2[j]) {
max = std::max(max, j - i);
}
}
}
return max;
}
// Two Pointers time: O(m + n) space: O(1)
// AC
int maxDistance(vector<int> &nums1, vector<int> &nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int max = 0;
int p = 0;
int q = 0;
while (p < len1 && q < len2) {
if (nums1[p] > nums2[q]) {
p++;
}
if (p < len1 && q < len2 && nums1[p] <= nums2[q]) {
max = std::max(max, q - p);
}
q++;
}
return max;
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
vector<int> data1{55, 30, 5, 4, 2};
vector<int> data2{100, 20, 10, 10, 5};
cout << "2 ?= " << s.maxDistance(data1, data2) << endl;
} | true |
f152d3bdaa77ad0cf9d698ec0fd88239b2c5ed1d | C++ | q10/SPCE2 | /src/ewald.cpp | UTF-8 | 10,161 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "common.h"
void SPCEHamiltonian::initialize_all_ewald_tables() {
ASSERT(EWALD_ALPHA > 0.0 and EWALD_NXY > 0 and EWALD_NZ > 0, "INVALID EWALD PARAMETERS ALPHA, NXY, OR NZ");
K_111_INDEX = (3 * EWALD_NXY + 2) * (2 * EWALD_NZ + 1) + EWALD_NZ;
NUM_K_VECTORS = (EWALD_NXY + 1) * (2 * EWALD_NXY + 1) * (2 * EWALD_NZ + 1) - 1;
initialize_erfc_table();
initialize_k_vectors_table();
initialize_rho_k_values_table();
initialize_exp_kr_cache_tables();
return;
}
void SPCEHamiltonian::initialize_erfc_table() {
ERFC_TABLE.clear();
double sqrt_alpha = sqrt(EWALD_ALPHA);
// to optimize map search by using one less division, we keep the keys as x10^4
for (double r = 0.0; r < BOX_Z_LENGTH; r += 0.001)
ERFC_TABLE.push_back(erfc(r * sqrt_alpha));
return;
}
void SPCEHamiltonian::initialize_k_vectors_table() {
K_VECTORS.clear();
// K vector order as follows (go through all ny and nzvalues descending, then ascending):
double *arr, tmp_k2, half_factor, alpha_inv_4 = -1.0 / (4.0 * EWALD_ALPHA), four_pi_volume_ek = 4.0 * PCONSTANTS::ELECTROSTATIC_K * M_PI / BOX_VOLUME;
for (int nx = 0; nx <= EWALD_NXY; nx++) {
for (int ny = -EWALD_NXY; ny <= EWALD_NXY; ny++) {
for (int nz = -EWALD_NZ; nz <= EWALD_NZ; nz++) {
if (nx != 0 || ny != 0 || nz != 0) { // removes the K=0 case
arr = new double[4];
arr[0] = 2.0 * M_PI * nx / BOX_LENGTH;
arr[1] = 2.0 * M_PI * ny / BOX_LENGTH;
arr[2] = 2.0 * M_PI * nz / BOX_Z_LENGTH;
// k_entry[3] will be the Fourier coefficient exp(-K^2 / (4*alpha)) / K^2, where K^2, or kx^2 + ky^2 + kz^2
tmp_k2 = arr[0] * arr[0] + arr[1] * arr[1] + arr[2] * arr[2];
arr[3] = exp(tmp_k2 * alpha_inv_4) / tmp_k2;
// placing the 4*pi/V here allows for smaller number of multiplications and divisions later on
// half_factor accounts for double weighting of Fourier coefficients along the nx=0 plane
half_factor = (nx == 0) ? 0.5 : 1.0;
arr[3] *= half_factor * four_pi_volume_ek;
K_VECTORS.push_back(arr);
}
}
}
}
ASSERT(NUM_K_VECTORS == (int)K_VECTORS.size(), "NUMBER OF K VECTORS NOT MATCHING.");
return;
}
void SPCEHamiltonian::initialize_rho_k_values_table() {
RHO_K_VALUES.clear();
dcomplex *column, column_sum;
int NUM_TOTAL_PARTICLES = WATERS.size() + IONS.size();
for (unsigned int k = 0; k < K_VECTORS.size(); k++) {
column = new dcomplex [NUM_TOTAL_PARTICLES + 2];
column_sum = dcomplex(0.0, 0.0);
for (int w = 0; w < NUM_TOTAL_PARTICLES; w++) {
column[w] = partial_rho(w, K_VECTORS[k]);
column_sum += column[w];
}
column[NUM_TOTAL_PARTICLES] = column_sum;
RHO_K_VALUES.push_back(column);
}
return;
}
void SPCEHamiltonian::initialize_exp_kr_cache_tables() {
for (int i = 0; i < 3; i++) {
if (exp_kr_O[i] != NULL)
delete [] exp_kr_O[i];
if (exp_kr_H1[i] != NULL)
delete [] exp_kr_H1[i];
if (exp_kr_H2[i] != NULL)
delete [] exp_kr_H2[i];
if (exp_kr_ion[i] != NULL)
delete [] exp_kr_ion[i];
}
int tmp_n;
for (int i = 0; i < 3; i++) {
tmp_n = (i < 2) ? EWALD_NXY : EWALD_NZ;
exp_kr_O[i] = new dcomplex [2 * tmp_n + 1];
exp_kr_H1[i] = new dcomplex [2 * tmp_n + 1];
exp_kr_H2[i] = new dcomplex [2 * tmp_n + 1];
exp_kr_ion[i] = new dcomplex [2 * tmp_n + 1];
}
for (int i = 0; i < 3; i++) {
tmp_n = (i < 2) ? EWALD_NXY : EWALD_NZ;
exp_kr_O[i][tmp_n] = exp_kr_H1[i][tmp_n] = exp_kr_H2[i][tmp_n] = exp_kr_ion[i][tmp_n] = PCONSTANTS::COMPLEX_ONE;
}
return;
}
dcomplex SPCEHamiltonian::partial_rho(int index, double * k_coords) {
double q, *coords;
dcomplex part_rho(0.0, 0.0);
if (index < (int)WATERS.size()) {
for (int atom = 0; atom < 9; atom += 3) {
coords = WATERS[index]->coords;
q = (atom == 0) ? Water::Q_O : Water::Q_H;
part_rho += q * exp(dcomplex(0.0, k_coords[0] * coords[atom] + k_coords[1] * coords[atom + 1] + k_coords[2] * coords[atom + 2]));
}
} else {
index -= WATERS.size();
coords = IONS[index]->coords;
part_rho = IONS[index]->charge * exp(dcomplex(0.0, k_coords[0] * coords[0] + k_coords[1] * coords[1] + k_coords[2] * coords[2]));
}
return part_rho;
}
double SPCEHamiltonian::total_ewald_energy() {
double ewald_energy = 0.0;
int NUM_TOTAL_PARTICLES = WATERS.size() + IONS.size();
for (int k = 0; k < 725; k++)
ewald_energy += norm(RHO_K_VALUES[k][NUM_TOTAL_PARTICLES]) * K_VECTORS[k][3];
return ewald_energy;
}
double SPCEHamiltonian::ewald_diff(int index) {
return (index < (int)WATERS.size()) ? ewald_diff_water(index) : ewald_diff_ion(index);
}
double SPCEHamiltonian::ewald_diff_water(int water_index) {
double sum_of_ewald_diffs = 0.0, old_pk2;
dcomplex *column, tmp_x_O, tmp_y_O, tmp_x_H1, tmp_y_H1, tmp_x_H2, tmp_y_H2;
int k = 0, NUM_TOTAL_PARTICLES = WATERS.size() + IONS.size();
set_exp_kr_table_for_water(water_index);
for (int nx = 0; nx <= EWALD_NXY; nx++) {
tmp_x_O = Water::Q_O * exp_kr_O[0][nx];
tmp_x_H1 = Water::Q_H * exp_kr_H1[0][nx];
tmp_x_H2 = Water::Q_H * exp_kr_H2[0][nx];
for (int ny = 0; ny <= 2 * EWALD_NXY; ny++) {
tmp_y_O = tmp_x_O * exp_kr_O[1][ny];
tmp_y_H1 = tmp_x_H1 * exp_kr_H1[1][ny];
tmp_y_H2 = tmp_x_H2 * exp_kr_H2[1][ny];
for (int nz = 0; nz <= 2 * EWALD_NZ; nz++) {
if (nx != 0 || ny != EWALD_NXY || nz != EWALD_NZ) {
column = RHO_K_VALUES[k];
old_pk2 = norm(column[NUM_TOTAL_PARTICLES]);
// save old rho(K, R)
// calculate and save new rho(K, R)
// update total rho to rho(K, R)_new - rho(K, R)_old
column[NUM_TOTAL_PARTICLES + 1] = column[water_index];
column[water_index] = tmp_y_O * exp_kr_O[2][nz] + tmp_y_H1 * exp_kr_H1[2][nz] + tmp_y_H2 * exp_kr_H2[2][nz];
column[NUM_TOTAL_PARTICLES] += column[water_index] - column[NUM_TOTAL_PARTICLES + 1];
sum_of_ewald_diffs += (norm(column[NUM_TOTAL_PARTICLES]) - old_pk2) * K_VECTORS[k][3];
k++;
}
}
}
}
return sum_of_ewald_diffs;
}
double SPCEHamiltonian::ewald_diff_ion(int index) {
int k = 0, ion_index = index - WATERS.size(), NUM_TOTAL_PARTICLES = WATERS.size() + IONS.size();
double sum_of_ewald_diffs = 0.0, old_pk2;
dcomplex *column, tmp_x_ion, tmp_y_ion;
set_exp_kr_table_for_ion(ion_index);
for (int nx = 0; nx <= EWALD_NXY; nx++) {
tmp_x_ion = IONS[ion_index]->charge * exp_kr_ion[0][nx];
for (int ny = 0; ny <= 2 * EWALD_NXY; ny++) {
tmp_y_ion = tmp_x_ion * exp_kr_ion[1][ny];
for (int nz = 0; nz <= 2 * EWALD_NZ; nz++) {
if (nx != 0 || ny != EWALD_NXY || nz != EWALD_NZ) {
column = RHO_K_VALUES[k];
old_pk2 = norm(column[NUM_TOTAL_PARTICLES]);
// save old rho(K, R)
// calculate and save new rho(K, R)
// update total rho to rho(K, R)_new - rho(K, R)_old
column[NUM_TOTAL_PARTICLES + 1] = column[index];
column[index] = tmp_y_ion * exp_kr_ion[2][nz];
column[NUM_TOTAL_PARTICLES] += column[index] - column[NUM_TOTAL_PARTICLES + 1];
sum_of_ewald_diffs += (norm(column[NUM_TOTAL_PARTICLES]) - old_pk2) * K_VECTORS[k][3];
k++;
}
}
}
}
return sum_of_ewald_diffs;
}
void SPCEHamiltonian::set_exp_kr_table_for_water(int water_index) {
double *coords = WATERS[water_index]->coords;
int tmp_n, tmp_m, tmp_o;
for (int i = 0; i < 3; i++) {
tmp_o = (i < 2) ? EWALD_NXY : EWALD_NZ;
tmp_n = tmp_o + 1;
tmp_m = tmp_o - 1;
exp_kr_O[i][tmp_n] = exp(dcomplex(0.0, K_VECTORS[K_111_INDEX][i] * coords[i]));
exp_kr_H1[i][tmp_n] = exp(dcomplex(0.0, K_VECTORS[K_111_INDEX][i] * coords[i + 3]));
exp_kr_H2[i][tmp_n] = exp(dcomplex(0.0, K_VECTORS[K_111_INDEX][i] * coords[i + 6]));
exp_kr_O[i][tmp_m] = PCONSTANTS::COMPLEX_ONE / exp_kr_O[i][tmp_n];
exp_kr_H1[i][tmp_m] = PCONSTANTS::COMPLEX_ONE / exp_kr_H1[i][tmp_n];
exp_kr_H2[i][tmp_m] = PCONSTANTS::COMPLEX_ONE / exp_kr_H2[i][tmp_n];
for (int j = 2; j <= tmp_o; j++) {
exp_kr_O[i][tmp_o + j] = exp_kr_O[i][tmp_m + j] * exp_kr_O[i][tmp_n];
exp_kr_O[i][tmp_o - j] = exp_kr_O[i][tmp_n - j] * exp_kr_O[i][tmp_m];
exp_kr_H1[i][tmp_o + j] = exp_kr_H1[i][tmp_m + j] * exp_kr_H1[i][tmp_n];
exp_kr_H1[i][tmp_o - j] = exp_kr_H1[i][tmp_n - j] * exp_kr_H1[i][tmp_m];
exp_kr_H2[i][tmp_o + j] = exp_kr_H2[i][tmp_m + j] * exp_kr_H2[i][tmp_n];
exp_kr_H2[i][tmp_o - j] = exp_kr_H2[i][tmp_n - j] * exp_kr_H2[i][tmp_m];
}
}
return;
}
void SPCEHamiltonian::set_exp_kr_table_for_ion(int ion_index) {
int tmp_n, tmp_m, tmp_o;
double *coords = IONS[ion_index]->coords;
for (int i = 0; i < 3; i++) {
tmp_o = (i < 2) ? EWALD_NXY : EWALD_NZ;
tmp_n = tmp_o + 1;
tmp_m = tmp_o - 1;
exp_kr_ion[i][tmp_n] = exp(dcomplex(0.0, K_VECTORS[K_111_INDEX][i] * coords[i]));
exp_kr_ion[i][tmp_m] = PCONSTANTS::COMPLEX_ONE / exp_kr_ion[i][tmp_n];
for (int j = 2; j <= tmp_o; j++) {
exp_kr_ion[i][tmp_o + j] = exp_kr_ion[i][tmp_m + j] * exp_kr_ion[i][tmp_n];
exp_kr_ion[i][tmp_o - j] = exp_kr_ion[i][tmp_n - j] * exp_kr_ion[i][tmp_m];
}
}
return;
}
| true |
d6b8f40b296454d3e6d20e1a53fc22f0831f96b6 | C++ | magnusl/fuzzengine | /test/variables.cpp | UTF-8 | 1,100 | 2.90625 | 3 | [] | no_license | #include <gtest\gtest.h>
#include <fuzzengine\parser.h>
#include <sstream>
using namespace fuzzer::parser;
static std::shared_ptr<fuzzer::parser::Expression>
ParseExpression(const char * Expression)
{
std::stringstream str;
str << Expression;
fuzzer::parser::Tokenizer token(str);
fuzzer::parser::Parser parser;
return parser.ParseExpression(token);
}
TEST(Reference, VariableReference)
{
std::shared_ptr<fuzzer::parser::Expression> exp;
ASSERT_NO_THROW(exp = ParseExpression("$variable"));
ASSERT_EQ(Expression::EXP_REFERENCE, exp->GetType());
Reference * ref = (Reference *) exp.get();
EXPECT_STRCASEEQ("variable", ref->_name.c_str());
}
TEST(Reference, PropertyAccess)
{
std::shared_ptr<fuzzer::parser::Expression> exp;
ASSERT_NO_THROW(exp = ParseExpression("$variable.length"));
ASSERT_EQ(Expression::EXP_PROP_ACCESS, exp->GetType());
PropertyAccess * ref = (PropertyAccess *) exp.get();
EXPECT_STRCASEEQ("variable", ref->_name.c_str());
EXPECT_STRCASEEQ("length", ref->_propname.c_str());
} | true |
814e6be884925314ef8b5b922651aa183c57084a | C++ | LarsIngo/VR | /VR/Scene.cpp | UTF-8 | 1,630 | 2.875 | 3 | [] | no_license | #include "Scene.hpp"
#include "DxHelp.hpp"
#include "Material.hpp"
Scene::Scene(ID3D11Device* pDevice, ID3D11DeviceContext* pDeviceContext)
{
mpDevice = pDevice;
mpDeviceContext = pDeviceContext;
mpSkybox = nullptr;
}
Scene::~Scene()
{
}
void Scene::SortBackToFront(const glm::vec3& cameraPosition, const glm::vec3& cameraFrontDirection)
{
if (mEntityList.size() > 1) mQuickSort(mEntityList.data(), 0, mEntityList.size() - 1, cameraPosition, cameraFrontDirection);
}
void Scene::mQuickSort(Entity* arr, int left, int right, const glm::vec3& cameraPosition, const glm::vec3& cameraFrontDirection)
{
/* http://www.algolist.net/Algorithms/Sorting/Quicksort */
int i = left, j = right;
Entity tmp;
Entity pivot = arr[(left + right) / 2];
/* partition */
while (i <= j) {
while (mCompare(arr[i], pivot, cameraPosition, cameraFrontDirection))
i++;
while (mCompare(pivot, arr[j], cameraPosition, cameraFrontDirection))
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
mQuickSort(arr, left, j, cameraPosition, cameraFrontDirection);
if (i < right)
mQuickSort(arr, i, right, cameraPosition, cameraFrontDirection);
}
bool Scene::mCompare(const Entity& i, const Entity& j, const glm::vec3& cameraPosition, const glm::vec3& cameraFrontDirection)
{
return glm::dot(i.mPosition - cameraPosition, cameraFrontDirection) > glm::dot(j.mPosition - cameraPosition, cameraFrontDirection);
}
| true |
fe0057dad61f5ef0bc1fbdcdccefd8c0e03558a8 | C++ | Diptiman1/BuzzFizz | /BizzFuzz.cpp | UTF-8 | 1,035 | 3.640625 | 4 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
bool prime(int a)
{
bool flag = true;
int i = 0;
for (i = 2; i <= (a / 2); i++)
{
if ((a % i) == 0) flag = false;
}
return flag;
}
int main()
{
int n,i=0;
int num1 = 0, num2 = 1;
int curr,next,prev;
cout << "Enter the number of Fibonacci number " << endl;
cin >> n;
if (n == 1) { cout << num1 << endl; }
else if (n == 2) { cout << num1 << " " << num2; }
else
{
cout << num1 << " " << num2;
prev = num1;
next = num2;
for (i = 1; i < n; i++)
{
//prev = next;
curr = next + prev;
prev = next;
next = curr;
cout << " " << curr;
}
}
cout << endl;
if ((curr % 3) == 0)
{
cout << "Buzz" << endl;
if ((curr % 5) == 0)
{
cout << "Fizz" << endl;
cout << "FizzBuzz" << endl;
}
}
else if ((curr % 5) == 0)
{
cout << "Fizz" << endl;
}
else if(prime(curr)) cout << "BuzzFizz" << endl;
else cout << curr << endl;
//cout << endl;
} | true |
20df8f3fa925172c663b95eb98df0d4a4345e695 | C++ | TheFebrin/UNIVERSITY | /Algorithms and Data Structures/Pracownia 6/main.cpp | UTF-8 | 3,101 | 2.546875 | 3 | [] | no_license | /* Dejwo to ziomal ®© */
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector <int> vi;
typedef vector <ll> vl;
typedef pair <int, int> pi;
typedef pair <ll, ll> pl;
typedef tuple <int, int, int> ti;
typedef vector < pl > vpl;
typedef vector < pi > vpi;
typedef vector < ti > vti;
typedef complex < double > cd;
typedef vector < cd > vcd;
//double t = clock();
//cout << (clock() - t) / CLOCKS_PER_SEC <<endl;
bool debug = false;
#define deb if(debug)
#define pb push_back
#define FOR0(n) for(int i = 0; i < n; i++)
#define FOR0j(n) for(int j = 0; j < n; j++)
#define FOR1(n) for(int i = 1; i <= n; i++)
#define FOR1j(n) for(int j = 1; j <= n; j++)
#define FOR_REV(n) for(int i = n - 1; i >= 0 ; i--)
#define FOR_REVj(n) for(int j = n - 1; j >= 0 ; j--)
#define SIZE (3 * 1e5 + 42)
#define MAX (1000000 + 42)
#define MOD (1000000000 + 7)
#define PI 3.14159265
void fft(vcd &V, bool invert) {
int n = (int)V.size();
int j = 0;
FOR1( n - 1 ) {
int bit = n >> 1;
while( j & bit ){
j ^= bit;
bit >>= 1;
}
j ^= bit;
if (i < j) swap(V[ i ], V[ j ]);
}
for (int len = 2; len <= n; len <<= 1) {
double ang = 2 * PI / len;
if( invert ) ang *= -1;
cd wlen(cos(ang), sin(ang));
for (int i = 0; i < n; i += len) {
cd w( 1 );
for (int j = 0; j < len / 2; j++) {
cd u = V[ i + j ], v = V[ i + j + len / 2 ] * w;
V[ i + j ] = u + v;
V[ i + j + len / 2 ] = u - v;
w *= wlen;
}
}
}
if( invert ) {
for(auto & x : V){
x /= n;
}
}
}
vi multiply(vi A, vi B) {
vcd Va(A.begin(), A.end());
vcd Vb(B.begin(), B.end());
int n = 1;
while (n < (int)A.size() + (int)B.size())
n <<= 1;
Va.resize(n);
Vb.resize(n);
fft(Va, false);
fft(Vb, false);
FOR0( n ) Va[i] *= Vb[i];
fft(Va, true);
vi res( n );
FOR0( n ) res[ i ] = round(Va[ i ].real());
return res;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
// freopen("input.in","r",stdin);
// freopen("output.txt","w",stdout);
int n;
cin >> n;
int arr[ n ];
vi T;
unordered_map < int, int > cnt;
FOR0( n ) {
cin >> arr[ i ];
cnt[ arr[ i ] ] ++;
}
int mx = *max_element( arr, arr + n );
bool fft_arr[ mx + 1 ];
FOR0( mx + 1 ) fft_arr[ i ] = 0;
FOR0( n ) fft_arr[ arr[ i ] ] = 1;
FOR1( mx ) T.pb( fft_arr[ i ] );
reverse( T.begin(), T.end() );
auto ans = multiply(T, T);
// cout << endl;
// for(auto t: ans) cout << t << " ";
// cout << endl << endl;
int no = mx * 2;
for(auto t: ans){
if( t != 0 ) cnt[ no ] += t / 2;
no --;
}
vpi final;
for( auto m: cnt ) if( m.second ) final.pb( {m.first, m.second} );
final.pb( {0, 1} );
sort( final.begin(), final.end() );
for(auto f: final) cout << f.first << " " << f.second << "\n";
return 0;
}
| true |
8cf9a5b2a679a40092bb7b6bb93f16149310d46c | C++ | Zuvo007/InternSearchWorkspace | /sourcecodes/LinkedList/1.CreateLL.cpp | UTF-8 | 884 | 3.78125 | 4 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node * next;
};
node * MakingNode(int data)
{
node *newnode=new node();
newnode->data=data;
newnode->next=NULL;
return newnode;
}
node * InsertingNode(node *head,int data)
{
if(head==nullptr)
{
head=MakingNode(data);
}
else{
node *temp=MakingNode(data);
temp->next=head;
head=temp;
}
return head;
}
void print(node *head)
{
while(head!=nullptr)
{
cout<<head->data<<"->";
head=head->next;
}
cout<<"null"<<endl;
}
int main()
{
node *head=nullptr;
head=InsertingNode(head,2);
head=InsertingNode(head,3);
head=InsertingNode(head,4);
head=InsertingNode(head,5);
head=InsertingNode(head,6);
cout<<"LINKED LIST CREATION OUTPUT"<<endl;
print(head);
}
| true |
3acb2418e515cc36368f9edf5031b99b96c90c97 | C++ | PYChih/CppPrimer | /ch03_strings_vectors_and_arrays/exercise_3_32.cpp | UTF-8 | 703 | 3.453125 | 3 | [] | no_license | // g++ exercise_3_32.cpp && ./a.out
/*
- 練習3.32: 將你在前面定義的陣列拷貝到另一個陣列。使用vector改寫你的程式。
*/
#include<iostream>
#include <string>
#include <vector>
#include <cctype>
using std::string;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
int main(){
int index_array[10];
int copy_index_array[10];
vector<int> index_vector;
vector<int> copy_index_vector;
for (int i=0; i<10; ++i){
index_array[i] = i;
index_vector.push_back(i);
}
for (auto i : index_array){
cout<<i<<" ";
copy_index_array[i] = i;
}
copy_index_vector = index_vector;
cout<<endl;
return 0;
} | true |
0b01468e804f77e4412c44acc3deb5adca404ac6 | C++ | kcmao/leetcode_exercise | /c_coding_exercise/c_coding_exercise/05_替换空格/ReplaceSpaces.cpp | GB18030 | 3,124 | 3.9375 | 4 | [] | no_license | // 5滻ո
// Ŀʵһַеÿո滻"%20"롰We are happy.
// We%20are%20happy.
#include <stdio.h>
#include <string.h>
//====================Ŀ=====================
/*length Ϊַstrڻַstrʵʳ*/
void ReplaceBlank(char str[], int length)
{
if (str == nullptr || length <= 0)
{
return;
}
/*ԭʼַ*/
int originLength = 0;
int number_blank = 0;
int i = 0;
while (str[i] != '\0')
{
originLength++;
if (str[i] == ' ')
{
number_blank++;
}
i++;
}
/*newlength Ϊ滻ոַµij*/
int newLength = originLength + number_blank * 2;
/*鳤Ȳ*/
if (newLength > length)
{
return;
}
/*ʹָӺǰ*/
int indexOrigin = originLength;
int indexNew = newLength;
while (indexOrigin >= 0 && indexNew > indexOrigin)
{
if (str[indexOrigin] != ' ')
{
str[indexNew--] = str[indexOrigin--];
}
else
{
str[indexNew--] = '0';
str[indexNew--] = '2';
str[indexNew--] = '%';
indexOrigin--;
}
}
}
// ====================Դ====================
//㲻ΪʲôһҪconst
void Test(const char* testName, char str[], int length, const char expected[])
{
if (testName != nullptr)
printf("%s begins: ", testName);
ReplaceBlank(str, length);
if (expected == nullptr && str == nullptr)
printf("passed.\n");
else if (expected == nullptr && str != nullptr)
printf("failed.\n");
else if (strcmp(str, expected) == 0)
printf("passed.\n");
else
printf("failed.\n");
}
// ոھм
void Test1()
{
const int length = 100;
char str[length] = "hello world";
Test("Test1", str, length, "hello%20world");
}
// ոھӿͷ
void Test2()
{
const int length = 100;
char str[length] = " helloworld";
Test("Test2", str, length, "%20helloworld");
}
// ոھĩβ
void Test3()
{
const int length = 100;
char str[length] = "helloworld ";
Test("Test3", str, length, "helloworld%20");
}
// ո
void Test4()
{
const int length = 100;
char str[length] = "hello world";
Test("Test4", str, length, "hello%20%20world");
}
// nullptr
void Test5()
{
Test("Test5", nullptr, 0, nullptr);
}
// Ϊյַ
void Test6()
{
const int length = 100;
char str[length] = "";
Test("Test6", str, length, "");
}
//Ϊһոַ
void Test7()
{
const int length = 100;
char str[length] = " ";
Test("Test7", str, length, "%20");
}
// ַûпո
void Test8()
{
const int length = 100;
char str[length] = "helloworld";
Test("Test8", str, length, "helloworld");
}
// ַȫǿո
void Test9()
{
const int length = 100;
char str[length] = " ";
Test("Test9", str, length, "%20%20%20");
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9();
int mkc = getchar();
return 0;
} | true |
6bc1146c25122a65c5f9e8b2895aae49779ea2e2 | C++ | JoshKing56/BB8-Breadboard-Computer | /Arduino Code/main/clock.cpp | UTF-8 | 2,530 | 3 | 3 | [
"MIT"
] | permissive |
#include "Arduino.h"
#include "pins.h"
#include "clock.h"
void main_clock_ISR()
{
static byte system_clock_flag = 0;
// Toggle Pin
//
if (system_clock_flag == 1) { //If pin on.
PORTB &= SYSTEM_PORT_MASK_LOW; //Turn pin off.
system_clock_flag = 0;
}
else {
PORTB |= SYSTEM_PORT_MASK_HIGH;
system_clock_flag = 1;
}
}
void display_clock_ISR()
{
static byte display_clock_flag = 0;
// Toggle Pin
//
if (display_clock_flag == 1) { //If pin on.
PORTB &= DISPLAY_PORT_MASK_LOW; //Turn pin off.
display_clock_flag = 0;
}
else {
PORTB |= DISPLAY_PORT_MASK_HIGH;
display_clock_flag = 1;
}
}
void attach_timers() {
pinMode(SYSTEM_CLOCK_PIN, OUTPUT);
pinMode(DISPLAY_CLOCK_PIN, OUTPUT);
Timer1.initialize(1000000 / DEFAULT_SYSTEM_FREQ); // set a timer of length 10 microseconds (or 100,000Hz)
Timer1.attachInterrupt( main_clock_ISR ); // attach the service routine here
Timer3.initialize(1000000 / DEFAULT_DISPLAY_FREQ);
Timer3.attachInterrupt(display_clock_ISR);
}
void set_system_frequency() {
int freq;
switch (frequency_method()) {
case 1: freq = reading_to_freq(read_ocl_register()); break;
case 2: freq = reading_to_freq(read_analog_input()); break;
case 3: freq = reading_to_freq(read_com_port()); break;
default: freq = DEFAULT_SYSTEM_FREQ;
}
Timer1.setPeriod(1000000 / freq);
}
byte frequency_method() {
if (digitalRead(FREQ_METHOD_SWITCH1) && digitalRead(FREQ_METHOD_SWITCH2)) { //both high
return (1);
}
else if ((digitalRead(FREQ_METHOD_SWITCH1) && !digitalRead(FREQ_METHOD_SWITCH2)) || (!digitalRead(FREQ_METHOD_SWITCH1) && digitalRead(FREQ_METHOD_SWITCH2))) { //different
return (2);
}
else if (!digitalRead(FREQ_METHOD_SWITCH1) && !FREQ_METHOD_SWITCH2) { // both low
return (3);
}
else return (4); //error
}
uint16_t read_ocl_register() {
byte i, val;
uint16_t reg_reading = 0;
for (i = 0; i < 14; i++) {
val = digitalRead(OCL_REGISTER_PIN_0 + i); //read input
reg_reading += val << i; // shift value based on pin being read
}
return (reg_reading);
}
uint16_t read_analog_input() {
return (analogRead(ANALOG_POT_PIN) << 4); //map 10 bit reading to 14 bit
}
uint16_t read_com_port() {
}
int reading_to_freq(uint16_t reading) {
if (reading < 256) //slow reading
return (map(reading, 1, 256, 0.2, 50)); //steps of 0.2ish Hz
else //fast reading
return (map(reading, 257, 16384, 50, 250000)); // steps of 15.6ish hz
}
| true |
aa2e9551e7bc7cc2852b4a6c9dbe9a94a3d3b2a3 | C++ | jimmylin1017/UVA | /11005 - Cheapest Base.cpp | UTF-8 | 991 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int dollar[36];
bool min_base[36+1];
int cheap_count(int num, int base)
{
int money = 0;
for(;num > 0;num/=base)
money+=dollar[num%base];
return money;
}
int main()
{
int a,b;
cin>>a;
for(int kase = 1;kase <= a;kase++)
{
memset(dollar,0,sizeof(dollar));
memset(min_base,0,sizeof(min_base));
cout<<"Case "<<kase<<":\n";
for(int i=0;i<36;i++)
{
cin>>dollar[i];
}
cin>>b;
while(b--)
{
int num,min;
cin>>num;
cout<<"Cheapest base(s) for number "<<num<<":";
min = cheap_count(num,2);
min_base[2] = 1;
for(int i=3;i<=36;i++)
{
int temp = cheap_count(num,i);
if(min > temp)
{
min = temp;
memset(min_base,0,sizeof(min_base));
min_base[i] = 1;
}
else if(min == temp)
min_base[i] = 1;
}
for(int i=1;i<=36;i++)
{
if(min_base[i])
{
cout<<" "<<i;
}
}
cout<<endl;
}
if(kase != a)
cout<<endl;
}
return 0;
} | true |
7e6b49633f661835db93dd87a74d4a871b823682 | C++ | netanelsu/college_cpp_projects | /build stack/stack.h | UTF-8 | 643 | 3.328125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Stack {
private:
class Node {
private:
int value;
Node* next;
friend class Stack;
public:
Node(int value) :value(value), next(NULL) {};
Node(const Node &);
void print() { cout << value << endl; };
};
Node* head;
int size;
public:
Stack() :head(NULL), size(0){};
Stack(const Stack&);
~Stack();
const Stack& operator =(const Stack&);
const Stack& operator+=(int);
Stack& operator-=(int);
bool operator==(const Stack&);
bool operator!=(const Stack&);
Stack& operator!();
void PrintStack();
friend ostream& operator<<(ostream& , Stack& );
}; | true |
a1906f757258725b048c68c0da89972d89bec9aa | C++ | bullocgr/cs162 | /assignments/assignment3/Apartment.cpp | UTF-8 | 797 | 3.09375 | 3 | [] | no_license | #include "Apartment.hpp"
using namespace std;
//accessors
Tenants_other& Apartment::get_tenants(int i) {return tenants[i];}
Apartment::Apartment() {
this->property_val = ((rand()%200)+400)*100;
this->num_tenants = (rand()%7)+4;
this->name = "Apartment";
this->rent = ((rand()%500) + 100);
this->tenants = new Tenants_other[this->num_tenants];
for (int i = 0; i < num_tenants; i++) {
this->tenants[i] = Tenants_other();
}
}
Apartment::Apartment(const Apartment& copy) {
this->property_val = copy.property_val;
this->name = copy.name;
this->num_tenants = copy.num_tenants;
this->rent = copy.rent;
for(int i = 0; i < this->num_tenants; i++) {
this->tenants[i] = copy.tenants[i];
}
}
Apartment::~Apartment() {
if(tenants != NULL) delete [] tenants;
} | true |
4dc97586f12cbaf671590ea10553b2e050d4a748 | C++ | taehee-kim-dev/Problem-solving | /Baekjoon/Function/1065.cpp | UTF-8 | 666 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
bool HanCheck(int n);
int main_1065(void) {
int n;
cin >> n;
int hanCount = 0;
for (int i = 1; i <= n; i++) {
if (HanCheck(i) == true)
hanCount++;
}
cout << hanCount << endl;
return 0;
}
bool HanCheck(int n) {
string nString = to_string(n);
vector<int> vec;
for (int i = 0; i < int(nString.length()); i++) {
vec.push_back(int(nString[i]) - 48);
}
bool hanCheck = true;
if (n > 10) {
int d = vec[1] - vec[0];
for (int i = 2; i < int(vec.size()); i++) {
if (vec[i] - vec[i - 1] != d) {
hanCheck = false;
break;
}
}
}
return hanCheck;
} | true |
b51495baf8b41c9ed1329713937b842fb8a39275 | C++ | abidshaikh1941/Trie_Dictionary | /TrieDictionary.cpp | UTF-8 | 1,471 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include "Trie.cpp"
using namespace std;
int main()
{
std::cout << "Dictionary using Trie Datastructure \n";
fstream data;
string s;
data.open("C:\\Users\\Adil\\Desktop\\Trie\\data.txt",ios::in);
if (!data)
{
cout << "Error while loading file";
return -1;
}
int totalWords{};
Dictionary german;
while (!data.eof())
{
data >> s;
german.insert(s, s + "_meaning");
totalWords++;
}
cout << totalWords<<"\n";
while (1)
{
cout << "1. search word\n";
cout << "2. remove word\n";
cout << "3. exit app\n";
int choice{1};
cin >> choice;
switch(choice)
{
case 1:
{ string s;
cout << "Enter a word to search - ";
cin >> s;
german.search(s);
break;
}
case 2:
{ string s;
cout << "Enter a word to remove - ";
cin >> s;
german.search(s);
break;
}
case 3:
{
exit(0);
break;
}
default:
cout << "Enter correct option\n";
}
}
}
| true |
03180fd5e14ab8e91f2b86b968d7ebf5a3e0579e | C++ | thakurutkarsh22/Hacktober-Open | /SelectionSort.cpp | UTF-8 | 919 | 3.84375 | 4 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
//you can directly use stl swap for swapping it will make your code more functioning
/*void swap(int &a, int &b)
{ int temp;
temp = a;
a = b;
b = temp;
} */
void display(int *arr, int n) {
for(int i = 0; i<n; i++)
{ cout << arr[i] << " ";
}
cout << endl;
}
void SelectionSort(int *arr, int n) {
int i, j, i_min;
for(i = 0; i<n-1; i++)
{ i_min = i;
for(j = i+1; j<n; j++)
{ if(arr[j] < arr[i_min])
i_min = j;
swap(arr[i], arr[i_min]);
}
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int array[n];
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> array[i];
}
SelectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
| true |
194071bc86d018fd4bbde35862f735e5e4b4ed9d | C++ | beawar/HBStats | /label.cpp | UTF-8 | 879 | 2.609375 | 3 | [] | no_license | #include "label.h"
#include <QRect>
#include <QFont>
Label::Label(QWidget *parent, Qt::WindowFlags f){
QLabel(parent, f);
}
Label::Label(const QString &text, QWidget *parent, Qt::WindowFlags f){
QLabel(text, parent, f);
}
void Label::resizeEvent(QResizeEvent* event){
QLabel::resizeEvent(event);
QFont font = this->font();
QRect cRect = this->contentsRect();
if( !this->text().isEmpty() ){
int fontSize = 1;
bool resized = false;
while(!resized)
{
QFont f(font);
f.setPixelSize(fontSize);
QRect r = QFontMetrics(f).boundingRect(this->text());
if(r.height() <= cRect.height() && r.width() <= cRect.width() )
fontSize++;
else
resized = true;
}
font.setPixelSize(fontSize);
this->setFont(font);
}
}
| true |
87674574a5340e14d29ea9ed6fa7e64d192ebccb | C++ | masonium/sketchbook | /dpad/src/image.h | UTF-8 | 2,544 | 3.171875 | 3 | [] | no_license | #ifndef IMAGE_H__
#define IMAGE_H__
class LPD8806x8;
/**
* Representation of given as input. The public interface to all color-based
* methods assume that colors are 8-bit per component. Any conversions are done
* internally and transparently.
*/
struct color
{
union
{
uint8_t grb[3];
struct
{
uint8_t g, r, b;
} v;
};
};
struct Palette
{
Palette(uint16_t size) : _size(size) {
_c = (color*)malloc(_size * sizeof(color));
}
~Palette() {
free(_c);
}
/**
* Set the color specified for the given index.
*/
void set_color(uint8_t index, uint8_t r, uint8_t g, uint8_t b);
void set_color(uint8_t index, uint32_t rgb) {
set_color(index, (rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff);
}
void set_color_hsv(uint8_t index, uint8_t hue, uint8_t saturation, uint8_t value);
/**
* Rotate the first 'num' colors in the palette.
*/
void cycle_colors(uint16_t num) {
color c = _c[0];
for (uint16_t i = 0; i < num - 1; ++i)
_c[i] = _c[i+1];
_c[num-1] = c;
}
public:
color* _c;
private:
friend class LPD8806x8;
uint16_t _size;
};
class StripImage
{
private:
uint8_t _c[128];
uint8_t _size;
friend class LPD8806x8;
public:
StripImage() : _size(128) { }
StripImage(uint8_t size) : _size(size) { }
void fill( uint8_t index ) {
for (uint8_t i = 0; i < _size; ++i) {
_c[i] = 0;
}
}
void set_color( uint8_t x, uint8_t color_index) {
_c[x] = color_index;
}
};
class Image
{
public:
uint8_t _c[8][128];
friend class LPD8806x8;
public:
Image() {
}
void fill( uint8_t index ) {
for (uint8_t i = 0; i < 8; ++i)
for (uint8_t j = 0; j < 128; ++j)
_c[i][j] = index;
}
void set_color( uint8_t x, uint8_t y, uint8_t color_index) {
uint8_t r, c;
rowcol(x, y, r, c);
_c[r][c] = color_index;
}
uint8_t get_color( uint8_t x, uint8_t y ) const {
uint8_t r, c;
rowcol(x, y, r, c);
return _c[r][c];
}
uint8_t& operator() (uint8_t x, uint8_t y) {
uint8_t r, c;
rowcol(x, y, r, c);
return _c[r][c];
}
uint8_t operator() (uint8_t x, uint8_t y) const {
uint8_t s, r;
rowcol(x, y, s, r);
return _c[s][r];
}
void rowcol(uint8_t x, uint8_t y, uint8_t& s, uint8_t& r) const {
bool h = x >= 16;
s = x % 4 + h * 4;
uint8_t m;
if (h)
{
m = (x - s - 12) / 4;
}
else
{
m = (12 + s - x) / 4;
}
r = m * 32;
r += m % 2 == 0 ? y : 31 - y;
}
};
#endif
| true |
e9dcd904c4ffff9054fd640e8222cc94b6fb76e1 | C++ | RedwanNewaz/ActiveSLAM | /hexTree/coverage.cpp | UTF-8 | 2,004 | 3.078125 | 3 | [] | no_license | #include "coverage.h"
coverage::coverage()
{
//manually defined area constraint
area_constraint.area_x=area_constraint.area_y=7;
area_constraint.sampling_length=0.5;
// initialze local map
local_map=new MST;
reset_local_map_with_heading(UP);
update_global_map(local_map,0);
}
int coverage::area_coverage_direction(float robot[2], int dir){
// int mapIndex=get_map_index(robot);
//// int current_robot_direction=global_map.path[mapIndex].heading;
int current_robot_direction=local_map->heading;
int nex_direction;
if(dir==-1)
nex_direction=compliment_direction(current_robot_direction);
else
nex_direction=dir;
//update global map information
local_map->covered_index++;
float max_index_for_path=area_constraint.area_y/area_constraint.sampling_length;
local_map->coverage=max_index_for_path/(1+local_map->covered_index);
// ROS_INFO_STREAM(" coverage "<<local_map->coverage);
local_map->heading=nex_direction;
if(local_map->coverage<1){
nex_direction=RIGHT;
if(local_map->dir==UP)
reset_local_map_with_heading( DOWN );
else
reset_local_map_with_heading(UP);
}
return nex_direction;
}
void coverage::reset_local_map_with_heading(direction x ){
local_map->coverage=local_map->covered_index=local_map->heading=0;
if(x==DOWN)
local_map->heading=3;
local_map->dir=x;
}
int coverage::compliment_direction(int dir){
switch (dir) {
case 0:return 5;
case 1:return 4;
case 2:return 3;
case 3:return 2;
case 4:return 1;
case 5:return 0;
}
}
void coverage::update_global_map(MST *node,int index){
// global_map.index=index;
// global_map.path[index]=node;
}
int coverage::get_map_index(float robot[2]){
float power=0;
for(int j=0;j<2;j++)
power+=pow(robot[j],2);
float distance=sqrt(power);
return distance/(4*area_constraint.sampling_length);
}
| true |
b801237df19e7bd7918a8da0cab11cebcf4902a8 | C++ | superweaver/leetcode | /p1442.cc | UTF-8 | 1,501 | 3.484375 | 3 | [] | no_license | #include "common.h"
class Solution {
public:
int countTriplets(vector<int>& arr) {
int result = 0;
int n = arr.size();
/*
unordered_map<int, vector<int>> cache; // xor value -> index of first element to get xor value
int x = 0;
cache[x] = {-1};
for (int i = 0; i < n; ++i) {
x ^= arr[i];
if (cache.count(x)) {
for (auto pre : cache[x]) {
result += i - pre - 1;
}
cache[x].push_back(i);
} else {
cache[x] = {i};
}
}
*/
unordered_map<int, pair<int, int>> cache; // xor value -> (sum of prefix, count of previous index)
cache[0] = {-1, 1};
int x = 0;
for (int i = 0; i < n; ++i) {
x ^= arr[i];
if (cache.count(x)) {
// pick any of previous index then arr[pre + 1, ... i] has xor value = 0
// divide into two non-empty parts, then they have same xor value
result += (i - 1) * cache[x].second - cache[x].first;
cache[x].first += i;
cache[x].second++;
} else {
cache[x] = {i, 1};
}
}
return result;
}
};
int main() {
vector<int> arr = {2,3,1,6,7}; // 4
//arr.assign(5, 1); // 10
arr = {7,11,12,9,5,2,7,17,22}; // 8
Solution s;
cout << s.countTriplets(arr) << endl;
return 0;
}
| true |
66c30ce3fe27d5f52e4323b6aca2a65fe2f69da6 | C++ | kunwar-vikrant/Hackerrank- | /aggressive_cows.cpp | UTF-8 | 815 | 2.875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include<algorithm>
using namespace std;
bool check(int mid, int arr[], int c, int size_arr){
int cows = 1, pos = arr[0];
for(int i = 1; i < size_arr; i++){
if(arr[i]-pos >= mid){
pos = arr[i];
cows++;
if(cows == c){
return true;
}
}
}
return false;
}
int main() {
// your code goes here
int n,c;
cin>>n>>c;
int arr[n];
for(int i = 0; i < n; i++){
cin>>arr[i];
}
// cout<<endl;
sort(arr, arr+n);
int start = 0, end = arr[n-1], max_len = -1;
while(start < end){
int mid = (start+end)/2;
if(check(mid, arr, c, n)){ // 4 9 19 20 30
if(mid > max_len)
max_len = mid;
start = mid+1;
}
else{
end = mid;
}
}
cout<<max_len<<endl;
return 0;
} | true |
979825e834d6ec8f2ca8ec950532ffa18bfaf5f4 | C++ | runru1030/PS | /1000-9999/2920.cpp | UTF-8 | 280 | 2.828125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
string s[3]={"ascending", "descending", "mixed"};
int a, b;
int i;
for(i=1;i<9;i++){
cin>>a;
if(a==b-1||a==b+1||i==1){
b=a;
}
else{
cout<<s[2];
return 0;
};
}
if(a==1)cout<<s[1];
else cout<<s[0];
}
| true |
b84f4f6d40a0f6766c965d726473bffa09cb66e3 | C++ | houdini22/impulse-dataset | /src/main.cpp | UTF-8 | 5,610 | 2.75 | 3 | [] | no_license | #include "src/Impulse/Dataset/include.h"
#include <sys/stat.h>
using namespace Impulse::Dataset;
using namespace std::chrono;
void test1() {
auto start = std::chrono::system_clock::now();
// build dataset from csv...
DatasetBuilder::CSVBuilder builder("/home/hud/projekty/impulse-ml-dataset/src/data/data.csv");
Dataset dataset = builder.build();
dataset.out();
// slice dataset to input and output set
DatasetModifier::DatasetSlicer datasetSlicer(dataset);
datasetSlicer.addInputColumn(0);
datasetSlicer.addInputColumn(1);
datasetSlicer.addInputColumn(2);
datasetSlicer.addOutputColumn(3);
SlicedDataset slicedDataset = datasetSlicer.slice();
Dataset input = slicedDataset.input;
Dataset output = slicedDataset.output;
// fill missing data by mean of fields
DatasetModifier::Modifier::MissingData missingDataModifier(input);
missingDataModifier.setModificationType("mean");
missingDataModifier.applyToColumn(1);
missingDataModifier.applyToColumn(2);
input.out();
// create categories
DatasetModifier::Modifier::Category categoryModifier(input);
categoryModifier.applyToColumn(0);
input.out();
// modify "Yes" and "No" to numbers
DatasetModifier::Modifier::Callback callbackModifier(output);
callbackModifier.setCallback([](T_String oldValue) -> T_String {
if (oldValue.find("Yes") != T_String::npos) {
return "1";
}
return "0";
});
callbackModifier.applyToColumn(0);
output.out();
// scale all input
DatasetModifier::Modifier::ZScoresScaling zScoresModifier(input);
zScoresModifier.apply();
input.out();
DatasetModifier::DatasetSplitter datasetSplitter(slicedDataset);
SplittedDataset splittedDataset = datasetSplitter.split(0.8);
splittedDataset.primary.input.out();
splittedDataset.primary.output.out();
splittedDataset.secondary.input.out();
splittedDataset.secondary.output.out();
auto end = std::chrono::system_clock::now();
long elapsed_seconds = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
std::cout << elapsed_seconds << std::endl;
DatasetExporter::CSVExporter exporter(input);
exporter.exportTo("/home/hud/projekty/impulse-ml-dataset/src/data/export.csv");
}
void test2() {
DatasetBuilder::CSVBuilder builder("/home/hud/projekty/impulse-ml-dataset-private/src/data/data2.csv");
Dataset dataset = builder.build();
dataset.out();
DatasetModifier::Modifier::CategoryId categoryId(dataset);
categoryId.applyToColumn(0);
categoryId.applyToColumn(1);
dataset.out();
categoryId.saveColumnMapTo(0, "/home/hud/projekty/impulse-ml-dataset-private/src/data/map0.json");
categoryId.saveColumnMapTo(1, "/home/hud/projekty/impulse-ml-dataset-private/src/data/map1.json");
}
void test3() {
DatasetBuilder::CSVBuilder builder("/home/hud/projekty/impulse-ml-dataset/src/data/data3.csv");
Dataset dataset = builder.build();
dataset.out();
DatasetModifier::Modifier::MinMaxScaling minMaxScaling(dataset);
minMaxScaling.apply();
dataset.out();
}
void test4() {
DatasetBuilder::CSVBuilder builder("/home/hud/projekty/impulse-ml-dataset/src/data/data3.csv");
Dataset dataset = builder.build();
std::cout << dataset.exportToEigen() << std::endl;
}
void test5() {
DatasetBuilder::CSVBuilder builder("/home/hud/projekty/impulse-ml-dataset-private/src/data/data2.csv");
Dataset dataset = builder.build();
dataset.out();
dataset.changeOrdering({0, 1, 2});
DatasetModifier::Modifier::CategoryId modifier(dataset);
modifier.applyToColumn(0);
modifier.applyToColumn(1);
dataset.out(50);
}
void run(int argc, char *argv[]) {
std::vector<T_String> params(argv, argv + argc);
DatasetBuilder::CSVBuilder builder(params.at(1));
Dataset dataset = builder.build();
dataset.changeOrdering(
{std::stoi(params.at(3).c_str()), std::stoi(params.at(4).c_str()), std::stoi(params.at(5).c_str())});
if (params.at(2) == "1") {
dataset.removeSample(0);
}
DatasetModifier::Modifier::CategoryId modifier(dataset);
#pragma omp parallel for
for(int i = 0; i < 2; i++) {
modifier.applyToColumn(i);
}
DatasetExporter::CSVExporter exporter(dataset);
T_String outPath(params.at(6).c_str());
mkdir(outPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
T_String indexPath(outPath);
indexPath.append("index.csv");
exporter.exportTo(indexPath);
T_String map0Path(outPath);
map0Path.append("map0.json");
modifier.saveColumnMapTo(0, map0Path);
T_String map1Path(outPath);
map1Path.append("map1.json");
modifier.saveColumnMapTo(1, map1Path);
T_String statsPath(outPath);
statsPath.append("statistics.json");
nlohmann::json statsJSON;
int numOfRatings = 0;
DatasetData samples = dataset.getSamples();
for (auto &sample : samples) {
if(!std::isnan(sample->getColumnToDouble(2))) {
numOfRatings++;
}
}
statsJSON["subjectsCount"] = modifier.getItemsCount(0);
statsJSON["usersCount"] = modifier.getItemsCount(1);
statsJSON["ratingsCount"] = numOfRatings;
statsJSON["density"] = (double) numOfRatings / (modifier.getItemsCount(0) * modifier.getItemsCount(1));
std::ofstream out(statsPath);
out << statsJSON.dump();
out.close();
}
int main(int argc, char *argv[]) {
//test1();
//test2();
//test3();
//test4();
//test5();
run(argc, argv);
return 0;
} | true |
f20df60ecf17491c30580b3b55106ab85640934e | C++ | Mstoned/leetcode-solutions | /test/204_count_primes_test.cpp | UTF-8 | 962 | 3.140625 | 3 | [] | no_license | #include "204_count_primes.h"
#include "gtest/gtest.h"
using namespace std;
CountPrimesSolution *solution204 = new CountPrimesSolution;
TEST(CountPrimes, Test0) {
int actual = solution204->countPrimes(10);
int expected = 4;
EXPECT_EQ(actual, expected);
}
TEST(CountPrimes, Test1) {
int actual = solution204->countPrimes(100);
int expected = 25;
EXPECT_EQ(actual, expected);
}
TEST(CountPrimes, Test2) {
int actual = solution204->countPrimes(10000);
int expected = 1229;
EXPECT_EQ(actual, expected);
}
TEST(CountPrimes, Test3) {
int actual = solution204->countPrimes(100000);
int expected = 9592;
EXPECT_EQ(actual, expected);
}
TEST(CountPrimes, Test4) {
int actual = solution204->countPrimes(200000);
int expected = 17984;
EXPECT_EQ(actual, expected);
}
TEST(CountPrimes, Test5) {
int actual = solution204->countPrimes(2000000);
int expected = 148933;
EXPECT_EQ(actual, expected);
} | true |
a3b68d3ae65f4c24bbe29b5eaefe53266c073c3f | C++ | RickyLiu0w0/Snake | /Snake/food.cpp | UTF-8 | 367 | 2.984375 | 3 | [] | no_license | #include "food.h"
Food::Food(int hight, int width, int weight)
{
srand(static_cast<unsigned int>(time(nullptr)));
//要取得[a,b)的随机整数,使用(rand() % (b-a))+ a;
foo = new FoodUnit((rand()% (hight - 2 - 2)) + 2, (rand()% (width - 2 - 2)) + 2 , weight);//随机生成食物单元
}
FoodUnit * Food::getFoodUnit() const
{
return foo;
}
| true |
068fd2176d19a324672d61d93f7178730104e559 | C++ | vcato/guisolver | /scenestatetaggedvalue.cpp | UTF-8 | 36,910 | 2.671875 | 3 | [] | no_license | #include "scenestatetaggedvalue.hpp"
#include <sstream>
#include "indicesof.hpp"
#include "contains.hpp"
#include "nextunusedname.hpp"
#include "taggedvalueio.hpp"
#include "pointlink.hpp"
using std::string;
using std::cerr;
using std::istringstream;
using std::ostringstream;
using XYZChannels = SceneState::XYZChannelsRef;
using TransformSolveFlags = SceneState::TransformSolveFlags;
using TransformExpressions = SceneState::TransformExpressions;
static void
resolveMarkerNameConflicts(
SceneState &scene_state,
MarkerNameMap &marker_name_map
)
{
for (MarkerIndex marker_index : indicesOf(scene_state.markers())) {
std::string &name = scene_state.marker(marker_index).name;
if (name[0] == '$') {
const string &old_name = name.substr(1);
name = nextUnusedName(markerNames(scene_state), old_name + "_");
marker_name_map[old_name] = name;
}
}
}
static string withoutTrailingNumber(const string &arg)
{
string::const_iterator i = arg.end();
while (i != arg.begin() && isdigit(*(i-1))) --i;
return string(arg.begin(), i);
}
static void
resolveBodyNameConflicts(BodyIndex body_index, SceneState &scene_state)
{
std::string &name = scene_state.body(body_index).name;
if (name[0] == '$') {
string prefix = withoutTrailingNumber(name.substr(1));
name = nextUnusedName(bodyNames(scene_state), prefix);
}
}
static NumericValue
childNumericValueOr(
const TaggedValue &tagged_value,
const TaggedValue::Tag &child_name,
NumericValue default_value
)
{
return findNumericValue(tagged_value, child_name).valueOr(default_value);
}
static int intValueOr(const TaggedValue &tv, int /*default_value*/)
{
const NumericValue *numeric_ptr = tv.value.maybeNumeric();
if (!numeric_ptr) {
assert(false); // not implemented
}
else {
NumericValue nv = *numeric_ptr;
if (int(nv) != nv) {
assert(false); // not implemented
}
return int(nv);
}
}
static int
childIntValueOr(
const TaggedValue &tagged_value,
const string &tag,
int default_value
)
{
const TaggedValue *child_ptr = findChild(tagged_value, tag);
if (child_ptr) {
return intValueOr(*child_ptr, default_value);
}
return default_value;
}
static bool
childBoolValueOr(
const TaggedValue &tagged_value,
const TaggedValue::Tag &child_name,
bool default_value
)
{
return findBoolValue(tagged_value, child_name).valueOr(default_value);
}
static string
childStringValueOr(
const TaggedValue &tagged_value,
const TaggedValue::Tag &child_name,
const string &default_value
)
{
return findStringValue(tagged_value, child_name).valueOr(default_value);
}
static SceneState::XYZ xyzStateFromTaggedValue(const TaggedValue &tagged_value)
{
NumericValue x = childNumericValueOr(tagged_value, "x", 0);
NumericValue y = childNumericValueOr(tagged_value, "y", 0);
NumericValue z = childNumericValueOr(tagged_value, "z", 0);
return {x,y,z};
}
static Expression
expressionFor(
const TaggedValue &xyz_tagged_value,
const string &child_name
)
{
const TaggedValue *child_ptr = findChild(xyz_tagged_value, child_name);
if (!child_ptr) {
return "";
}
return childStringValueOr(*child_ptr, "expression", "");
}
static SceneState::XYZExpressions
xyzExpressionsFromTaggedValue(const TaggedValue &tagged_value)
{
Expression x = expressionFor(tagged_value, "x");
Expression y = expressionFor(tagged_value, "y");
Expression z = expressionFor(tagged_value, "z");
return {x,y,z};
}
static TransformState
makeTransformFromTaggedValue(const TaggedValue &tagged_value)
{
TransformState result;
const TaggedValue *translation_ptr = findChild(tagged_value, "translation");
if (!translation_ptr) {
assert(false);
}
const TaggedValue *rotation_ptr = findChild(tagged_value, "rotation");
if (!rotation_ptr) {
assert(false);
}
const auto default_scale = SceneState::Transform::defaultScale();
result.translation = xyzStateFromTaggedValue(*translation_ptr);
result.rotation = xyzStateFromTaggedValue(*rotation_ptr);
result.scale = findNumericValue(tagged_value, "scale").valueOr(default_scale);
return result;
}
static bool
solveFlagFor(
const TaggedValue &xyz_tagged_value,
const string &child_name,
bool default_value
)
{
const TaggedValue *child_ptr = findChild(xyz_tagged_value, child_name);
if (!child_ptr) {
assert(false); // not implemented
}
return childBoolValueOr(*child_ptr, "solve", default_value);
}
static SceneState::XYZSolveFlags
makeXYZSolveFlagsFromChildTaggedValue(
const TaggedValue &child, bool default_value
)
{
SceneState::XYZSolveFlags flags;
flags.x = solveFlagFor(child, "x", default_value);
flags.y = solveFlagFor(child, "y", default_value);
flags.z = solveFlagFor(child, "z", default_value);
return flags;
}
static SceneState::XYZSolveFlags
childXYZSolveFlagsOr(const TaggedValue *scale_ptr, bool default_value)
{
if (scale_ptr) {
return makeXYZSolveFlagsFromChildTaggedValue(*scale_ptr, default_value);
}
else {
return {default_value, default_value, default_value};
}
}
static SceneState::XYZSolveFlags
makeXYZSolveFlagsFromTaggedValue(
const TaggedValue &tagged_value,
const string &tag,
bool default_value
)
{
return childXYZSolveFlagsOr(findChild(tagged_value, tag), default_value);
}
static SceneState::XYZExpressions
makeXYZExpressionsFromTaggedValue(
const TaggedValue &tagged_value,
const string &child_name
)
{
const TaggedValue *child_ptr = findChild(tagged_value, child_name);
if (!child_ptr) {
assert(false); // not implemented
}
return xyzExpressionsFromTaggedValue(*child_ptr);
}
static TransformSolveFlags
makeSolveFlagsFromTaggedValue(const TaggedValue &tagged_value)
{
TransformSolveFlags result;
result.translation =
makeXYZSolveFlagsFromTaggedValue(
tagged_value, "translation", /*default_value*/true
);
result.rotation =
makeXYZSolveFlagsFromTaggedValue(
tagged_value, "rotation", /*default_value*/true
);
return result;
}
static TransformExpressions
makeExpressionsFromTaggedValue(const TaggedValue &tagged_value)
{
TransformExpressions result;
result.translation =
makeXYZExpressionsFromTaggedValue(tagged_value, "translation");
result.rotation =
makeXYZExpressionsFromTaggedValue(tagged_value, "rotation");
result.scale = expressionFor(tagged_value, "scale");
return result;
}
static SceneState::XYZ
xyzValueOr(const TaggedValue &tv, const SceneState::XYZ &default_value)
{
SceneState::XYZ result;
result.x = childNumericValueOr(tv, "x", default_value.x);
result.y = childNumericValueOr(tv, "y", default_value.y);
result.z = childNumericValueOr(tv, "z", default_value.z);
return result;
}
static bool
markerNameExists(
const SceneState::Marker::Name &name,
const SceneState &scene_state
)
{
return contains(markerNames(scene_state), name);
}
static bool
bodyNameExists(
const SceneState::Marker::Name &name,
const SceneState &scene_state
)
{
return contains(bodyNames(scene_state), name);
}
static MarkerIndex
createMarkerFromTaggedValueWithoutResolvingConflicts(
SceneState &scene_state,
const TaggedValue &tagged_value,
Optional<BodyIndex> maybe_parent_index
)
{
Optional<StringValue> maybe_old_name =
findStringValue(tagged_value, "name");
Optional<StringValue> maybe_name;
if (maybe_old_name) {
if (!markerNameExists(*maybe_old_name, scene_state)) {
maybe_name = maybe_old_name;
}
else {
maybe_name = "$" + *maybe_old_name;
}
}
MarkerIndex marker_index = scene_state.createMarker(maybe_parent_index);
if (maybe_name) {
scene_state.marker(marker_index).name = *maybe_name;
}
const TaggedValue *position_ptr = findChild(tagged_value, "position");
if (position_ptr) {
scene_state.marker(marker_index).position =
xyzStateFromTaggedValue(*position_ptr);
scene_state.marker(marker_index).position_expressions =
xyzExpressionsFromTaggedValue(*position_ptr);
}
return marker_index;
}
namespace {
struct BodyTaggedValue {
Optional<BodyIndex> maybe_body_index;
TaggedValue child_tagged_value;
};
}
static void
addMarkerTaggedValues(
const TaggedValue &tagged_value,
Optional<BodyIndex> maybe_parent_index,
vector<BodyTaggedValue> &body_tagged_values
)
{
for (auto &child_tagged_value : tagged_value.children) {
if (child_tagged_value.tag == "Marker") {
body_tagged_values.push_back({maybe_parent_index, child_tagged_value});
}
}
}
static void
createMarkersFromTaggedValues(
const vector<BodyTaggedValue> &body_tagged_values,
SceneState &scene_state
)
{
for (const BodyTaggedValue &body_tagged_value : body_tagged_values) {
const TaggedValue &child_tagged_value =
body_tagged_value.child_tagged_value;
if (child_tagged_value.tag == "Marker") {
const Optional<BodyIndex> maybe_parent_index =
body_tagged_value.maybe_body_index;
createMarkerFromTaggedValueWithoutResolvingConflicts(
scene_state,
child_tagged_value,
maybe_parent_index
);
}
}
}
static SceneState::XYZ
childXYZValueOr(
const TaggedValue *child_ptr,
const SceneState::XYZ &default_value
)
{
if (child_ptr) {
return xyzValueOr(*child_ptr, default_value);
}
return default_value;
}
static SceneState::XYZ
tagXYZValueOr(
const TaggedValue &tagged_value,
const string &tag,
const SceneState::XYZ &default_value
)
{
return childXYZValueOr(findChild(tagged_value, tag), default_value);
}
static void
fillBoxStateFromTaggedValue(
SceneState::Box &box_state,
const TaggedValue &box_tagged_value
)
{
{
const TaggedValue *scale_ptr = findChild(box_tagged_value, "scale");
const SceneState::XYZ default_scale = {1,1,1};
if (scale_ptr) {
box_state.scale = xyzValueOr(*scale_ptr, default_scale);
box_state.scale_expressions =
xyzExpressionsFromTaggedValue(*scale_ptr);
}
else {
SceneState::XYZ box_scale;
box_scale.x =
childNumericValueOr(box_tagged_value, "scale_x", default_scale.x);
box_scale.y =
childNumericValueOr(box_tagged_value, "scale_y", default_scale.y);
box_scale.z =
childNumericValueOr(box_tagged_value, "scale_z", default_scale.z);
box_state.scale = box_scale;
}
}
box_state.center = tagXYZValueOr(box_tagged_value, "center", {0,0,0});
box_state.center_expressions =
makeXYZExpressionsFromTaggedValue(box_tagged_value, "center");
}
static void
fillLineStateFromTaggedValue(
SceneState::Line &line_state,
const TaggedValue &line_tagged_value
)
{
line_state.start = tagXYZValueOr(line_tagged_value, "start", {0,0,0});
line_state.end = tagXYZValueOr(line_tagged_value, "end", {1,0,0});
}
static bool
isValidPositionIndex(int v, int n_positions)
{
if (v < 0) {
assert(false); // not implemented
}
if (v >= n_positions) {
assert(false); // not implemented
}
return true;
}
static bool
isValidTriangle(int v1, int v2, int v3, int n_positions)
{
return
isValidPositionIndex(v1, n_positions) &&
isValidPositionIndex(v2, n_positions) &&
isValidPositionIndex(v3, n_positions) &&
v1 != v2 &&
v2 != v3 &&
v3 != v1;
}
static void
fillMeshStateFromTaggedValue(
SceneState::Mesh &mesh_state,
const TaggedValue &mesh_tagged_value
)
{
const TaggedValue *scale_ptr = findChild(mesh_tagged_value, "scale");
mesh_state.scale = childXYZValueOr(scale_ptr, {1,1,1});
mesh_state.scale_solve_flags = childXYZSolveFlagsOr(scale_ptr, false);
mesh_state.center = tagXYZValueOr(mesh_tagged_value, "center", {0,0,0});
const TaggedValue *positions_ptr = findChild(mesh_tagged_value, "positions");
auto &positions_state = mesh_state.shape.positions;
if (positions_ptr) {
for (auto &child_tagged_value : positions_ptr->children) {
auto &index_string = child_tagged_value.tag;
istringstream stream(index_string);
int index = 0;
stream >> index;
if (!stream) {
assert(false); // not implemented
}
if (index < 0) {
assert(false); // not implemented
}
if (int(positions_state.size()) <= index) {
positions_state.resize(index + 1, SceneState::XYZ{0,0,0});
}
positions_state[index] = xyzValueOr(child_tagged_value, {0,0,0});
}
}
for (auto &child_tagged_value : mesh_tagged_value.children) {
if (child_tagged_value.tag == "Triangle") {
int v1 = childIntValueOr(child_tagged_value, "vertex1", 0);
int v2 = childIntValueOr(child_tagged_value, "vertex2", 0);
int v3 = childIntValueOr(child_tagged_value, "vertex3", 0);
int n_positions = positions_state.size();
if (!isValidTriangle(v1, v2, v3, n_positions)) {
assert(false); // not implemented
}
mesh_state.shape.triangles.emplace_back(v1, v2, v3);
}
}
}
static const StringValue &
mappedMarkerName(
const StringValue &marker_name,
const MarkerNameMap &marker_name_map
)
{
auto iter = marker_name_map.find(marker_name);
if (iter == marker_name_map.end()) {
return marker_name;
}
else {
return iter->second;
}
}
static void
setDistanceErrorMarkerMember(
SceneState::DistanceError &distance_error_state,
DistanceErrorPoint point,
const StringValue &marker_name,
const MarkerNameMap &marker_name_map,
SceneState &result
)
{
void (SceneState::DistanceError::* member_ptr)(Optional<Marker>) = 0;
switch (point) {
case DistanceErrorPoint::start:
member_ptr = &SceneState::DistanceError::setStart;
break;
case DistanceErrorPoint::end:
member_ptr = &SceneState::DistanceError::setEnd;
break;
}
StringValue mapped_marker_name =
mappedMarkerName(marker_name, marker_name_map);
(distance_error_state.*member_ptr)(
maybeMarker(findMarkerWithName(result, mapped_marker_name))
);
}
static void
scanPointRef(
const std::string &tag,
SceneState::DistanceError &distance_error_state,
DistanceErrorPoint point,
const TaggedValue &tagged_value,
const MarkerNameMap &marker_name_map,
SceneState &result // rename this
)
{
const TaggedValue::Tag &child_name = tag;
const TaggedValue *child_ptr = findChild(tagged_value, child_name);
if (!child_ptr) {
return;
}
const TaggedValue &child = *child_ptr;
const PrimaryValue &value = child.value;
if (const StringValue *string_ptr = value.maybeString()) {
const StringValue &marker_name = *string_ptr;
setDistanceErrorMarkerMember(
distance_error_state, point, marker_name, marker_name_map, result
);
}
else if (const EnumerationValue *enum_ptr = value.maybeEnumeration()) {
if (enum_ptr->name == "MarkerRef") {
Optional<StringValue> maybe_marker_name =
findStringValue(child, "marker_name");
if (maybe_marker_name) {
setDistanceErrorMarkerMember(
distance_error_state,
point,
*maybe_marker_name,
marker_name_map,
result
);
}
}
else if (enum_ptr->name == "BodyMeshPositionRef") {
Optional<StringValue> maybe_body_name =
findStringValue(child, "body_name");
Optional<NumericValue> maybe_mesh_index =
findNumericValue(child, "mesh_index");
Optional<NumericValue> maybe_position_index =
findNumericValue(child, "position_index");
if (maybe_body_name && maybe_mesh_index && maybe_position_index) {
Optional<BodyIndex> maybe_body_index =
findBodyWithName(result, *maybe_body_name);
if (maybe_body_index) {
switch (point) {
case DistanceErrorPoint::start:
distance_error_state.setStart(
Body(*maybe_body_index)
.mesh(*maybe_mesh_index)
.position(*maybe_position_index)
);
break;
case DistanceErrorPoint::end:
distance_error_state.setEnd(
Body(*maybe_body_index)
.mesh(*maybe_mesh_index)
.position(*maybe_position_index)
);
break;
}
}
}
}
}
}
static void
createDistanceErrorFromTaggedValue(
SceneState &result,
const Optional<BodyIndex> maybe_body_index,
const TaggedValue &tagged_value,
const MarkerNameMap &marker_name_map
)
{
DistanceErrorIndex index = result.createDistanceError(maybe_body_index);
SceneState::DistanceError &distance_error_state =
result.distance_errors[index];
scanPointRef(
"start",
distance_error_state,
DistanceErrorPoint::start,
tagged_value,
marker_name_map,
result
);
scanPointRef(
"end",
distance_error_state,
DistanceErrorPoint::end,
tagged_value,
marker_name_map,
result
);
{
auto tag = "desired_distance";
auto optional_value = findNumericValue(tagged_value, tag);
if (optional_value) {
distance_error_state.desired_distance = *optional_value;
}
}
{
auto tag = "weight";
auto optional_value = findNumericValue(tagged_value, tag);
if (optional_value) {
distance_error_state.weight = *optional_value;
}
}
}
static void
buildDistanceErrorTaggedValues(
const TaggedValue &tagged_value,
Optional<BodyIndex> maybe_body_index,
vector<BodyTaggedValue> &body_tagged_values
)
{
for (auto &child_tagged_value : tagged_value.children) {
if (child_tagged_value.tag == "DistanceError") {
body_tagged_values.push_back({maybe_body_index, child_tagged_value});
}
}
}
static void
createDistanceErrorsFromTaggedValues(
const vector<BodyTaggedValue> &body_tagged_values,
SceneState &result,
const MarkerNameMap &marker_name_map
)
{
for (auto &body_tagged_value : body_tagged_values) {
if (body_tagged_value.child_tagged_value.tag == "DistanceError") {
Optional<BodyIndex> maybe_body_index =
body_tagged_value.maybe_body_index;
const TaggedValue &child_tagged_value =
body_tagged_value.child_tagged_value;
createDistanceErrorFromTaggedValue(
result, maybe_body_index, child_tagged_value, marker_name_map
);
}
}
}
static void
createChildBodiesInSceneState(
SceneState &result,
const TaggedValue &tagged_value,
const Optional<BodyIndex> maybe_parent_index,
vector<BodyTaggedValue> &body_tagged_values
);
static BodyIndex
createBodyInSceneState(
SceneState &result,
const TaggedValue &tagged_value,
const Optional<BodyIndex> maybe_parent_index
)
{
Optional<StringValue> maybe_old_name =
findStringValue(tagged_value, "name");
Optional<StringValue> maybe_name;
if (maybe_old_name) {
if (!bodyNameExists(*maybe_old_name, result)) {
maybe_name = maybe_old_name;
}
else {
maybe_name = "$" + *maybe_old_name;
}
}
BodyIndex body_index = result.createBody(maybe_parent_index);
SceneState::Body &body_state = result.body(body_index);
if (maybe_name) {
body_state.name = *maybe_name;
}
setAll(body_state.solve_flags, true);
body_state.transform =
makeTransformFromTaggedValue(tagged_value);
body_state.solve_flags =
makeSolveFlagsFromTaggedValue(tagged_value);
body_state.expressions =
makeExpressionsFromTaggedValue(tagged_value);
for (auto &child : tagged_value.children) {
if (child.tag == "Box") {
const TaggedValue &box_tagged_value = child;
BoxIndex box_index = body_state.createBox();
SceneState::Box &box_state = body_state.boxes[box_index];
fillBoxStateFromTaggedValue(box_state, box_tagged_value);
}
}
for (auto &child : tagged_value.children) {
if (child.tag == "Line") {
const TaggedValue &line_tagged_value = child;
LineIndex line_index = body_state.createLine();
SceneState::Line &line_state = body_state.lines[line_index];
fillLineStateFromTaggedValue(line_state, line_tagged_value);
}
}
for (auto &child : tagged_value.children) {
if (child.tag == "Mesh") {
const TaggedValue &mesh_tagged_value = child;
MeshIndex mesh_index = body_state.createMesh(SceneState::MeshShape());
SceneState::Mesh &mesh_state = body_state.meshes[mesh_index];
fillMeshStateFromTaggedValue(mesh_state, mesh_tagged_value);
}
}
return body_index;
}
static BodyIndex
createBodyFromTaggedValueWithoutResolvingConflicts(
SceneState &result,
const TaggedValue &tagged_value,
const Optional<BodyIndex> maybe_parent_index,
vector<BodyTaggedValue> &body_tagged_values
)
{
BodyIndex body_index =
createBodyInSceneState(result, tagged_value, maybe_parent_index);
createChildBodiesInSceneState(
result, tagged_value, body_index, body_tagged_values
);
addMarkerTaggedValues(tagged_value, body_index, body_tagged_values);
buildDistanceErrorTaggedValues(
tagged_value, body_index, body_tagged_values
);
return body_index;
}
static void
resolveBodyNameConflictsOnBranch(
SceneState &scene_state,
Optional<BodyIndex> maybe_body_index
)
{
struct Visitor {
SceneState &scene_state;
void visitBody(BodyIndex body_index) const
{
resolveBodyNameConflicts(body_index, scene_state);
}
void visitMarker(MarkerIndex) const
{
}
} visitor = {scene_state};
forEachBranchIndexInPreOrder(
maybe_body_index,
scene_state,
visitor
);
}
static void
createFromBodyTaggedValues(
const vector<BodyTaggedValue> &body_tagged_values,
SceneState &result,
MarkerNameMap &marker_name_map,
Optional<BodyIndex> maybe_body_index
)
{
createMarkersFromTaggedValues(body_tagged_values, result);
resolveMarkerNameConflicts(result, marker_name_map);
createDistanceErrorsFromTaggedValues(
body_tagged_values, result, marker_name_map
);
resolveBodyNameConflictsOnBranch(result, maybe_body_index);
}
BodyIndex
createBodyFromTaggedValue(
SceneState &result,
const TaggedValue &tagged_value,
const Optional<BodyIndex> maybe_parent_index,
MarkerNameMap &marker_name_map
)
{
vector<BodyTaggedValue> body_tagged_values;
BodyIndex body_index =
createBodyFromTaggedValueWithoutResolvingConflicts(
result,
tagged_value,
maybe_parent_index,
body_tagged_values
);
createFromBodyTaggedValues(
body_tagged_values, result, marker_name_map, body_index
);
return body_index;
}
static void
createChildBodiesInSceneState(
SceneState &result,
const TaggedValue &tagged_value,
const Optional<BodyIndex> maybe_parent_index,
vector<BodyTaggedValue> &body_tagged_values
)
{
for (auto &child_tagged_value : tagged_value.children) {
if (child_tagged_value.tag == "Transform") {
createBodyFromTaggedValueWithoutResolvingConflicts(
result,
child_tagged_value,
maybe_parent_index,
body_tagged_values
);
}
}
}
static void
createVariableFromTaggedValue(
SceneState &result, const TaggedValue &tagged_value
)
{
Optional<StringValue> maybe_old_name =
findStringValue(tagged_value, "name");
VariableIndex variable_index = result.createVariable();
if (maybe_old_name) {
result.variables[variable_index].name = *maybe_old_name;
}
result.variables[variable_index].value =
findNumericValue(tagged_value, "value").valueOr(0);
}
static void
createVariablesInSceneState(SceneState &result, const TaggedValue &tagged_value)
{
for (auto &child_tagged_value : tagged_value.children) {
if (child_tagged_value.tag == "Variable") {
createVariableFromTaggedValue(result, child_tagged_value);
}
}
}
SceneState makeSceneStateFromTaggedValue(const TaggedValue &tagged_value)
{
SceneState result;
Optional<BodyIndex> maybe_parent_index;
MarkerNameMap marker_name_map;
vector<BodyTaggedValue> body_tagged_values;
createChildBodiesInSceneState(
result, tagged_value, maybe_parent_index,
body_tagged_values
);
addMarkerTaggedValues(tagged_value, maybe_parent_index, body_tagged_values);
buildDistanceErrorTaggedValues(
tagged_value, maybe_parent_index, body_tagged_values
);
createFromBodyTaggedValues(body_tagged_values, result, marker_name_map, {});
createVariablesInSceneState(
result, tagged_value
);
return result;
}
static TaggedValue &
create(TaggedValue &parent, const string &tag, bool value)
{
parent.children.push_back(TaggedValue(tag));
TaggedValue &result = parent.children.back();
if (value) {
result.value = EnumerationValue{"true"};
}
else {
result.value = EnumerationValue{"false"};
}
return result;
}
static TaggedValue &create(TaggedValue &parent, const string &tag)
{
parent.children.push_back(TaggedValue(tag));
return parent.children.back();
}
static TaggedValue &
create(TaggedValue &parent, const string &tag, NumericValue value)
{
parent.children.push_back(TaggedValue(tag));
TaggedValue &result = parent.children.back();
result.value = value;
return result;
}
static TaggedValue &
create(TaggedValue &parent, const string &tag, StringValue value)
{
parent.children.push_back(TaggedValue(tag));
TaggedValue &result = parent.children.back();
result.value = value;
return result;
}
static const bool *
maybeSolveFlag(
const SceneState::XYZSolveFlags *xyz_solve_flags_ptr,
bool SceneState::XYZSolveFlags::*member_ptr
)
{
if (!xyz_solve_flags_ptr) {
return nullptr;
}
return &(xyz_solve_flags_ptr->*member_ptr);
}
static const Expression *
maybeExpression(
const SceneState::XYZExpressions *xyz_expressions_ptr,
Expression SceneState::XYZExpressions::* member_ptr
)
{
if (!xyz_expressions_ptr) {
return nullptr;
}
return &(xyz_expressions_ptr->*member_ptr);
}
static void
create2(
TaggedValue &parent,
const string &member_name,
NumericValue value,
const bool *solve_flag_ptr,
const Expression *expression_ptr
)
{
TaggedValue &tagged_value = create(parent, member_name, value);
if (solve_flag_ptr) {
create(tagged_value, "solve", *solve_flag_ptr);
}
if (expression_ptr) {
if (!expression_ptr->empty()) {
create(tagged_value, "expression", *expression_ptr);
}
}
}
static void
createXYZChildren(
TaggedValue &parent,
const SceneState::XYZ &xyz,
const SceneState::XYZSolveFlags *xyz_flags_ptr = nullptr,
const SceneState::XYZExpressions *expressions_ptr = nullptr
)
{
using Flags = SceneState::XYZSolveFlags;
using XYZExpressions = SceneState::XYZExpressions;
create2(
parent,
"x",
xyz.x,
maybeSolveFlag(xyz_flags_ptr, &Flags::x),
maybeExpression(expressions_ptr, &XYZExpressions::x)
);
create2(
parent,
"y",
xyz.y,
maybeSolveFlag(xyz_flags_ptr, &Flags::y),
maybeExpression(expressions_ptr, &XYZExpressions::y)
);
create2(
parent,
"z",
xyz.z,
maybeSolveFlag(xyz_flags_ptr, &Flags::z),
maybeExpression(expressions_ptr, &XYZExpressions::z)
);
}
static TaggedValue &
create(TaggedValue &parent, const string &tag, XYZChannels channel_state)
{
parent.children.push_back(TaggedValue(tag));
TaggedValue &result = parent.children.back();
createXYZChildren(
result,
channel_state.values,
/*solve_flags_ptr*/nullptr,
&channel_state.expressions
);
return result;
}
static TaggedValue &
create(TaggedValue &parent, const string &tag, const SceneState::XYZ &xyz_state)
{
TaggedValue &tagged_value = create(parent, tag);
createXYZChildren(tagged_value, xyz_state);
return tagged_value;
}
static bool
scaleHasDefaultState(
const TransformState &transform_state,
const TransformSolveFlags &transform_solve_flags,
const TransformExpressions &transform_expressions
)
{
if (transform_state.scale != SceneState::Transform::defaultScale()) {
return false;
}
if (transform_solve_flags.scale != TransformSolveFlags::defaultScale()) {
return false;
}
if (transform_expressions.scale != TransformExpressions::defaultScale()) {
return false;
}
return true;
}
static TaggedValue &
createTransformInTaggedValue(
TaggedValue &parent,
const SceneState::Body::Name &name,
const TransformState &transform_state,
const TransformSolveFlags &solve_flags,
const TransformExpressions &expressions
)
{
auto &transform = create(parent, "Transform");
{
auto &parent = transform;
create(parent, "name", name);
{
auto &translation = create(parent, "translation");
auto &parent = translation;
createXYZChildren(
parent,
transform_state.translation,
&solve_flags.translation,
&expressions.translation
);
}
{
auto &rotation = create(parent, "rotation");
auto &parent = rotation;
createXYZChildren(
parent,
transform_state.rotation,
&solve_flags.rotation,
&expressions.rotation
);
}
if (!scaleHasDefaultState(transform_state, solve_flags, expressions)) {
create2(
parent,
"scale",
transform_state.scale,
&solve_flags.scale,
&expressions.scale
);
}
}
return transform;
}
static TaggedValue &
createBoxInTaggedValue(TaggedValue &parent, const SceneState::Box &box_state)
{
auto &box_tagged_value = create(parent, "Box");
create(box_tagged_value, "scale", box_state.scaleChannels());
create(box_tagged_value, "center", box_state.centerChannels());
return box_tagged_value;
}
static TaggedValue &
createLineInTaggedValue(TaggedValue &parent, const SceneState::Line &line_state)
{
auto &box_tagged_value = create(parent, "Line");
create(box_tagged_value, "start", line_state.start);
create(box_tagged_value, "end", line_state.end);
return box_tagged_value;
}
static string str(int index)
{
ostringstream stream;
stream << index;
return stream.str();
}
static TaggedValue &
createMeshInTaggedValue(
TaggedValue &parent,
const SceneState::Mesh &mesh_state
)
{
auto &mesh_tagged_value = create(parent, "Mesh");
createXYZChildren(
create(mesh_tagged_value, "scale"),
mesh_state.scale,
&mesh_state.scale_solve_flags,
/*expressions_ptr*/nullptr
);
create(mesh_tagged_value, "center", mesh_state.center);
auto &positions_tagged_value = create(mesh_tagged_value, "positions");
// Create positions
for (auto index : indicesOf(mesh_state.shape.positions)) {
auto &position_tagged_value = create(positions_tagged_value, str(index));
createXYZChildren(position_tagged_value, mesh_state.shape.positions[index]);
}
// Create triangles
for (auto index : indicesOf(mesh_state.shape.triangles)) {
auto &triangle_tagged_value = create(mesh_tagged_value, "Triangle");
NumericValue v1 = mesh_state.shape.triangles[index].v1;
NumericValue v2 = mesh_state.shape.triangles[index].v2;
NumericValue v3 = mesh_state.shape.triangles[index].v3;
create(triangle_tagged_value, "vertex1", v1);
create(triangle_tagged_value, "vertex2", v2);
create(triangle_tagged_value, "vertex3", v3);
}
return mesh_tagged_value;
}
static void
createMarkerInTaggedValue(
TaggedValue &parent, const SceneState::Marker &marker_state
)
{
auto &marker = create(parent, "Marker");
create(marker, "name", marker_state.name);
create(marker, "position", marker_state.positionChannels());
}
static void
createVariableInTaggedValue(
TaggedValue &parent,
const SceneState::Variable &variable_state
)
{
auto &variable = create(parent, "Variable");
create(variable, "name", variable_state.name);
create(variable, "value", variable_state.value);
}
static void
createMarkerRef(
TaggedValue &parent, const string &tag, const string &marker_name
)
{
parent.children.push_back(TaggedValue(tag));
TaggedValue &result = parent.children.back();
result.value = EnumerationValue{"MarkerRef"};
create(result, "marker_name", marker_name);
}
static void
createBodyMeshPositionRef(
TaggedValue &parent,
const string &tag,
BodyMeshPosition body_mesh_position,
const SceneState &scene_state
)
{
parent.children.push_back(TaggedValue(tag));
TaggedValue &result = parent.children.back();
result.value = EnumerationValue{"BodyMeshPositionRef"};
BodyIndex body_index = body_mesh_position.array.body_mesh.body.index;
MeshIndex mesh_index = body_mesh_position.array.body_mesh.index;
MeshPositionIndex position_index = body_mesh_position.index;
string body_name = scene_state.body(body_index).name;
create(result, "body_name", body_name);
create(result, "mesh_index", NumericValue(mesh_index));
create(result, "position_index", NumericValue(position_index));
}
static void
createPointLink(
const PointLink &point_link,
const string &tag,
const SceneState &scene_state,
TaggedValue &parent
)
{
if (point_link.maybe_marker) {
MarkerIndex marker_index = point_link.maybe_marker->index;
auto &marker_name = scene_state.marker(marker_index).name;
createMarkerRef(parent, tag, marker_name);
}
else if (point_link.maybe_body_mesh_position) {
createBodyMeshPositionRef(
parent, tag, *point_link.maybe_body_mesh_position, scene_state
);
}
else {
assert(false); // shouldn't happen
}
}
static void
createDistanceErrorInTaggedValue(
TaggedValue &parent,
const SceneState::DistanceError &distance_error_state,
const SceneState &scene_state
)
{
auto &distance_error = create(parent, "DistanceError");
{
auto &parent = distance_error;
if (distance_error_state.hasStart()) {
const PointLink &point_link =
*distance_error_state.optional_start;
createPointLink(point_link, "start", scene_state, parent);
}
if (distance_error_state.hasEnd()) {
const PointLink &point_link =
*distance_error_state.optional_end;
createPointLink(point_link, "end", scene_state, parent);
}
create(parent, "desired_distance", distance_error_state.desired_distance);
create(parent, "weight", distance_error_state.weight);
}
}
static Optional<BodyIndex>
maybeAttachedBodyIndex(const SceneState::Marker &marker_state)
{
return marker_state.maybe_body_index;
}
static Optional<BodyIndex>
maybeAttachedBodyIndex(const SceneState::DistanceError &distance_error_state)
{
return distance_error_state.maybe_body_index;
}
static void
createChildBodiesInTaggedValue(
TaggedValue &transform,
const SceneState &scene_state,
const Optional<BodyIndex> maybe_body_index
)
{
for (BodyIndex other_body_index : indicesOf(scene_state.bodies())) {
const SceneState::Body &other_body_state =
scene_state.body(other_body_index);
if (other_body_state.maybe_parent_index == maybe_body_index) {
createBodyTaggedValue(transform, other_body_index, scene_state);
}
}
}
void
createBodyTaggedValue(
TaggedValue &parent,
BodyIndex body_index,
const SceneState &scene_state
)
{
const SceneState::Body &body_state = scene_state.body(body_index);
const TransformState &transform_state = body_state.transform;
TaggedValue &transform =
createTransformInTaggedValue(
parent,
body_state.name,
transform_state,
body_state.solve_flags,
body_state.expressions
);
for (const SceneState::Box &box_state : body_state.boxes) {
createBoxInTaggedValue(transform, box_state);
}
for (const SceneState::Line &line_state : body_state.lines) {
createLineInTaggedValue(transform, line_state);
}
for (const SceneState::Mesh &mesh_state : body_state.meshes) {
createMeshInTaggedValue(transform, mesh_state);
}
createChildBodiesInTaggedValue(transform, scene_state, body_index);
for (auto &marker_state : scene_state.markers()) {
if (maybeAttachedBodyIndex(marker_state) == body_index) {
createMarkerInTaggedValue(transform, marker_state);
}
}
for (auto &distance_error_state : scene_state.distance_errors) {
if (maybeAttachedBodyIndex(distance_error_state) == body_index) {
createDistanceErrorInTaggedValue(
transform, distance_error_state, scene_state
);
}
}
}
TaggedValue makeTaggedValueForSceneState(const SceneState &scene_state)
{
TaggedValue result("Scene");
for (
const SceneState::Variable &variable_state
: scene_state.variables
) {
createVariableInTaggedValue(result, variable_state);
}
createChildBodiesInTaggedValue(result, scene_state, /*maybe_parent_index*/{});
for (const SceneState::Marker &marker_state : scene_state.markers()) {
if (!maybeAttachedBodyIndex(marker_state)) {
createMarkerInTaggedValue(result, marker_state);
}
}
for (
const SceneState::DistanceError &distance_error_state
: scene_state.distance_errors
) {
if (!maybeAttachedBodyIndex(distance_error_state)) {
createDistanceErrorInTaggedValue(
result, distance_error_state, scene_state
);
}
}
return result;
}
| true |
682bb019f829deb63c43f014ef853b65fa247458 | C++ | pn1137/University-Administration-System | /Course.cpp | UTF-8 | 3,948 | 3.71875 | 4 | [] | no_license | /*
* Functions for Course.h
* Patrick Naugle : 18 November 2016
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include "Course.h"
#include "Student.h"
#include "Teacher.h"
using std::vector;
using std::string;
using std::cout;
using std::find;
/*
* Constructor to create a course
*/
Course::Course(string courseTitle, string courseLevel, string dept)
{
title = courseTitle;
level = courseLevel;
departmentName = dept;
}
/*
* Destructor to destroy a course
*/
Course::~Course() {}
/*
* Set a grade for a student
*/
void Course::setGrade(string studentID, double grade)
{
int position; // Index of the vector
// Find the index of the student in the vector by ID
for (position = 0; position < studentList.size(); position++)
{
if (studentID.compare(studentList[position]->getID()) == 0)
{
break; // ID matches
}
}
if (position >= studentList.size()) // Student not found
{
cout << "ERROR, Cannot set grade: Student not found.\n";
}
else // Student found
{
grades[position] = grade; // Set the grade
}
}
/*
* Add a student to the student list
*/
void Course::addStudent(Student *student)
{
studentList.push_back(student); // Append studentList with new student name
grades.push_back(0); // Append grades with initial grade for new student
}
/*
* Add a teacher to the teacher list
*/
void Course::addTeacher(Person *teacher)
{
teacherList.push_back(teacher); // Append teacherList with new teacher
}
/*
* Remove a student from the student list
*/
void Course::removeStudent(Student *student)
{
int position; // Index of the vector
// Find the index of the student in the vector
position = find(studentList.begin(), studentList.end(), student) - studentList.begin();
if (position >= studentList.size()) // Student not found
{
cout << "ERROR, Cannot remove student: Student not found.\n";
}
else // Student found
{
studentList.erase(studentList.begin() + position); // Remove student
grades.erase(grades.begin() + position); // Remove grade
}
}
/*
* Remove a teacher from the teacher list
*/
void Course::removeTeacher(Person *teacher)
{
int position; // Index of the vector
// Find the index of the teacher in the vector
position = find(teacherList.begin(), teacherList.end(), teacher) - teacherList.begin();
if (position >= teacherList.size()) // Teacher not found
{
cout << "ERROR, Cannot remove teacher: Teacher not found.\n";
}
else // Teacher found
{
teacherList.erase(teacherList.begin() + position); // Remove teacher
}
}
/*
* Return the course level
*/
string Course::getLevel()
{
return level;
}
/*
* Return the course title
*/
string Course::getTitle()
{
return title;
}
/*
* Return the department name
*/
string Course::getDepartmentName()
{
return departmentName;
}
/*
* Output the list of students and their grades
*/
void Course::printGrades()
{
int size = studentList.size();
cout << this->getTitle() << "'s Grade List:\n\n";
if (size == 0)
{
cout << "No Entries\n";
}
else
{
for (int i = 0; i < size; i++)
{
cout << "Student name: " << studentList[i]->getName()
<< "\n\tID: " << studentList[i]->getID() << "\n\tGrade: " << grades[i] << "\n";
}
}
cout << '\n';
}
/*
* Output the list of teachers
*/
void Course::printTeacherList()
{
int size = teacherList.size();
cout << this->getTitle() << "'s Teachers are:\n\n";
if (size == 0)
{
cout << "No Entries\n";
}
else
{
for (int i = 0; i < size; i++)
{
cout << "Teacher name: " << teacherList[i]->getName()
<< "\n\tID: " << teacherList[i]->getID() << '\n';
}
}
cout << '\n';
} | true |
d2cca463a64ef27231b6dfbecae7e185eb286236 | C++ | ryanr08/CS-32 | /Homework 2/eval.cpp | UTF-8 | 6,841 | 3.46875 | 3 | [] | no_license | #include "Set.h"
#include <stack>
#include <string>
#include <cassert>
#include <iostream>
using namespace std;
bool isOperator(char c);
bool isValidExpression(string infix);
bool hasHigherPrecedence(char l, char r);
void applyBooleanOperation(bool& operand1, bool& operand2, char ch, bool& result);
bool evaluatePostFix(string postfix, const Set& trueValues, const Set& falseValues);
int evaluate(string infix, const Set& trueValues, const Set& falseValues, string& postfix, bool& result)
{
if (!isValidExpression(infix))
return 1;
postfix = "";
stack<char> operators;
for (unsigned long i = 0; i < infix.size(); i++) // convert infix expression to postfix
{
if (islower(infix[i]))
{
postfix += infix[i];
}
else if (infix[i] == '(')
{
operators.push('(');
}
else if (infix[i] == '!')
{
operators.push('!');
}
else if (infix[i] == ')')
{
while (operators.top() != '(')
{
postfix += operators.top();
operators.pop();
}
operators.pop();
}
else if (isOperator(infix[i]))
{
while (!operators.empty() && operators.top() != '(' && !hasHigherPrecedence(infix[i], operators.top()))
{
postfix += operators.top();
operators.pop();
}
operators.push(infix[i]);
}
}
while (!operators.empty())
{
postfix += operators.top();
operators.pop();
}
for (unsigned long i = 0; i < infix.size(); i++) // check if every operand letters appears in either trueValues or falseValues
{
if (islower(infix[i]))
{
if (trueValues.contains(infix[i]))
{
if (falseValues.contains(infix[i]))
return 3;
}
else if (!falseValues.contains(infix[i]))
return 2;
}
}
result = evaluatePostFix(postfix, trueValues, falseValues);
return 0;
}
bool evaluatePostFix(string postfix, const Set& trueValues, const Set& falseValues)
{
char t;
trueValues.get(0, t);
char f;
falseValues.get(0, f);
stack<char> Operands;
for (unsigned long i = 0; i < postfix.size(); i++) // evaluating the postfix expression
{
if (isalpha(postfix[i]))
Operands.push(postfix[i]);
else if (postfix[i] == '|' || postfix[i] == '&')
{
bool tempResult = true;
bool operand2 = trueValues.contains(Operands.top());
Operands.pop();
bool operand1 = trueValues.contains(Operands.top());
Operands.pop();
applyBooleanOperation(operand1, operand2, postfix[i], tempResult);
if (tempResult == true)
Operands.push(t);
else
Operands.push(f);
}
else
{
bool operand1 = trueValues.contains(Operands.top());
Operands.pop();
operand1 = !operand1;
if (operand1)
Operands.push(t);
else
Operands.push(f);
}
}
if (trueValues.contains(Operands.top()))
return true;
else
return false;
}
void applyBooleanOperation(bool& operand1, bool& operand2, char ch, bool& result)
{
switch (ch)
{
case '|':
result = (operand1 || operand2);
return;
case '&':
result = (operand1 && operand2);
return;
}
return;
}
bool hasHigherPrecedence(char l, char r)
{
if (l == r)
return false;
switch (l)
{
case '!':
return true;
case '&':
if (r == '!')
return false;
else
return true;
case '|':
return false;
}
return false;
}
bool isOperator(char c)
{
if (c == '&' || c == '|')
return true;
return false;
}
bool isValidExpression(string infix)
{
if (infix.size() == 0)
return false;
string newFix;
int newSize = 0;
for (unsigned long i = 0; i < infix.size(); i++) //remove spaces from infix
{
if (isOperator(infix[i]) || islower(infix[i]) || infix[i] == ')' || infix[i] == '(' || infix[i] == '!')
{
newFix += infix[i];
newSize++;
}
else if (infix[i] != ' ')
return false;
}
for (int i = 0; i < newSize; i++) // check if infix is valid
{
if (i == 0)
{
if (isOperator(newFix[i]))
return false;
}
if (i == (newSize - 1))
{
if (!islower(newFix[i]) && newFix[i] != ')')
return false;
}
else if (islower(newFix[i]))
{
if (!isOperator(newFix[i + 1]) && newFix[i + 1] != ')')
return false;
}
else if (isOperator(newFix[i]))
{
if (!islower(newFix[i + 1]) && newFix[i + 1] != '!' && newFix[i + 1] != '(')
return false;
}
else if (newFix[i] == '(')
{
if (newFix[i + 1] == ')')
return false;
}
}
int count1 = 0;
int count2 = 0;
for (int i = 0; i < newSize; i++) // check if number of open and closed parenthesis are equal
{
if (newFix[i] == '(')
count1++;
else if (newFix[i] == ')')
count2++;
}
return (count1 == count2);
}
int main()
{
string trueChars = "tywz";
string falseChars = "fnx";
Set trues;
Set falses;
for (int k = 0; k < trueChars.size(); k++)
trues.insert(trueChars[k]);
for (int k = 0; k < falseChars.size(); k++)
falses.insert(falseChars[k]);
string pf;
bool answer;
assert(evaluate("t&!(f|t&t|f)|!!!(f&t&f)", trues, falses, pf, answer) == 0 && answer);
assert(evaluate("t|f&f ", trues, falses, pf, answer) == 0 && answer);
assert(evaluate(" !f|t ", trues, falses, pf, answer) == 0 && answer);
assert(evaluate("!(f|t) ", trues, falses, pf, answer) == 0 && !answer);
assert(evaluate("t & !f", trues, falses, pf, answer) == 0 && answer);
assert(evaluate("&t|f", trues, falses, pf, answer) == 1);
assert(evaluate(")t|f( & !f", trues, falses, pf, answer) == 1);
assert(evaluate("((((((t|f)))", trues, falses, pf, answer) == 1);
assert(evaluate("w| f", trues, falses, pf, answer) == 0 && pf == "wf|" && answer);
assert(evaluate("y|", trues, falses, pf, answer) == 1);
assert(evaluate("n t", trues, falses, pf, answer) == 1);
assert(evaluate("nt", trues, falses, pf, answer) == 1);
assert(evaluate("()", trues, falses, pf, answer) == 1);
assert(evaluate("y(n|y)", trues, falses, pf, answer) == 1);
assert(evaluate("t(&n)", trues, falses, pf, answer) == 1);
assert(evaluate("(n&(t|7)", trues, falses, pf, answer) == 1);
assert(evaluate("", trues, falses, pf, answer) == 1);
assert(evaluate("f | !f & (t&n) ", trues, falses, pf, answer) == 0 && pf == "ff!tn&&|" && !answer);
assert(evaluate(" x ", trues, falses, pf, answer) == 0 && pf == "x" && !answer);
trues.insert('x');
assert(evaluate("((x))", trues, falses, pf, answer) == 3);
falses.erase('x');
assert(evaluate("((x))", trues, falses, pf, answer) == 0 && pf == "x" && answer);
trues.erase('w');
assert(evaluate("w| f", trues, falses, pf, answer) == 2);
falses.insert('w');
assert(evaluate("w| f", trues, falses, pf, answer) == 0 && pf == "wf|" && !answer);
cout << "Passed all tests" << endl;
} | true |
a13737f91aaf79ac8c923f6a595da490e2e7b650 | C++ | kclick91/KMeansCPlusPlus | /KMeans/main.cpp | UTF-8 | 1,089 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include "DataCollection.h"
#include "Partitioner.h"
//Implementation of the K-Means algorithm//
void Run()
{
int clu;
//User enter both # of clusters and # of data Points
cout << "Enter number of clusters." << endl;
cin >> clu;
int dP;
cout << "Enter number of data points." << endl;
cin >> dP;
int* numbOfClusters = &clu; //number of clusters
int* dataPoints = &dP; // number of data points
DataCollection* dc = new DataCollection(dataPoints);
Partitioner* p = new Partitioner(*dc);
cout << "Print Data." << endl;
dc->PrintData();
cout << "Initialize Centers" << endl;
p->InitializeCenters(clu);
cout << "Print Centers." << endl;
p->InitializeDistances();
p->PrintCenters();
cout << "Measure Distances." << endl;
int testConvergence = 0;
//Repeat until the same cluster centers occur
while(testConvergence != clu)
{
p->MeasureDistances();
p->PrintDistances();
p->PrintClusterAssignments();
testConvergence = p->ReadjustCenters();
}
cout << "Finished." << endl;
}
int main()
{
Run();
return 0;
}
| true |
bc180d09b31e98fdfcb72e491e4a54e13039d1c5 | C++ | ChildofFire/CodingStuff | /Geeks4Geeks/LCS.cpp | UTF-8 | 933 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int maximum(int a, int b)
{
return (a>b)? a: b;
}
string LCS(string s1, string s2, int a, int b)
{
int mat[a+1][b+1];
for(int i=0;i<=a;i++)
for(int j=0;j<=b;j++)
if(i==0 || j==0)
mat[i][j]=0;
else
mat[i][j]=(s1[i-1]==s2[j-1])? mat[i-1][j-1]+1 : maximum(mat[i-1][j],mat[i][j-1]);
int i=a, j=b;
string str;
while(mat[i][j]!=0)
{
if(mat[i][j]!=maximum(mat[i-1][j],mat[i][j-1])) {str+=s1[i-1]; i--; j--;}
else
{
if(mat[i][j]==mat[i-1][j]) i--;
else j--;
}
}
reverse(str.begin(),str.end());
return str;
}
int main()
{
int t,a,b; string s1, s2;
cin>>t;
while(t--)
{
cin>>a>>b;
cin>>s1>>s2;
cout<<LCS(s1,s2,a,b)<<endl;
}
}
| true |
370a266b7f06ea6d658e74cf8bd298822a682de2 | C++ | Jane11111/leetcode | /417.cpp | UTF-8 | 4,284 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix);
bool isValid(pair<int,int> p,int m,int n);
bool canGo(pair<int,int> p,int cur,vector<vector<int>>& matrix);
int main() {
vector<vector<int>> matrix;
vector<int> row1;
vector<int> row2;
vector<int> row3;
vector<int> row4;
vector<int> row5;
row1.push_back(1);
row1.push_back(2);
row1.push_back(2);
row1.push_back(3);
row1.push_back(5);
row2.push_back(3);
row2.push_back(2);
row2.push_back(3);
row2.push_back(4);
row2.push_back(4);
row3.push_back(2);
row3.push_back(4);
row3.push_back(5);
row3.push_back(3);
row3.push_back(1);
row4.push_back(6);
row4.push_back(7);
row4.push_back(1);
row4.push_back(4);
row4.push_back(5);
row5.push_back(5);
row5.push_back(1);
row5.push_back(1);
row5.push_back(2);
row5.push_back(4);
matrix.push_back(row1);
matrix.push_back(row2);
matrix.push_back(row3);
matrix.push_back(row4);
matrix.push_back(row5);
vector<pair<int,int>> res=pacificAtlantic(matrix);
cout<<res.size()<<endl;
}
bool isValid(pair<int,int> p,int m,int n){
int x=p.first;
int y=p.second;
return x>=0&&x<m&&y>=0&&y<n;
}
bool canGo(pair<int,int> p,int cur,vector<vector<int>>& matrix){
int x=p.first;
int y=p.second;
return matrix[x][y]>=cur;
}
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<pair<int,int>> res;
int m=matrix.size();
if(m==0)
return res;
int n=matrix[0].size();
if(n==0)
return res;
vector<pair<int,int>> PQ;
map<pair<int,int>,bool> Pmap;
for(int i=0;i<n;i++){
pair<int,int> p=pair<int,int>(0,i);
PQ.push_back(p);
Pmap[p]=true;
}
for(int i=0;i<m;i++){
pair<int,int> p=pair<int,int>(i,0);
PQ.push_back(p);
Pmap[p]=true;
}
while(!PQ.empty()){
pair<int,int> cur=PQ[0];
PQ.erase(PQ.begin());
int x=cur.first;
int y=cur.second;
int h=matrix[x][y];
pair<int,int> up(x-1,y);
pair<int,int> down(x+1,y);
pair<int,int> left(x,y-1);
pair<int,int> right(x,y+1);
if(!Pmap.count(up)&&isValid(up,m,n)&&canGo(up,h,matrix)){
Pmap[up]=true;
PQ.push_back(up);
}
if(!Pmap.count(down)&&isValid(down,m,n)&&canGo(down,h,matrix)){
Pmap[down]=true;
PQ.push_back(down);
}
if(!Pmap.count(left)&&isValid(left,m,n)&&canGo(left,h,matrix)){
Pmap[left]=true;
PQ.push_back(left);
}
if(!Pmap.count(right)&&isValid(right,m,n)&&canGo(right,h,matrix)){
Pmap[right]=true;
PQ.push_back(right);
}
}
vector<pair<int,int>> AQ;
map<pair<int,int>,bool> Amap;
for(int i=0;i<n;i++){
pair<int,int> p=pair<int,int>(m-1,i);
AQ.push_back(p);
Amap[p]=true;
}
for(int i=0;i<m;i++){
pair<int,int> p=pair<int,int>(i,n-1);
AQ.push_back(p);
Amap[p]=true;
}
while(!AQ.empty()){
pair<int,int> cur=AQ[0];
AQ.erase(AQ.begin());
int x=cur.first;
int y=cur.second;
int h=matrix[x][y];
pair<int,int> up(x-1,y);
pair<int,int> down(x+1,y);
pair<int,int> left(x,y-1);
pair<int,int> right(x,y+1);
if(!Amap.count(up)&&isValid(up,m,n)&&canGo(up,h,matrix)){
Amap[up]=true;
AQ.push_back(up);
}
if(!Amap.count(down)&&isValid(down,m,n)&&canGo(down,h,matrix)){
Amap[down]=true;
AQ.push_back(down);
}
if(!Amap.count(left)&&isValid(left,m,n)&&canGo(left,h,matrix)){
Amap[left]=true;
AQ.push_back(left);
}
if(!Amap.count(right)&&isValid(right,m,n)&&canGo(right,h,matrix)){
Amap[right]=true;
AQ.push_back(right);
}
}
map<pair<int,int>,bool>::iterator ite=Pmap.begin();
while(ite!=Pmap.end()){
if(Amap.count(ite->first))
res.push_back(ite->first);
ite++;
}
return res;
} | true |
9a768f113818ad9b4f64d1a9bb6a9146bcd995ae | C++ | artcom/asl | /asl/thread/completion.h | UTF-8 | 1,100 | 2.984375 | 3 | [
"BSL-1.0"
] | permissive | #ifndef ASL_THREAD_COMPLETION_H_
#define ASL_THREAD_COMPLETION_H_
#include <boost/thread.hpp>
namespace asl {
namespace thread {
class completion {
public:
completion() : complete_(false) {}
~completion() {}
private:
volatile bool complete_;
boost::mutex mutex_;
boost::condition_variable condition_variable_;
public:
void signal() {
complete_ = true;
condition_variable_.notify_all();
}
bool is_complete() {
return complete_;
}
void wait() {
boost::mutex::scoped_lock lock(mutex_);
while(!complete_) {
condition_variable_.wait(lock);
}
}
template<typename Duration_Type_>
bool timed_wait(Duration_Type_ wait_duration) {
boost::system_time const timeout = boost::get_system_time() + wait_duration;
boost::mutex::scoped_lock lock(mutex_);
while(!complete_) {
if(!condition_variable_.timed_wait(lock, timeout)) {
return false;
}
}
return true;
}
};
}
}
#endif // !ASL_THREAD_COMPLETION_H_
| true |
83d366b5a2eff1cce956782f08e01dba803c18ef | C++ | yuchaozh/EECS395_Programming-Assignment-4 | /town.h | UTF-8 | 664 | 2.734375 | 3 | [] | no_license | /*
Author: Zhou Yuchao
Date:12/03/2013
Store the information of destination. This is the node of the map_array
*/
#ifndef _TOWN_H
#define _TOWN_H
#include<iostream>
#include<string>
#include "list.h"
#include "node.h"
using namespace std;
class town
{
public:
list *edges;
//constructor
town();
//destructor
~town();
//set the name of the destination
void setDestinationName(string name);
//set the outgoing vertex in correspoing list
void setList(int end, double distance, double speed, double time);
//return the name of the destination
string getDestinationName();
//return the list
list* getList();
string destinationName;
};
#endif
| true |
3da6073b417bffea140cc4b49fdf69e9d5f1b458 | C++ | khanmosajjid/DataStructure | /structure.cpp | UTF-8 | 668 | 3.109375 | 3 | [] | no_license | #include<iostream>
using namespace std;
// struct address
// {int stateNo;
// int cityNo;
// };
// struct student
// {int rNo;
// char* name;
// struct address addr;
// float cgpa;
// };
// int main(){
// struct student std;
// std.rNo=10;
// std.name="mj";
// std.addr.stateNo=3;
// cout<<std.name;
// cout<<std.addr.stateNo;
// return 0;
// }
struct s1
{
int g;
struct s1*f;
};
struct s2
{
float c;
struct s1*d;
char e;
};
struct s3{
int a;
struct s2 *b;
char z;
};
int main(){
struct s3 *p;
p =new(s3);
p->a=10;
p->b=new(s2);
p->b->d=new(s1);
p->b->d->g=5;
cout<<p->b->d->g;
return 0;
} | true |
bfc39ac08a426b6e3fd05fe9e4e84fe176818c5c | C++ | smilagros/Algorithm-And-Data-Structures-Implementation | /College Placement Practice - HackerCode/Recursion/Q7_reverse_string_not_words.cpp | UTF-8 | 880 | 3.40625 | 3 | [] | no_license | #include<string>
#include<iostream>
using namespace std;
//function to reverse a given string
void reverse_string(string str,int st,int ed)
{
if(st == ed)
return;
char ch = str[st];
str[st] = str[ed];
str[ed] = ch;
reverse_string(str,st+1,ed-1);
}
string getString(string str)
{
string result = "";
int l = str.length();
int first = 0,last = 0;
for(int i=0;i<l;i++)
{
if(str[i] == ' ')
{
int a = i - first;
string stk = str.substr(first,a);
reverse_string(stk,0,stk.length());
result = result + stk + " ";
first = i+1;
}
}
}
string rev(string str)
{
string stm = "";
for(int i=str.length()-1;i>=0;i--)
{
stm = stm+str[i];
}
stm = stm+" ";
string output = getString(stm);
return output;
}
int main()
{
string ss;
getline(cin,ss);
// string result = rev(ss);
string g = "hello";
ss += g;
cout<<ss<<endl;
return 0;
}
| true |
66a55429c92bce61b307ddae085f4e610e8a7d1f | C++ | r3dark/DS_CODES | /ll_check_fixed.cpp | UTF-8 | 1,475 | 3.71875 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct node
{
node *next;
int data;
node *prev;
};
class ll
{
node *head=NULL;
public:
void insertend()
{
int value;
cout<<"enter value"<<endl;
cin>>value;
node *newnode=new node;
newnode->data=value; // important to initialize here as
newnode->next=NULL; // new node is created but not what it is pointing at?
newnode->prev=NULL; // have to set NULL/address and value as soon as node is made
if(!head)
{
head=newnode;
}
else{
node *temp=head;
while(temp->next)
{
temp=temp->next;
}
temp->next=newnode; // now if no value and pointer is set to newnode before, temp->next is pointing to a node which has no data and its prev
//and next are not specified
newnode->data=value; //then no need to set value here again
newnode->next=NULL; //and no need to set newnode->NULL again, coz already did above
newnode->prev=temp;
}
}
void print()
{
node *curr=head;
while(curr)
{
cout<<curr->data<<" ";
curr=curr->next;
}
cout<<endl;
}
};
int main()
{
ll obj;
obj.insertend();
/*obj.insertend();
obj.insertend();
obj.insertend();*/
obj.print();
}
| true |
374da3056e1a686516eb88ae3da19bc20bcc59c5 | C++ | CXUtk/TRV2 | /src/TREngine/Core/Utils/Collision.h | UTF-8 | 3,115 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <Core.h>
#include <glm/glm.hpp>
#include <algorithm>
#include <vector>
#include <Core/Structures/Rect.hpp>
TRV2_NAMESPACE_BEGIN
constexpr float EPS = 1e-5f;
enum class CollisionSide
{
LEFT,
RIGHT,
TOP,
BOTTOM
};
struct Interval
{
bool horizontal;
float V;
float L, R;
};
inline bool IntervalIntersects(const Interval& A, const Interval& B)
{
return std::max(A.L, B.L) < std::min(A.R, B.R);
}
inline std::vector<Interval> GetCollidingSegments(const Rectf& rect, glm::vec2 velocity)
{
std::vector<Interval> segments;
if (velocity.x > 0)
{
// 右碰撞段
segments.push_back({ false, rect.Position.x + rect.Size.x, rect.Position.y, rect.Position.y + rect.Size.y });
}
else if (velocity.x < 0)
{
// 左碰撞段
segments.push_back({ false, rect.Position.x, rect.Position.y, rect.Position.y + rect.Size.y });
}
// 如果速度x等于0,那么不存在左右碰撞段
if (velocity.y > 0)
{
// 上碰撞段
segments.push_back({ true, rect.Position.y + rect.Size.y, rect.Position.x, rect.Position.x + rect.Size.x });
}
else if(velocity.y < 0)
{
// 下碰撞段
segments.push_back({ true, rect.Position.y, rect.Position.x, rect.Position.x + rect.Size.x });
}
// 如果速度y等于0,那么不存在上下碰撞段
return segments;
}
inline std::vector<Interval> GetCollidingSegmentsRev(const Rectf& rect, glm::vec2 velocity)
{
std::vector<Interval> segments;
if (velocity.x > 0)
{
// 左碰撞段
segments.push_back({ false, rect.Position.x, rect.Position.y, rect.Position.y + rect.Size.y });
}
else if (velocity.x < 0)
{
// 右碰撞段
segments.push_back({ false, rect.Position.x + rect.Size.x, rect.Position.y, rect.Position.y + rect.Size.y });
}
// 如果速度x等于0,那么不存在左右碰撞段
if (velocity.y > 0)
{
// 下碰撞段
segments.push_back({ true, rect.Position.y, rect.Position.x, rect.Position.x + rect.Size.x });
}
else if(velocity.y < 0)
{
// 上碰撞段
segments.push_back({ true, rect.Position.y + rect.Size.y, rect.Position.x, rect.Position.x + rect.Size.x });
}
// 如果速度y等于0,那么不存在上下碰撞段
return segments;
}
inline float GetNearestCollisionTime(const Interval& subject, glm::vec2 velocity, const std::vector<Interval>& intervals)
{
double minimalTime = std::numeric_limits<double>::infinity();
for (auto& inv : intervals)
{
if (subject.horizontal)
{
double distY = inv.V - subject.V;
double t = distY / velocity.y;
if (t < 0) continue;
double moveX = velocity.x * t;
// If X collides
if (std::max(subject.L + moveX, (double)inv.L) < std::min(subject.R + moveX, (double)inv.R))
{
if (t < minimalTime)
{
minimalTime = t;
}
}
}
else
{
double distX = inv.V - subject.V;
double t = distX / velocity.x;
if (t < 0) continue;
double moveY = velocity.y * t;
// If X collides
if (std::max(subject.L + moveY, (double)inv.L) < std::min(subject.R + moveY, (double)inv.R))
{
if (t < minimalTime)
{
minimalTime = t;
}
}
}
}
return minimalTime;
}
TRV2_NAMESPACE_END | true |
42ed2157307a0d4747a0bca54ffb0c5eabeb6e90 | C++ | pbraga88/study | /2022/CPP-01_ConceptsReview/13-OOP-ClassesAndObjects/Section-Challenge/include/Movies.h | UTF-8 | 685 | 2.96875 | 3 | [] | no_license | #ifndef _MOVIES_CLASS_H_
#define _MOVIES_CLASS_H_
#include <string>
#include <vector>
#include "Movie.h"
class Movies {
std::vector<Movie> movies;
// std::string movie_name;
// std::string movie_rating;
// int movie_watch_count;
public:
/* Both 'Constructor' and 'Destructor' will be automatically addressed by compiler when they do nothing, like the example below.
I'm declaring them here for the sake of example */
// Constructor
Movies();
// Destructor
~Movies();
bool add_movie(std::string name, std::string rating, int watch_count);
bool increment_watched(std::string name);
void display();
};
#endif // _MOVIES_CLASS_H_ | true |
4ab30ebcf7a237d6f7d42083da8b2cb48bf06373 | C++ | pnthao/P3_AQSIOS | /stream.thao/dsms/src/common/include/execution/scheduler/lottery_sched_id.h | UTF-8 | 1,025 | 2.734375 | 3 | [] | no_license | #ifndef _LOTTERY_SCHEDULER_ID
#define _LOTTERY_SCHEDULER_ID
#ifndef _SCHEDULER_
#include "execution/scheduler/scheduler.h"
#endif
#include <vector>
namespace Execution {
class LotterySchedulerID : public Scheduler {
private:
static const unsigned int MAX_OPS = 100;
// Operators that we are scheduling
Operator *ops [MAX_OPS];
//a vector that holds the operator id that holds
//each ticket number ( the index of the vector)
std::vector <unsigned int> tickets;
// Number of operators that we have to schedule
unsigned int numOps;
//max of operator priorities
double max_op_priorities;
//the length of a cycle in tuples
// i.e. the number of tuples that should be
//processed before the system reassigns the tickets
int cycle_length;
bool bStop;
public:
LotterySchedulerID ();
virtual ~LotterySchedulerID ();
// Inherited from Scheduler
int addOperator (Operator *op);
int run (long long int numTimeUnits);
int stop ();
int resume ();
};
}
#endif
| true |
286a716b0dbea3fc28af6c21b0d79d056604e1a6 | C++ | zimnicky/knu-iii-s-labs-oop | /tasks/19/disjointset.cpp | UTF-8 | 491 | 2.890625 | 3 | [] | no_license | #include "disjointset.h"
DisjointSet::DisjointSet(unsigned int count)
{
sets.resize(count);
for (unsigned int i = 0; i < count; i++)
sets[i] = i;
}
int DisjointSet::getNumberOfSet(unsigned int element)
{
if (element != sets[element])
sets[element] = getNumberOfSet(sets[element]);
return sets[element];
}
void DisjointSet::join(unsigned int el1, unsigned int el2)
{
int p1 = getNumberOfSet(el1);
int p2 = getNumberOfSet(el2);
sets[p2] = p1;
}
| true |
93deec0bf0562f1cc43b4282f008209b8df74667 | C++ | zeze1004/C-practice | /Programers_Level1.cpp | UHC | 1,073 | 3.53125 | 4 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <stdio.h>
using namespace std;
/*
1-1. Էµ ¦ 2 ϴ.
1-2. Էµ Ȧ 3 ϰ 1 մϴ.
2. ۾ 1 ݺմϴ.
*/
int solution(int num) {
int answer = 0;
int i = 0;
while (i < 500)
{
if (num % 2 == 0)
{
num = num / 2;
answer++;
printf(" %d -> ", num);
i++;
}
else {
num = num*3 + 1;
printf(" %d -> ", num);
answer++;
i++;
}
if (num == 1)
break;
}
if (num != 1)
answer = -1;
printf("\n : %d", answer);
return answer;
}
int main()
{
int k;
printf(" ԷϽÿ: ");
scanf("%d", &k);
solution(k);
return 0;
} | true |
df2e7f26355b0d32696842ed48315adae631cce1 | C++ | jared-two-foxes/BlackJack | /framework/include/terminal/util.hpp | UTF-8 | 1,655 | 3.1875 | 3 | [] | no_license | #ifndef FRAMEWORK_TERMINAL_UTIL_HPP__
#define FRAMEWORK_TERMINAL_UTIL_HPP__
#include <string>
#define ESC "\x1b"
#define CSI "\x1b["
namespace framework {
inline auto toString(std::string const& x) -> std::string {
return x;
}
template <class T>
auto toString(T const& x) ->decltype(std::to_string(x)) {
return std::to_string(x);
}
inline std::vector<std::string > split(std::string const& str, const std::string& delimiter = "\n") {
std::vector<std::string > tokens;
auto start = 0U;
auto end = str.find(delimiter);
while (end != std::string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + delimiter.size();
end = str.find(delimiter, start);
}
if (start != str.size()) {
tokens.push_back(str.substr(start, str.size() - start));
}
return tokens;
}
template <class T, class F>
auto map(T const& data, F const& f) {
std::vector<decltype(f(data[0]))> result(data.size());
std::transform(
data.begin(), data.end(),
result.begin(),
f);
return result;
}
inline std::string repeat(unsigned n, std::string const& s) {
std::string result = "";
for (unsigned i = 0; i < n; ++i) {
result += s;
}
return result;
}
inline std::string clearBeforeCursor() {
return CSI"0K";
}
inline std::string clearAfterCursor() {
return CSI"1K";
}
inline std::string clearLine() {
return CSI"2K\r";
}
inline std::string moveUp(unsigned n = 1 ) {
return CSI + std::to_string(n) + "A\r";
}
inline std::string clearLines(unsigned n = 1) {
return CSI"0m" + clearBeforeCursor() + ((n) ? repeat(n, clearLine() + moveUp()) + clearLine() : std::string(""));
}
}
#endif // FRAMEWORK_TERMINAL_UTIL_HPP__
| true |
411aa275ddd9d1ae36ae59a6e9277fba07da6e89 | C++ | akboga/80sampleCProjects | /project4.cpp | ISO-8859-9 | 344 | 3.0625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
// Bir kenar girilen karenin alan ve evresini hesaplayan program.
int main(){
int i,alan,cevre;
printf("Karenin bir kenar uzunlugunu giriniz : ");
scanf("%d",&i);
alan = i*i;
cevre = i*4;
printf("Karenin alani : %d\n",alan);
printf("Karenin cevresi : %d\n",cevre);
return 0;
}
| true |
93ca1e0df9aaeaa2c1a1342d59fad2795d0bf928 | C++ | helcl42/line | /src/DetectionSettings.cpp | UTF-8 | 2,028 | 3.09375 | 3 | [] | no_license | #include "DetectionSettings.h"
//format 334432 657687 657654 ...
DetectionSettings::DetectionSettings(int argc, char** argv)
: colorIndex(0)
{
for (int i = 2; i < argc; i++)
{
DetectionColorItem* item = new DetectionColorItem();
std::string color(argv[i]);
if (color.length() == 6)
{
for (int j = 0, index = 0; j < 3; j++, index += 2)
{
item->color[j] = Utils::convertStringToHexInt(color.substr(index, 2));
}
}
else
{
throw std::runtime_error("Invalid color format");
}
colors.push_back(item);
}
}
DetectionSettings::~DetectionSettings()
{
for (unsigned int i = 0; i < colors.size(); i++)
{
SAFE_DELETE(colors[i]);
}
}
unsigned int DetectionSettings::getCountOfColors() const
{
return colors.size();
}
DetectionColorItem* DetectionSettings::getNext()
{
colorIndex++;
if(colorIndex >= colors.size())
{
colorIndex = 0;
}
return colors[colorIndex];
}
DetectionColorItem* DetectionSettings::getItem(int index) const
{
if (index >= 0 || index < (int)colors.size())
{
return colors[index];
}
else
{
throw std::runtime_error("DetectionSettings:getItem:Invalid index");
}
}
DetectionColorItem* DetectionSettings::operator[](int index)
{
if (index >= 0 || index < (int)colors.size())
{
return colors[index];
}
else
{
throw std::runtime_error("DetectionSettings:operator[]:Invalid index");
}
}
std::ostream& operator<<(std::ostream& out, const DetectionSettings& settings)
{
out << "Detection settings:" << std::endl;
for (unsigned int i = 0; i < settings.colors.size(); i++)
{
out << "-------------------------------" << std::endl;
out << i + 1 << ") color" << std::endl;
out << settings.colors[i]->color << std::endl;
}
return out;
}
| true |
af915567af112fe5636fba00515567b5a52a09f1 | C++ | deadpool10086/love-C | /del.cpp | GB18030 | 2,466 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <time.h>
#include <stdlib.h>
#define DEFAULTNUM 10000
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
template <typename WC>
class SeqList
{
private:
WC *data;
int maxNum;
int end;
public:
SeqList(int n = DEFAULTNUM)
{
if(n > 0)
{
maxNum = n;
end = -1;
data = new WC[maxNum];
if(data == NULL)
{
cerr << "ڴը" << endl;
exit(1);
}
}
}
~SeqList(void)
{
delete[] data;
}
void add(int &n)
{
if(end < maxNum)
{
data[++end] = n;
}
else
cerr << "The data is already full " << endl;
}
void search(int &n)
{
int i;
for(i = 0; i < end; i++)
{
if(n==data[i])
{
cout << "The data is located in the " << i+1 << endl;
return;
}
}
cout << "Can't find such data." << endl;
}
void change(int &i,int &n)
{
if(i > 0 && i <= end+1)
{
data[i-1] = n;
}
else
cerr << "Position error " <<endl;
}
void del(int &i)
{
if(i < 1 || i > end)
{
cerr << "Position error" << endl;
}
else
{
for(int j = i-1; j <= end; j++)
{
data[j]=data[j+1];
}
end--;
}
}
void output(void)
{
for(int i = 0; i <= end; i++)
{
cout << i+1 << ':' << data[i] << '\t';
}
}
void insert_sort(void)
{
int temp;
int j;
for(int i = 1; i <= end; i++)
{
temp = data[i];
for(j = i; i > 0; j--)
{
if(temp < data[j-1])
data[j] = data[j-1];
else
break;
}
data[j] = temp;
}
}
void full(void)
{
for( ; end < maxNum-1; end++)
data[end] = rand();
}
};
int main(int argc, char** argv) {
int n,i,d;
cout << "鳤" << endl;
cin >> n;
SeqList<int> s(n);
while(1)
{
srand((unsigned)time(NULL));
cout << "\n1.ӣ2.ң3.ģ4.ɾ5.ݣ6.ٳ7.0.˳";
cin >> n;
if(n==0)
break;
switch(n)
{
case 1: cout << "data:" << endl; cin >> d; s.add(d); break;
case 2: cout << "data:" << endl; cin >> d; s.search(d); break;
case 3: cout << "data:" << endl; cin >> i >> d; s.change(i,d); break;
case 4: cout << "data:" << endl; cin >> d; s.del(d); break;
case 5: s.output(); break;
case 6: s.full();
case 7: s.insert_sort(); break;
}
}
return 0;
}
| true |
48905ef8841e6bcf6e5fab0928015f3182587c00 | C++ | terishrimp/SDL_BlackJack | /source/Deck.cpp | UTF-8 | 2,588 | 3.390625 | 3 | [] | no_license | #pragma once
#include "Deck.h"
Deck::Deck(SDL_Renderer* const renderer) : m_renderer{ renderer } {
createDeck();
}
Card Deck::takeCardFromFront() {
Card takenCard = getCardAtIndex(0);
removeCard(0);
return takenCard;
}
void Deck::shuffleCardList() {
srand((unsigned int)time(nullptr));
std::random_shuffle(deckList.begin(), deckList.end());
}
std::vector<Card> Deck::getDeckList() {
return deckList;
}
Card Deck::getCardAtIndex(const int index) {
return deckList[index];
}
void Deck::removeCard(const int index) {
deckList.erase(deckList.begin() + index);
}
void Deck::createDeck() {
deckList.clear();
Card ace(false, 1, "Ace", "Spades", m_renderer);
Card two(false, 2, "Two", "Spades", m_renderer);
Card three(false, 3, "Three", "Spades", m_renderer);
Card four(false, 4, "Four", "Spades", m_renderer);
Card five(false, 5, "Five", "Spades", m_renderer);
Card six(false, 6, "Six", "Spades", m_renderer);
Card seven(false, 7, "Seven", "Spades", m_renderer);
Card eight(false, 8, "Eight", "Spades", m_renderer);
Card nine(false, 9, "Nine", "Spades", m_renderer);
Card ten(false, 10, "Ten", "Spades", m_renderer);
Card jack(false, 10, "Jack", "Spades", m_renderer );
Card queen(false, 10, "Queen", "Spades", m_renderer);
Card king(false, 10, "King", "Spades", m_renderer);
for (size_t i{ 0 }; i < 4; ++i) {
std::string suitType;
switch (i) {
case 0:
suitType = "Spades";
break;
case 1:
suitType = "Clubs";
break;
case 2:
suitType = "Hearts";
break;
default:
suitType = "Diamonds";
break;
}
deckList.push_back(ace);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(two);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(three);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(four);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(five);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(six);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(seven);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(eight);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(nine);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(ten);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(jack);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(queen);
deckList[deckList.size() - 1].setSuit(suitType);
deckList.push_back(king);
deckList[deckList.size() - 1].setSuit(suitType);
}
} | true |
b5accfba27c4208253161ca618c7df5d0026a43e | C++ | tarasrumezhak/CString | /test/my_str_clear.cc | UTF-8 | 353 | 2.59375 | 3 | [] | no_license | #include "gtest/gtest.h"
extern "C" {
#include "cstrings.h"
}
TEST(CStringsTest, my_str_clear) {
my_str_t str;
my_str_create(&str, 0);
my_str_from_cstr(&str, "merry christmas!", 100);
my_str_clear(&str);
ASSERT_EQ(str.size_m, 0);
ASSERT_EQ(str.capacity_m, 100);
ASSERT_STREQ(my_str_get_cstr(&str), "");
my_str_free(&str);
}
| true |
520dcefe7b7ce66a9c70ab32fd52c7f636b67fab | C++ | jackaberdeen15/EE40GA_Sort | /EE40GA_Sort/generalArray.h | UTF-8 | 13,664 | 3.859375 | 4 | [] | no_license | #ifndef __GENERALARRAY_H_
#define __GENERALARRAY_H_
#include "ArrayItem.h"
// version with inheritance
class general_array{
protected:
// "reference item" has to be initialized with the address
// of a (non-base class) valid object, allocated on the heap
basic_item *reference_item;
// this is an array of pointers.
// each pints to a generic element
basic_item **thearray;
// number of array entries allocated
int max_arraysize;
bool memallocated;
// number of array entries used
int tot_items;
// index of current item (may be useful)
int current_index;
// functions that are needed by each derived class to do sorting (this is useful for bublbesort
bool swapElements(int elem1_index, int elem2_index)
{
// check that the memory is allocated and that the element indexes are within array boundary
if(memIsAllocated() && checkIndexIsAllowed(elem1_index) && checkIndexIsAllowed(elem2_index) )
{
basic_item* temp_swap;
temp_swap=thearray[elem1_index];
thearray[elem1_index]=thearray[elem2_index];
thearray[elem2_index]=temp_swap;
return true;
}
return false;
}
// allocate item on heap for the specific type (calling the porper constructor)
basic_item* allocateSpecificItem()
{
basic_item* result = NULL;
if(reference_item!=NULL)
result=reference_item->allocateItem();
return result;
}
// remove item from heap for the specific type (calling the porper distructor)
void deallocateSpecificItem(basic_item* item_ptr)
{
if(reference_item!=NULL && item_ptr!=NULL)
reference_item->deallocateItem(item_ptr);
}
void deallocateArrayContent()
{
if( (memIsAllocated()) && (getMaxSize()>0) )
{
basic_item* curr_elem_ptr;
// delete all items that have been allocated
for(int index=0; index<getMaxSize();index++)
{
curr_elem_ptr=getNremoveElementPtr(index);
// call a function for the specific item
if(curr_elem_ptr!=NULL)
deallocateSpecificItem(curr_elem_ptr);
}
resetCurrIndexDefault();
}
}
void deallocateArray()
{
deallocateArrayContent();
if( (memIsAllocated()) && (getMaxSize()>0) )
{
// now deallocate the memory for the array itself
// if calloc is used to allocate
free(thearray);
// if new is used to allocate
//delete thearray;
thearray=NULL;
memallocated=false;
max_arraysize=0;
}
// option to deallocate the referece item (that was allocated externally)
//if(reference_item!=NULL)
// delete reference_item;
}
// ---- following functions give direct acees to elemt pointers: use for advanced stuff only ----
// gives direct access an element: only to be used by memeber functions;
// It leaves the element in the array.
// [ this is useful for the bubblesort (and mergesort) ]
basic_item *getElementPtr(int index)
{
// check that the memory is allocated and that the element indexes are within array boundary
if( checkIndexIsAllowed(index) )
return thearray[index];
else
return NULL;
}
// It removes the element from the array:
// [ this is useful for the mergesort ]
basic_item *getNremoveElementPtr(int index)
{
// copy the pointer
basic_item *elem_ptr=getElementPtr(index);
if(elem_ptr!=NULL)
{
// clear the pointer in the array, but the moemory it points to is still valid (and the pointer is returned)
thearray[index]=NULL;
tot_items--;
if(tot_items<0)
tot_items=0;
}
return elem_ptr;
}
// insert an element to the array (if requred position is available)
bool insertElementPtr(int index, basic_item* item_ptr)
{
// check that the memory is allocated and that the element index is within array boundary
if(memIsAllocated() && checkIndexIsAllowed(index) )
{
// add the item if array element is not occupied already
if(thearray[index]==NULL)
{
if( (item_ptr!=NULL) )
{
thearray[index]=item_ptr;
tot_items++;
return true;
}
else
{
cout << endl << " Attempting to insert a NULL element." << endl;
return false;
}
}
else
{
cout << endl << " Attempting to overwrite element at position " << index << " : not allowed." << endl;
return false;
}
}
else
return false;
}
// -------------------------------------------------------------------------------------------------
//reset the current index to the default value (-1)
void resetCurrIndexDefault(){current_index=-1;}
//
void basic_initialization()
{
max_arraysize=0; memallocated=false; reference_item=NULL;
tot_items=0; thearray=NULL; resetCurrIndexDefault();
}
public:
general_array(){basic_initialization();}
// the derived object destructor should call deallocateArrayAndContent()
~general_array(){deallocateArray();}
//
bool attachRefrenceItem( basic_item* ref_item_ptr)
{
// only performed once
if(reference_item==NULL && ref_item_ptr!=NULL)
{
reference_item=ref_item_ptr;
return true;
}
return false;
}
//
bool memIsAllocated() {return memallocated;}
int getMaxSize() {return max_arraysize;}
int getTotItems() {return tot_items;}
int getCurrIndex() {return current_index;}
bool allocateArray(int in_arraysize)
{
if( (!memIsAllocated()) && (in_arraysize>0) )
{
if(reference_item==NULL)
{
cout << "Error in allocateArray(): reference item must be allocated first."<< endl;
return false;
}
// calloc guarantees the pointer are set to NULL
thearray=(basic_item **)calloc(in_arraysize, sizeof(basic_item *) );
if(thearray!=NULL)
{
max_arraysize=in_arraysize;
memallocated=true;
// now fill with "empty" integer_items: each needs to be allocated
for(int index=0;index<getMaxSize(); index++)
{
basic_item* emptyitem=allocateSpecificItem();
if(emptyitem==NULL)
{
cout << "Error in allocateArray(): out of memory for item "<< index << endl;
return false;
}
appendElementPtr(emptyitem);
}
resetCurrIndexToZero();
return true;
}
else
return false;
}
return false;
}
//
bool checkIndexIsAllowed(int index)
{
if(memIsAllocated() && index>=0 && index<getMaxSize())
return true;
else
return false;
}
bool resetCurrIndexToZero()
{
if(checkIndexIsAllowed(0))
{
current_index=0;
return true;
}
return false;
}
// to insert or remove elemnts (useful with mergesort)
bool appendElementPtr(basic_item* item_ptr)
{
bool success = insertElementPtr((current_index+1), item_ptr);
if(success)
{
current_index++;
//tot_items++;// not needed: this is done by insertElementPtr
}
return success;
}
basic_item * getNremoveCurrElementPtr()
{
basic_item* result=getNremoveElementPtr(current_index);
current_index++;
tot_items--;
return result;
}
basic_item * getCurrElementPtr()
{
basic_item* result=getElementPtr(current_index);
return result;
}
// to print content to screen with the right format
bool printItemOnScreen(int position)
{
basic_item* elem_ptr=getElementPtr(position);
if(elem_ptr!=NULL)
{
elem_ptr->printItemOnScreen();
return true;
}
return false;
}
void printArrayOnScreen()
{
if( memIsAllocated() && (getTotItems()>0) )
{
// parse all positions
for(int position=0; position<getMaxSize(); position++)
{
cout << "Element Position: "<< position << " ->" << endl;
// print the item, if any
if( printItemOnScreen(position) )
cout << endl;
else
cout << "No Element in this position."<< endl;
}
}
}
// input functions
void enterArrayFromKeyboard()
{
if( memIsAllocated() && (getTotItems()>0) )
{
basic_item *curr_item;
// parse all positions
for(int position=0; position<getMaxSize(); position++)
{
curr_item=getElementPtr(position);
if(curr_item==NULL)
cout << "Element at position "<< position << "is not allocated" << endl;
else
{
if(!curr_item->isEmpty())
cout << "Enter value for element at position "<< position << endl;
else
cout << "Overwriting value for element at position "<< position << "..." << endl;
curr_item->enterItemFromKeyboard();
tot_items++;
}
}
}
}
void fillRandomValueArray()
{
if( memIsAllocated() && (getTotItems()>0) )
{
basic_item *curr_item;
// the following sets the random number generator differently
// for evey execution, depending on the date/time.
srand((unsigned int)time(NULL));
// parse all positions
for(int position=0; position<getMaxSize(); position++)
{
curr_item=getElementPtr(position);
if(curr_item==NULL)
cout << "Element at position "<< position << "is not allocated" << endl;
else
{
curr_item->generateRandomItem();
tot_items++;
}
}
}
}
void findItemsWithinRange(basic_item* min_item, basic_item* max_item, basic_sort_criteria* sort_criteria_ptr = NULL)
{
sort_criteria_ptr->setAscending(true);
for (int curr_index = 0; curr_index < getMaxSize(); curr_index++)
{
basic_item* curr_item = getElementPtr(curr_index);
// in case there are "empty (non allocated) items"
if (curr_item != NULL)
{
if (!curr_item->IsLargerThan(max_item, sort_criteria_ptr)&&!curr_item->IsSmallerThan(min_item, sort_criteria_ptr))
{
cout << "\nElement Position: " << curr_index << " ->" << endl;
printItemOnScreen(curr_index);
}
}
}
}
void findItemsThatMatch(basic_item* search_item, basic_sort_criteria* sort_criteria_ptr)
{
sort_criteria_ptr->setAscending(true);
for (int curr_index = 0; curr_index < getMaxSize(); curr_index++)
{
basic_item* curr_item = getElementPtr(curr_index);
// in case there are "empty (non allocated) items"
if (curr_item != NULL) {
if (curr_item->IsEqualTo(search_item, sort_criteria_ptr))
{
cout << "\nElement Position:" << curr_index << "->" << endl;
printItemOnScreen(curr_index);
}
}
}
}
void findItemsThatInclude(basic_item* search_item, basic_sort_criteria* sort_criteria_ptr)
{
for (int curr_index = 0; curr_index < getMaxSize(); curr_index++)
{
basic_item* curr_item = getElementPtr(curr_index);
// in case there are "empty (non allocated) items"
if (curr_item != NULL) {
if (curr_item->IsWithin(search_item, sort_criteria_ptr))
{
cout << "\nElement Position:" << curr_index << "->" << endl;
printItemOnScreen(curr_index);
}
}
}
}
void findmonthsThatMatch(basic_item* search_month, basic_sort_criteria* sort_criteria_ptr)
{
sort_criteria_ptr->setAscending(true);
for (int curr_index = 0; curr_index < getMaxSize(); curr_index++)
{
basic_item* curr_item = getElementPtr(curr_index);
// in case there are "empty (non allocated) items"
if (curr_item != NULL) {
if (curr_item->FindMonth(search_month, sort_criteria_ptr))
{
cout << "\nElement Position:" << curr_index << "->" << endl;
printItemOnScreen(curr_index);
}
}
}
}
void findyearsThatMatch(basic_item* search_year, basic_sort_criteria* sort_criteria_ptr)
{
sort_criteria_ptr->setAscending(true);
for (int curr_index = 0; curr_index < getMaxSize(); curr_index++)
{
basic_item* curr_item = getElementPtr(curr_index);
// in case there are "empty (non allocated) items"
if (curr_item != NULL) {
if (curr_item->FindYear(search_year, sort_criteria_ptr))
{
cout << "\nElement Position:" << curr_index << "->" << endl;
printItemOnScreen(curr_index);
}
}
}
}
//
void bubblesort(basic_sort_criteria* sort_criteria_ptr=NULL)
{
// Parse the array with a double for loop.
// Select two successive items using the getElementPtr: items A and B
// Use A->IsLargerThan(B); if so, use swapElements(...).
// note: sort_criteria_ptr is an optional paramteter (default is null)
// when present, this can be used to determine the sorting type:
// example 1: "ascending" or "discending" for simple items that hold numbers or strings
// example 2: "sort by name" or "sort by student ID" for complex items that hold both names and numbers
// To be completed by students:
// The version below produces the correct result but performs some unnecessary comparisons.
// Modify it so that it becomes smore efficient
for(int loop_index=0; loop_index<getMaxSize()-1; loop_index++)
{
bool swapped = false;
for(int curr_index=0; curr_index<getMaxSize()-1; curr_index++)
{
bool comparison_result=true;
basic_item* curr_item=getElementPtr(curr_index);
basic_item* next_item=getElementPtr(curr_index+1);
// in case there are "empty (non allocated) items"
if(curr_item!=NULL)
comparison_result=curr_item->IsLargerThan(next_item, sort_criteria_ptr);
if (comparison_result)
{
swapElements(curr_index, curr_index + 1);
swapped = true;
}
}
//cout << "Total loops: " << loop_index << endl;
if (!swapped) break;
}
}
void mergesort(basic_sort_criteria* sort_criteria=NULL)
{
// To be completed by students;
// sugestions (see mergesort for integers):
// Create two "half-size arrays" for the two half/lists.
// Move the items in the input array to the two "half-size arrays" using the getNremoveElementPtr(...) and appendElementPtr(...)
//
// Sort the two "half-size arrays" recursively;
//
// For the two "half-size arrays", write a (privante) subroutine merge_sorted_lists to fill the intial array (now empty but allocated)
// with the two "half-size arrays" that are now sorted; Use A->IsLargerThan(B); .
//
// close recursion for a list of one element
// note: sort_criteria_ptr is an optional paramteter (default is null): see bublerot for examples
}
};
#endif
| true |
c008bbe0e88e10ccaaa0ec4e0e6299c784e0ecc9 | C++ | fxst1/spaceinvader | /src/objects/enemywaves.cc | UTF-8 | 3,559 | 2.546875 | 3 | [] | no_license | #include "spaceinvader.hh"
#include "gameobjects.hh"
Wave::EnemyShip::EnemyShip(Wave* w):
engine::Entity(),
_group(w),
_pv(3),
_last_shoot(0),
_recovery(500),
_move_func(nullptr)
{
std::cout << "* Alloc ship without call move" << std::endl;
}
Wave::EnemyShip::EnemyShip(Wave* w, MoveFunc *mvfunc):
engine::Entity(),
_group(w),
_pv(3),
_last_shoot(0),
_recovery(500),
_move_func(mvfunc)
{
std::cout << "* Alloc ship with call move" << std::endl;
}
Wave::EnemyShip::~EnemyShip(void) {
if (_move_func) delete _move_func;
}
void Wave::EnemyShip::lossPv(engine::Engine & eng) {
_pv--;
(void)eng;
}
std::string Wave::EnemyShip::ID(void) const {
return (":enemy");
}
bool Wave::EnemyShip::canOutScene(void) const {
return (false);
}
void Wave::EnemyShip::onInit(engine::Engine & e) {
(void)e;
}
void Wave::EnemyShip::tick(engine::Engine & e) {
if (this->_pv <= 0 || this->getX() < -100) {
e.removeEntity(this);
} else {
engine::Box old_pos = *this;
this->moveTick(e);
if (_last_shoot > 0) _last_shoot -= e._delta_time;
if (_last_shoot <= 0) {
this->shoot(e, old_pos);
}
}
}
void Wave::EnemyShip::populateBullet(engine::Engine & e) {
Factory f(e, this);
EnemyBullet* bullet = f.enemyBullet( this, 1.0, 0 );
bullet->setX(this->getX());
e.addEntity( bullet );
_last_shoot = _recovery;
}
void Wave::EnemyShip::moveTick(engine::Engine & e) {
if (_move_func == nullptr) {
this->_group->moveFunc(this, e);
}
else {
(*this->_move_func)(this, e);
}
}
void Wave::EnemyShip::shoot(engine::Engine & e, engine::Box const &oldpos) {
if (_last_shoot <= 0 && oldpos.getX() >= 400 && oldpos.getY() < this->getY()) {
this->populateBullet(e);
}
}
void Wave::EnemyShip::onDestroy(engine::Engine & e) {
this->_group->remove(this, e);
Factory f(e, this);
e.addEntity(
f.explosion(this)
);
}
bool Wave::EnemyShip::canCollide(engine::Entity const & e) const {
return (e.ID() == ":player:bullet");
}
void Wave::EnemyShip::onCollide(engine::Engine & engine, engine::Entity & e) {
if (this->_pv > 0) this->_pv--;
if (e.ID() == ":player:bullet") {
engine.removeEntity( &e );
}
(void)engine;
(void)e;
}
/*********************/
Wave::Wave(std::size_t n, MoveFunc * mv):
engine::Entity(),
_n_ennemies(n),
_enemies(),
_move_func(mv)
{}
Wave::~Wave(void) {
//delete _move_func;
}
void Wave::remove(Wave::EnemyShip *en, engine::Engine & e) {
this->_enemies.remove(en);
if (this->_enemies.size() == 0) {
e.removeEntity(this);
}
}
bool Wave::isEmpty(void) const {
return (this->_enemies.size() == 0);
}
void Wave::populate(engine::Engine & e, Game &g) {
Wave::EnemyShip* prev_en = nullptr;
for (std::size_t i = 0; i < _n_ennemies; i++) {
Wave::EnemyShip* en = new Wave::EnemyShip(this);
en->setTexture( g.getTexture("spider") );
en->resize(en->getTexture()->getW(), en->getTexture()->getH());
en->setZ(1);
if (prev_en == nullptr) {
en->move(
(int)e.getScene().getW(),
(int)(e.getScene().getH() / 2) - (en->getH() / 2)
);
}
else {
en->move(prev_en->getX() - 100, prev_en->getY());
}
prev_en = en;
this->_enemies.push_back(en);
e.addEntity(en);
}
}
bool Wave::canOutScene(void) const {
return (true);
}
void Wave::onOutScene(engine::Engine & e) {
(void)e;
}
bool Wave::canCollide(engine::Entity const & e) const {
return (false);
(void)e;
}
void Wave::onDestroy(engine::Engine & e) {
(void)e;
}
void Wave::moveFunc(engine::Entity * ent, engine::Engine & eng) {
if (this->_move_func != nullptr)
(*this->_move_func)(ent, eng);
}
| true |
afdb9a229f4c32713db3535dd816a7a908ad6998 | C++ | fpoinsot/projetMathFinal | /ConsoleApplication1/Grille.cpp | ISO-8859-1 | 13,423 | 2.953125 | 3 | [] | no_license | #include "stdafx.h"
#include "Grille.h"
#include <iostream>
#include <random>
#include "GestionRandom.h"
#include <fstream>
Grille::Grille(int paramDegre) : degre(paramDegre), dimensionTabSudoku(paramDegre*paramDegre), nombreCaseAfficheeEtRemplie(0),nombreCaseRemplie(0)
{
if(paramDegre > 0)
{
tabSudoku = new CaseGrille[dimensionTabSudoku*dimensionTabSudoku];
//initialiser tout les degre de liberte des case au maximum = (degr de la grille)
for(int i = 0; i<dimensionTabSudoku;i++)
{
for(int j=0;j<dimensionTabSudoku;j++)
{
CaseGrille & cursor = getCase(i,j);
cursor.degreLibertee=0;
cursor.ligne=i;
cursor.colonne=j;
}
}
}
}
Grille::~Grille(void)
{
delete[] tabSudoku;
}
CaseGrille & Grille::getCase(int ligne, int colonne)
{
CaseGrille & caseSelect = tabSudoku[ligne*dimensionTabSudoku + colonne];
return caseSelect;
}
bool Grille::setValeurCase(int ligne, int colonne, int valeur)
{
//verifier valeurs
for(int i = 0; i<dimensionTabSudoku; i++)
{
CaseGrille & cursor = getCase( ligne , i);
if( cursor.remplie == true && cursor.valeur == valeur) return false;
}
for(int i = 0; i<dimensionTabSudoku; i++)
{
CaseGrille & cursor = getCase( i, colonne);
if( cursor.remplie == true && cursor.valeur == valeur) return false;
}
//tout est bon
if( !getCase(ligne, colonne).remplie)
{
nombreCaseRemplie ++;
nombreCaseAfficheeEtRemplie++;
}
getCase(ligne, colonne).setValeur(valeur);
return true;
}
bool Grille::setValeurTableau(int* tabValeur)
{
bool reussite = true;
for ( int i=0;i<dimensionTabSudoku;i++)
{
for(int j =0;j<dimensionTabSudoku;j++)
{
if (this->setValeurCase(i,j,tabValeur[i*dimensionTabSudoku + j]) == false )reussite = false;;
}
}
return reussite;
}
int Grille::getValeurCase(int ligne, int colonne)
{
return getCase(ligne, colonne).getValeur();
}
void Grille::getValeurLigne(int ligne, int * resultat)
{
for(int i = 0;i<dimensionTabSudoku;i++)
{
CaseGrille & cursor = getCase(ligne,i);
if(cursor.remplie && cursor.affichee) resultat[i]= cursor.getValeur();
else resultat[i]= -1;
}
}
void Grille::getValeurCollone(int colonne, int * resultat)
{
for(int i = 0;i<dimensionTabSudoku;i++)
{
CaseGrille & cursor = getCase(i,colonne);
if(cursor.remplie && cursor.affichee) resultat[i]= cursor.getValeur();
else resultat[i]= -1;
}
}
void Grille::getValeurCarre(int ligne, int colonne,int* resultat)
{
int numLignePremiereCaseCarre = ligne - (ligne % degre);
int numColonnePremiere = colonne - (colonne%degre);
int index = 0;
for(int i = numLignePremiereCaseCarre;i<(numLignePremiereCaseCarre + degre);i++)
{
for(int j = numColonnePremiere;j<(numColonnePremiere + degre);j++)
{
CaseGrille & cursor = getCase(i,j);
if(cursor.remplie && cursor.affichee) resultat[index]= cursor.getValeur();
else resultat[index]= -1;
index++;
}
}
}
void Grille::afficherGrille()
{
std::ofstream myfile;
myfile.open ("sortie.txt", std::ios::out | std::ios::app);
for(int i =0;i<dimensionTabSudoku;i++)
{
for(int j = 0;j<dimensionTabSudoku;j++)
{
CaseGrille & caseG = this->getCase(i,j);
if ( caseG.remplie == true && caseG.affichee == true)
{
int val = caseG.getValeur();
std::cout << val << ' ';
myfile << val << ' ';
}
else{
std::cout << " ";
myfile << " ";
}
}
std::cout << std::endl;
myfile << std::endl;
}
std::cout << std::endl;
myfile << std::endl;
}
bool Grille::getAfficheCase(int ligne, int colonne){ return getCase(ligne,colonne).affichee;}
bool Grille::getRemplieCase(int ligne, int colonne){ return getCase(ligne,colonne).remplie;}
void Grille::gommerCase(int ligne, int colonne)
{
CaseGrille & cursor = getCase(ligne, colonne);
if(cursor.remplie)
{
nombreCaseRemplie --;
if (cursor.affichee) nombreCaseAfficheeEtRemplie--;
}
cursor.gommerValeur();
}
void Grille::faireApparaitreCase(int ligne, int colonne)
{
CaseGrille & cursor = getCase(ligne, colonne);
if(!cursor.remplie) return; //pas d interet
if(cursor.affichee) return; //pas d interet
cursor.affichee = true;
nombreCaseAfficheeEtRemplie++;
checkDegreLiberteApparrition(ligne,colonne);
}
void Grille::cacherCase(int ligne, int colonne)
{
CaseGrille & cursor = getCase(ligne, colonne);
if(!cursor.remplie) return; //pas d interet
if(!cursor.affichee) return; //pas d interet
cursor.affichee= false;
nombreCaseAfficheeEtRemplie--;
checkDegreLiberte(ligne,colonne);
}
CaseGrille & Grille::tirerCaseRemplieEtAffichee()
{
int dice_roll = tirerUnIntEntre(0,nombreCaseAfficheeEtRemplie-1);
int index =0;
while (dice_roll >0)
{
if(tabSudoku[index].remplie && tabSudoku[index].affichee) dice_roll--;
index++;
}
return tabSudoku[index];
}
void Grille::getLigne(int ligne, CaseGrille** resultat)
{
for(int i = 0; i <dimensionTabSudoku;i++)
{
resultat[i]=&getCase(ligne,i);
}
}
void Grille::getColonne(int colonne,CaseGrille** resultat)
{
for(int i = 0; i <dimensionTabSudoku;i++)
{
resultat[i]=&getCase(i,colonne);
}
}
void Grille::getCarre(int ligne, int colonne,CaseGrille** resultat)
{
int numLignePremiereCaseCarre = ligne - (ligne % degre);
int numColonnePremiere = colonne - (colonne%degre);
int index = 0;
for(int i = numLignePremiereCaseCarre;i<(numLignePremiereCaseCarre + degre);i++)
{
for(int j = numColonnePremiere;j<(numColonnePremiere + degre);j++)
{
CaseGrille & cursor = getCase(i,j);
index++;
}
}
}
void Grille::getCarreTronque(int ligne, int colonne, CaseGrille** resultat)
{
getCarre(ligne,colonne,resultat);
for(int i =0;i<dimensionTabSudoku;i++)
{
if ((resultat[i]->getLigne() == ligne) || (resultat[i]->colonne == colonne))
{
resultat[i] = NULL;
}
}
}
void Grille::checkDegreLiberte(int ligne, int colonne)
{
int valeur = getCase(ligne,colonne).getValeur();
//verifier la ligne modifie
CaseGrille** resultat = new CaseGrille*[dimensionTabSudoku];
getLigne(ligne,resultat);
for(int i = 0;i<dimensionTabSudoku;i++)
{
if(resultat[i]->colonne != colonne)
{
//pour chaques case de la ligne, verifier si la valeur est dans leur pool
bool decrementer = true;
int* pool = new int[dimensionTabSudoku];
getValeurCollone(resultat[i]->colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
getValeurCarre(ligne,resultat[i]->colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
if( decrementer == true) resultat[i]->degreLibertee++;
delete[] pool;
}
}
getColonne(colonne,resultat);
for(int i = 0;i<dimensionTabSudoku;i++)
{
if(resultat[i]->ligne != ligne)
{
//pour chaques case de la ligne, verifier si la valeur est dans leur pool
bool decrementer = true;
int* pool= new int[dimensionTabSudoku];
getValeurLigne(resultat[i]->ligne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
getValeurCarre(resultat[i]->ligne,colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
if( decrementer == true) resultat[i]->degreLibertee++;
delete[] pool;
}
}
getCarreTronque(ligne,colonne,resultat);
for(int i = 0;i<dimensionTabSudoku;i++)
{
if(resultat[i] != NULL)
{
//pour chaques case de la ligne, verifier si la valeur est dans leur pool
bool decrementer = true;
int* pool= new int[dimensionTabSudoku];
getValeurLigne(resultat[i]->ligne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
getValeurCollone(resultat[i]->colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
if( decrementer == true) resultat[i]->degreLibertee++;
delete[] pool;
}
}
getCase(ligne,colonne).degreLibertee++;
delete[] resultat;
}
void Grille::checkDegreLiberteApparrition(int ligne, int colonne)
{
int valeur = getCase(ligne,colonne).getValeur();
//verifier la ligne modifie
CaseGrille** resultat = new CaseGrille*[dimensionTabSudoku];
getLigne(ligne,resultat);
for(int i = 0;i<dimensionTabSudoku;i++)
{
if(resultat[i]->colonne != colonne)
{
//pour chaques case de la ligne, verifier si la valeur est dans leur pool
bool decrementer = true;
int* pool = new int[dimensionTabSudoku];
getValeurCollone(resultat[i]->colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
getValeurCarre(ligne,resultat[i]->colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
if( decrementer == true) resultat[i]->degreLibertee--;
delete[] pool;
}
}
getColonne(colonne,resultat);
for(int i = 0;i<dimensionTabSudoku;i++)
{
if(resultat[i]->ligne != ligne)
{
//pour chaques case de la ligne, verifier si la valeur est dans leur pool
bool decrementer = true;
int* pool= new int[dimensionTabSudoku];
getValeurLigne(resultat[i]->ligne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
getValeurCarre(ligne,resultat[i]->ligne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
if( decrementer == true) resultat[i]->degreLibertee--;
delete[] pool;
}
}
getCarreTronque(ligne,colonne,resultat);
for(int i = 0;i<dimensionTabSudoku;i++)
{
if(resultat[i] != NULL)
{
//pour chaques case de la ligne, verifier si la valeur est dans leur pool
bool decrementer = true;
int* pool= new int[dimensionTabSudoku];
getValeurLigne(resultat[i]->ligne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
getValeurCollone(resultat[i]->colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if(valeur == pool[j]) decrementer = false;
}
if( decrementer == true) resultat[i]->degreLibertee--;
delete[] pool;
}
}
getCase(ligne,colonne).degreLibertee--;
delete[] resultat;
}
void Grille::verifierInitialisationDebutSecondAlgo(){
bool degreLiberteOk = true;
for (int i = 0;i<dimensionTabSudoku;i++)
{
for( int j = 0; j<dimensionTabSudoku;j++)
{
CaseGrille & caseG = getCase(i,j);
if( caseG.degreLibertee != 0)
{
std::cout << "cette case n est pas a 0 au degre de liberte : ligne " << i << " colonne " << j << std::endl;
degreLiberteOk = false;
}
}
}
if (degreLiberteOk) std::cout << "degre de liberte OK " << std::endl;
if(nombreCaseAfficheeEtRemplie != dimensionTabSudoku*dimensionTabSudoku) std::cout << "le nombre de case affiche et remplie est de " << nombreCaseAfficheeEtRemplie << " au lieu de " << dimensionTabSudoku*dimensionTabSudoku << std::endl;
else std::cout << "nombre de case affiche et remplie OK " << std::endl;
if(nombreCaseRemplie != dimensionTabSudoku*dimensionTabSudoku) std::cout << "le nombre de case replie est de " << nombreCaseRemplie << " au lieu de "<< dimensionTabSudoku*dimensionTabSudoku << std::endl;
else std::cout << "nombre de case remplie OK" << std::endl;
}
CaseGrille * Grille::tirerCaseDegree(int degreEtudie,CaseGrille** tabDejaFait )
{
int nbCase=0;
for (int i = 0;i<dimensionTabSudoku;i++)
{
for( int j = 0; j<dimensionTabSudoku;j++)
{
CaseGrille & caseG = getCase(i,j);
if (caseG.degreLibertee == degreEtudie) nbCase++;
}
}
if (nbCase == 0) return NULL;
int alea = tirerUnIntEntre(1,nbCase);
for (int i = 0;i<dimensionTabSudoku;i++)
{
for( int j = 0; j<dimensionTabSudoku;j++)
{
CaseGrille & caseG = getCase(i,j);
if (caseG.degreLibertee == degreEtudie) alea--;
if ( alea == 0) return &caseG;
}
}
//normalement jamais crois
return NULL;
}
void Grille::checkPossibilite(int ligne, int colonne, int* possible)
{
int k = 0;
for(int i=0;i<dimensionTabSudoku;i++)
{
bool test = true;
int* pool = new int[dimensionTabSudoku];
getValeurLigne(ligne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if((i+1) == pool[j]) test = false;
}
getValeurCollone(colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if((i+1) == pool[j]) test = false;
}
getValeurCarre(ligne,colonne,pool);
for(int j=0;j<dimensionTabSudoku;j++)
{
if((i+1) == pool[j]) test = false;
}
if(test==true)
{
k = k+1;
possible[k] = i+1;
}
}
possible[0] = k;
}
double Grille::degreSensibiliteTableau()
{
double moyenne=0;
int nbCase=0;
for (int i =0;i<dimensionTabSudoku;i++)
{
for (int j =0;j<dimensionTabSudoku;j++)
{
moyenne+= getCase(i,j).degreLibertee;
nbCase++;
}
}
return moyenne/ nbCase;
}
double* Grille::degreSensibiliteCase(int ligne, int colonne)
{
double* tabDegre = new double[3];
for (int i = 0;i<3;i++) tabDegre[i]=0;
CaseGrille** resultat = new CaseGrille*[dimensionTabSudoku];
getLigne(ligne,resultat);
for (int i = 0;i<dimensionTabSudoku;i++) tabDegre[0]+=resultat[i]->degreLibertee;
tabDegre[0]= tabDegre[0]/dimensionTabSudoku;
getColonne(colonne,resultat);
for(int i =0;i<dimensionTabSudoku;i++) tabDegre[1]+= resultat[i]->degreLibertee;
tabDegre[1] = tabDegre[1]/dimensionTabSudoku;
getCarre(ligne,colonne,resultat);
for (int i=0;i<dimensionTabSudoku;i++) tabDegre[2]+=resultat[i]->degreLibertee;
tabDegre[2] = tabDegre[2]/dimensionTabSudoku;
delete[] resultat;
return tabDegre;
} | true |
caabe7a2b6d243d2342136a017e772cce0c8cb44 | C++ | shubhham786/Coding | /array and string/test.cpp | UTF-8 | 2,326 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
//To print the matrices
vector<int> kadens_algo_generic_subarry01(vector<int>&arr)
{
int gsum=-(int)1e9,csum=0,gedx=0,csdx=0,gsdx=0;
for(int i=0;i<arr.size();i++)
{
int ele=arr[i];
csum=csum+ele;
if(ele>csum)
{
csum=ele;
csdx=i;
}
//csum=max(ele,csum+ele);
if(csum>gsum){
gsum=csum;
gsdx=csdx;
gedx=i;
}
//gsum=max(csum,gsum);
}
return {gsum,gsdx,gedx};
}
int maximumSumRectangle(int R, int C, vector<vector<int>> M) {
// code here
int gsum=-(int)1e9,csum=0;
int gsri,geri,gsci,geci;
//for(int i=0;i<C;i++)
// ans.push_back(M[0][i]);
// cout<<R<<endl;
for(int i=0;i<R;i++)
{
//fill_n(ans.begin(), C, 0);
vector<int>ans(C,0);
for(int j=i;j<R;j++)
{
csum=0;
for(int k=0;k<C;k++)
{
ans[k]+=M[j][k];
// csum=max(ans[k],csum+ans[k]);
//gsum=max(gsum,csum);
}
// vector<int> kadens_algo_generic_subarry01(vector<int>&arr)
vector<int>a=kadens_algo_generic_subarry01(ans);
//cout<<csum<<" "<<i<<" "<<j<<endl;
if(a[0]>gsum)
{
gsum=a[0];
gsri=i;
geri=j;
gsci=a[1];
geci=a[2];
}
}
}
for(int i=gsri;i<=geri;i++)
{
for(int j=gsci;j<=geci;j++)
{
cout<<M[i][j]<<" ";
}
cout<<endl;
}
return gsum;
}
int main()
{
vector<vector<int>>M(4,vector<int>(5));
M={{1,2,-1,-4,-20},
{-8,-3,4,2,1},
{3,8,10,1,3},
{-4,-1,1,7,-6}};
int gsum=maximumSumRectangle(4,5,M);
//seggrate_0_1_2(arr);
// cout<<arr.size();
// for(int i:arr)
//{
// cout<<i<<" ";
//}
return 0;
} | true |
674342e993a0134eb832ce4896af183deb733f5c | C++ | bavernet/cpp-idioms | /day3/7_value_type2.cpp | UTF-8 | 531 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <list>
using namespace std;
// 반복자는 결국 클래스타입의 객체입니다.
// template <typename T>
// class vector_iterator {
// typedef T value_type;
// };
template <typename T>
typename T::value_type Sum(T first, T last) {
typename T::value_type s = typename T::value_type();
for (T it = first; it != last; ++it)
s += *it;
return s;
}
int main() {
list<double> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int n = Sum(v.begin(), v.end());
cout << n << endl;
}
| true |
e6a3164d6eddceab72a13fb387259a77ea37b030 | C++ | tim37021/R3D | /include/r3d/Pipeline/PostFX.hpp | UTF-8 | 1,806 | 2.84375 | 3 | [] | no_license | #ifndef __R3D_PIPELINE_POSTFX_HPP_
#define __R3D_PIPELINE_POSTFX_HPP_
#include <list>
#include <string>
#include <memory>
namespace r3d
{
class PostEffect;
class PostFX;
class Engine;
class ContextWindow;
class VertexArray;
class RenderTarget2D;
class Texture2D;
typedef std::shared_ptr<RenderTarget2D> RenderTarget2DPtr;
class PostEffectInstancer
{
public:
PostEffectInstancer()=default;
PostEffectInstancer(PostEffect *(*ctor)(PostFX *, Texture2D *), void (*dtor)(PostEffect *)):
m_constructor(ctor), m_destructor(dtor){}
PostEffectInstancer(const PostEffectInstancer &)=default;
PostEffect *newPostEffect(PostFX *pfx, Texture2D *input) { return m_constructor(pfx, input); }
void freePostEffect(PostEffect *effect) { m_destructor(effect); }
private:
PostEffect *(*m_constructor)(PostFX *, Texture2D *);
void (*m_destructor)(PostEffect *);
};
class PostEffect
{
public:
PostEffect(PostFX *pfx, const std::string &effectName, Texture2D *input);
virtual ~PostEffect(){}
virtual void run()=0;
virtual Texture2D *getResult()=0;
const std::string getName() const
{ return m_effectName; }
protected:
PostFX *m_pfx;
Engine *m_engine;
std::string m_effectName;
Texture2D *m_text;
ContextWindow *m_cw;
};
class PostFX
{
public:
PostFX(Engine *m_engine, ContextWindow *cw);
~PostFX();
void runAll();
PostEffect *pushEffect(const std::string &effectName, Texture2D *input);
void clear();
static void Initialise();
Engine *getEngine() { return m_engine; }
ContextWindow *getContextWindow() { return m_cw; }
private:
Engine *m_engine;
ContextWindow *m_cw;
std::list<PostEffect *> effects;
};
class PostFXFactory
{
public:
static void RegisterEffect(const std::string &name, PostEffectInstancer);
};
}
#endif | true |
07e6540b8a958a17a076eea6f2bdb8a6d06dc874 | C++ | kuzemczak/PAMSI_Projekt1 | /vectorAddon.h | UTF-8 | 376 | 3.15625 | 3 | [] | no_license | #ifndef VECTORADDON_H
#define VECTORADDON_H
#include <iostream>
template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) {
if (!v.empty()) {
out << '[';
for (T element : v)
out << element << ", ";
out << "\b\b]";
}
return out;
}
template<typename T>
void Swap(T & v0, T & v1)
{
T tmp = v0;
v0 = v1;
v1 = tmp;
}
#endif
| true |
cff9077159d80610bec690a9f1680961b0cb0633 | C++ | lonkaars/avans-kluis | /ReadSwitch/ReadSwitch.ino | UTF-8 | 557 | 2.8125 | 3 | [
"MIT"
] | permissive | int drukKnop = 12; //Hier initialiseer je de waarden
int led = A0;
int StaatdrukKnop = LOW; //Staat van de druktoets instellen
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT); //LED instellen als uitvoer
pinMode(drukKnop, INPUT); //Druktoets instellen als invoer
}
void loop() {
StaatdrukKnop = digitalRead(drukKnop); //Staat van de druktoets de waarde geven van het uitlezen van de druktoets
Serial.println(StaatdrukKnop);
if (StaatdrukKnop == HIGH){
digitalWrite(led, HIGH);
} else {
digitalWrite(led, LOW);
}
}
| true |
9483ca067454a03ae9b30c3296c23a2a8d01a9fa | C++ | Ivonhoe/LeetCode | /c++/src/leetcode/editor/cn/127-WordLadder.cpp | UTF-8 | 2,672 | 3.375 | 3 | [] | no_license | //给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
//
//
//
// 每次转换只能改变一个字母。
// 转换过程中的中间单词必须是字典中的单词。
//
//
// 说明:
//
//
// 如果不存在这样的转换序列,返回 0。
// 所有单词具有相同的长度。
// 所有单词只由小写字母组成。
// 字典中不存在重复的单词。
// 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
//
//
// 示例 1:
//
// 输入:
//beginWord = "hit",
//endWord = "cog",
//wordList = ["hot","dot","dog","lot","log","cog"]
//
//输出: 5
//
//解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
// 返回它的长度 5。
//
//
// 示例 2:
//
// 输入:
//beginWord = "hit"
//endWord = "cog"
//wordList = ["hot","dot","dog","lot","log"]
//
//输出: 0
//
//解释: endWord "cog" 不在字典中,所以无法进行转换。
// Related Topics 广度优先搜索
// 👍 642 👎 0
#include "string"
#include "queue"
#include "unordered_set"
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
unordered_set<string> wordSet(wordList.begin(), wordList.end());
// 如果endWord没有在wordSet出现,直接返回0
if (wordSet.find(endWord) == wordSet.end()) return 0;
// 初始化队列
queue<pair<string, int>> que;
que.push(pair<string, int>(beginWord, 1));
while (!que.empty()) {
pair<string, int> word = que.front();
que.pop();
if (word.first == endWord) {
return word.second;
}
// 将当前string的每个字符挨个替换成a~z,看wordSet里面有没有,复杂度降为26*word.size()
for (int i = 0; i < word.first.size(); i++) {
string newWord = word.first; // 用一个新单词替换word,因为每次置换一个字母
for (int j = 0; j < 26; j++) {
newWord[i] = j + 'a';
// 找到邻接的string,入队
if (wordSet.find(newWord) != wordSet.end()) {
que.push(pair<string, int>(newWord, word.second + 1));
wordSet.erase(newWord);
}
}
}
}
return 0;
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
return 0;
} | true |
339785c2267ce01d3f1c1882a5b3188f374ae4fa | C++ | vivi/bess | /core/utils/ip_test.cc | UTF-8 | 1,302 | 2.8125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "ip.h"
#include <gtest/gtest.h>
using bess::utils::be32_t;
namespace {
using bess::utils::Ipv4Prefix;
// Check if Ipv4Prefix can be correctly constructed from strings
TEST(IPTest, CIDRInStr) {
Ipv4Prefix prefix_1("192.168.0.1/24");
EXPECT_EQ((192 << 24) + (168 << 16) + 1, prefix_1.addr.value());
EXPECT_EQ(0xffffff00, prefix_1.mask.value());
Ipv4Prefix prefix_2("0.0.0.0/0");
EXPECT_EQ(0, prefix_2.addr.value());
EXPECT_EQ(0, prefix_2.mask.value());
Ipv4Prefix prefix_3("128.0.0.0/1");
EXPECT_EQ(128 << 24, prefix_3.addr.value());
EXPECT_EQ(0x80000000, prefix_3.mask.value());
}
// Check if Ipv4Prefix::Match() behaves correctly
TEST(IPTest, CIDRMatch) {
Ipv4Prefix prefix_1("192.168.0.1/24");
EXPECT_TRUE(prefix_1.Match(be32_t((192 << 24) + (168 << 16) + 254)));
EXPECT_FALSE(
prefix_1.Match(be32_t((192 << 24) + (168 << 16) + (2 << 8) + 1)));
Ipv4Prefix prefix_2("0.0.0.0/0");
EXPECT_TRUE(prefix_2.Match(be32_t((192 << 24) + (168 << 16) + 254)));
EXPECT_TRUE(prefix_2.Match(be32_t((192 << 24) + (168 << 16) + (2 << 8) + 1)));
Ipv4Prefix prefix_3("192.168.0.1/32");
EXPECT_FALSE(prefix_3.Match(be32_t((192 << 24) + (168 << 16) + 254)));
EXPECT_TRUE(prefix_3.Match(be32_t((192 << 24) + (168 << 16) + 1)));
}
} // namespace (unnamed)
| true |
1e1a63bcefadf9e8df000d4a04eebb272c1acdd4 | C++ | SvetlanaZhurba/Queue-and-time | /queue.cpp | UTF-8 | 4,092 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include "queue.h"
#include "node.h"
using namespace std;
queue::queue()
{
end = nullptr;
}
queue::~queue()
{
node *ptr = end;
while( ( ptr = end ) != nullptr )
{
end = end->getprev();
delete ptr;
ptr = nullptr;
}
delete end;
end = nullptr;
}
void queue::show()
{
node *ptr = end;
cout << "Конец очереди" << endl;
while( ptr != nullptr )
{
cout << ptr->getval() << endl;
ptr = ptr->getprev();
}
cout << "Начало очереди" << endl;
}
queue& queue::operator = ( int &a )
{
setlocale( LC_ALL, "Rus" );
node *ptr = end;
if( ptr != nullptr )
while( ptr->getprev() != nullptr && ptr->getprev()->getprev() != nullptr )
ptr = ptr->getprev();
if( ptr != nullptr && ptr->getprev() != nullptr )
{
cout << endl << "Вы извлекли: " << ptr->getprev()->getval() << endl;
a = ptr->getprev()->getval();
delete ptr->getprev();
ptr->setprev( nullptr );
}
else if( ptr != nullptr && ptr->getprev() == nullptr )
{
cout << endl << "Вы извлекли: " << ptr->getval() << endl;
a = ptr->getval();
delete end;
end = nullptr;
}
else
cout << endl << "Очередь пуста" << endl;
return *this;
}
queue& queue::operator = ( queue &q )
{
node *p1 = end;
node *p2 = q.end;
if( end == nullptr )
{
end = new node;
p1 = end;
}
while( p2 )
{
p1->setval( p2->getval() );
p2 = p2->getprev();
if( p2 != nullptr )
{
p1->setprev( new node );
p1 = p1->getprev();
}
else
p1->setprev( nullptr );
}
return *this;
}
queue& queue::operator + ( queue &q )
{
node *p1 = end;
node *p2 = q.end;
queue *qr = new queue;
qr->end = new node;
node *p = qr->end;
show();
cout << "------------------" << endl;
q.show();
cout << "------------------" << endl;
while( p1 != nullptr && p2 != nullptr )
{
p->setval( p1->getval() + p2->getval() );
p1 = p1->getprev();
p2 = p2->getprev();
if( p1 != nullptr && p2 != nullptr )
{
p->setprev( new node );
p = p->getprev();
}
else
p->setprev( nullptr );
}
qr->show();
return *qr;
}
queue& queue::operator * ( queue &q )
{
node *p1 = end;
node *p2 = q.end;
queue *qr = new queue;
qr->end = new node;
node *p = qr->end;
show();
cout << "------------------" << endl;
q.show();
cout << "------------------" << endl;
while( p1 != nullptr && p2 != nullptr )
{
p->setval( p1->getval() * p2->getval() );
p1 = p1->getprev();
p2 = p2->getprev();
if( p1 != nullptr && p2 != nullptr )
{
p->setprev( new node );
p = p->getprev();
}
else
p->setprev( nullptr );
}
qr->show();
return *qr;
}
queue& queue::operator / ( int n )
{
node *p1 = end;
queue *qr = new queue;
qr->end = new node;
node *p = qr->end;
show();
cout << "------------------" << endl;
while( p1 != nullptr )
{
p->setval( p1->getval() / n );
p1 = p1->getprev();
if( p1 != nullptr )
{
p->setprev( new node );
p = p->getprev();
}
else
p->setprev( nullptr );
}
qr->show();
return *qr;
}
queue& operator - ( queue &q1, queue &q2 )
{
node *p1 = q1.end;
node *p2 = q2.end;
queue *qr = new queue;
qr->end = new node;
node *p = qr->end;
q1.show();
cout << "------------------" << endl;
q2.show();
cout << "------------------" << endl;
while( p1 != nullptr && p2 != nullptr )
{
p->setval( p1->getval() - p2->getval() );
p1 = p1->getprev();
p2 = p2->getprev();
if( p1 != nullptr && p2 != nullptr )
{
p->setprev( new node );
p = p->getprev();
}
else
p->setprev( nullptr );
}
qr->show();
return *qr;
}
queue& operator += ( queue &q1, int n )
{
if( q1.end == nullptr )
{
q1.end = new node;
q1.end->setprev( nullptr );
q1.end->setval( n );
}
else
{
node *ptr = new node;
ptr->setprev( q1.end );
ptr->setval( n );
q1.end = ptr;
}
q1.show();
return q1;
}
| true |
492bc6a13c8274c682770745f62fd2a2c350eb53 | C++ | chiragxarora/SDE-SHEET | /Arrays/merge2sortedArrays.cpp | UTF-8 | 2,101 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <math.h>
#include <unordered_map>
#include <unordered_set>
#include <climits>
#include <utility>
#include <iomanip>
using namespace std;
// https://www.geeksforgeeks.org/efficiently-merging-two-sorted-arrays-with-o1-extra-space/
void approach1(vector<int>& v1, vector<int>& v2) {
int a = 0;
while(a<v1.size()) {
if(v1[a]>v2[0]){
// swap
swap(v1[a],v2[0]);
// rearrange
int val = v2[0], i=0;
while(i<v2.size()-1&&v2[i+1]<val) {
v2[i] = v2[i+1];
i++;
}
v2[i] = val;
}
a++;
}
}
void approach2(vector<int>& v1, vector<int>& v2) {
int i = 0, j = 0, k = v1.size()-1;
while(i<=k && j<v2.size()){
if(v1[i]>v2[j]){
swap(v1[k],v2[j]);
k--;
j++;
}
i++;
}
sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
}
void approach3(vector<int>& v1, vector<int>& v2) {
int gap = ceil((v1.size() + v2.size())/2);
int i = 0, j = gap;
while(1) {
i = 0;
j = gap;
while(j<v1.size() + v2.size()){
int ii = i, jj = j;
if(i>=v1.size()){
ii -= v1.size();
jj -= v1.size();
if(v2[ii] > v2[jj]) swap(v2[ii],v2[jj]);
}
else {
if(j>=v1.size()){
jj -= v1.size();
if(v1[ii] > v2[jj]) swap(v1[ii],v2[jj]);
}
else {
if(v1[ii] > v1[jj]) swap(v1[ii],v1[jj]);
}
}
i++;
j++;
}
if(gap==1) break;
gap = ceil(gap/2);
}
for(auto v : v1) cout<<v<<" ";
cout<<endl;
for(auto v : v2) cout<<v<<" ";
cout<<endl;
}
int main() {
vector<int> v1 {1,4,7,8};
vector<int> v2 {2,3,9};
// approach1(v1,v2);
// approach2(v1,v2);
approach3(v1,v2);
return 0;
} | true |
dfc11a0347eb88082518db7b84a3058c95f12761 | C++ | shaked6/splProject | /src/Watchable.cpp | UTF-8 | 1,405 | 2.734375 | 3 | [] | no_license | //
// Created by shaked on 25/11/2019.
//
#include <iostream>
#include "../include/Action.h"
#include "../include/Session.h"
#include "../include/Watchable.h"
using namespace std;
int Watchable::getLength() const {
return this->length;
}
std::vector<std::string> Watchable::getTags() const {
return this->tags;
}
int Episode::getSeason() const {
return this->season;
}
int Episode::getEpisodeNumber() const{
return this->episode;
}
std::string Movie::toString() const {
std::string str = ""+getName() + " " + to_string(this->getLength())+ " minutes [";
for(int i=0;i<getTags().size();i++){
str+=getTags().at(i);
if(getTags().size()-1) str+=", ";
}
str+="]";
return str;
}
std::string Episode::toString() const {
std::string str = ""+getName() + " S";
if(this->getSeason()<10)
str+="0"+to_string(getSeason())+"E";
else str+=to_string(getSeason())+"E";
if(this->getEpisodeNumber()<10)
str+="0"+to_string(getEpisodeNumber())+" ";
else str+=to_string(getEpisodeNumber())+" ";
str+= to_string(this->getLength())+ " minutes [";
for(int i=0;i<getTags().size();i++){
str+=getTags().at(i);
if(getTags().size()-1) str+=", ";
}
str+="]";
return str;
}
std::string Movie::getName() const{
return this->name;
}
std::string Episode::getName() const{
return this->seriesName;
} | true |
796d153c4d59e9dce135ae397e37fc8370a759f3 | C++ | Jorgefiestas/CompetitiveProgramming | /Codeforces/CF1303A.cpp | UTF-8 | 429 | 2.796875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int t, z, zo;
string str;
int main() {
cin >> t;
while (t--) {
z = 0;
zo = 0;
cin >> str;
bool seenOne = false;
for (char c : str) {
if (!seenOne && c != '1') {
continue;
}
else if (!seenOne && c == '1') {
seenOne = true;
}
else if (c == '0') {
z++;
zo++;
}
else {
zo = 0;
}
}
cout << z - zo << '\n';
}
return 0;
}
| true |
b52e2d7d9fbb9942b9dac9fa88bce007f7b07b5f | C++ | StabCrab/Data_Structures | /ShuntingYard/Token.cpp | UTF-8 | 943 | 3.203125 | 3 | [] | no_license | //
// Created by trykr on 18.05.2020.
//
#include "Token.h"
Token::Token()
{
this->token ="ERROR";
this->tokenType = TokenType::Number;
this->value = 0;
}
Token::Token(std::string token, TokenType tokenType)
{
this->token = std::move(token);
this->tokenType = tokenType;
this->value = 0; //чисто по преколу
}
Token::Token(std::string token, double value, TokenType tokenType)
{
this->token = std::move(token);
this->tokenType = tokenType;
this->value = value;
}
Token::~Token()
{
}
bool Token::operator==(Token token)
{
return this->tokenType == token.tokenType && this->token == token.token && this->value == token.value;
}
std::string Token::getToken() const
{
return this->token;
}
double Token::getValue() const {
return this->value;
}
TokenType Token::getTokenType() const {
return this->tokenType;
}
void Token::setValue(double val)
{
this->value = val;
}
| true |
309c8e1d948a60a45dc5ca1ece916eb0f126f75d | C++ | VekotinVerstas/NoiseSensorWorkshop | /arduino/i2s_Spectrum_test/i2s_Spectrum_test.ino | UTF-8 | 3,325 | 2.796875 | 3 | [
"MIT"
] | permissive | /*
This example reads audio data from an Invensense's ICS43432 I2S microphone
breakout board, and prints out the spectrum to the Serial console. The
Serial Plotter built into the Arduino IDE can be used to plot the audio
amplitude data (Tools -> Serial Plotter)
Circuit:
* Arduino/Genuino Zero, MKRZero or MKR1000 board
* ICS43432:
* GND connected GND
* 3.3V (3V) connected 3.3V (Zero) or VCC (MKR1000, MKRZero)
* WS (LRCL) connected to pin 0 (Zero) or pin 3 (MKR1000, MKRZero)
* CLK (BCLK) connected to pin 1 (Zero) or pin 2 (MKR1000, MKRZero)
* SD (DOUT) connected to pin 9 (Zero) or pin A6 (MKR1000, MKRZero)
created 21 November 2016
by Sandeep Mistry
*/
// This is originated from i2s_SpectrumSerialPlotter
#include <ArduinoSound.h>
// sample rate for the input
const int sampleRate = 8192;
// size of the FFT to compute
const int fftSize = 64;
// size of the spectrum output, half of FFT size
const int spectrumSize = fftSize / 2;
// array to store spectrum output
int spectrum[spectrumSize];
// array to store spectrum average
int spectrum_avg[spectrumSize];
// create an FFT analyzer to be used with the I2S input
FFTAnalyzer fftAnalyzer(fftSize);
// const bool single = true; // Print multiple values (false) or just one (true)
const bool single = false; // Print multiple values (false) or just one (true)
void setup() {
// Open serial communications and wait for port to open:
// A baud rate of 115200 is used instead of 9600 for a faster data rate
// on non-native USB ports
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// setup the I2S audio input for the sample rate with 32-bits per sample
if (!AudioInI2S.begin(sampleRate, 32)) {
Serial.println("Failed to initialize I2S input!");
while (1); // do nothing
}
// configure the I2S input as the input for the FFT analyzer
if (!fftAnalyzer.input(AudioInI2S)) {
Serial.println("Failed to set FFT analyzer input!");
while (1); // do nothing
}
}
void loop() {
int last_save = millis();
int sample_cnt = 0;
// Loop until 1000 ms is gone
while ((millis() - last_save) < 1000) {
// check if a new analysis is available
if (fftAnalyzer.available()) {
sample_cnt++;
// read the new spectrum
fftAnalyzer.read(spectrum, spectrumSize);
// Add all values to avg array
for (int i = 0; i < spectrumSize; i++) {
spectrum_avg[i] += spectrum[i];
}
}
}
for (int i = 0; i < spectrumSize; i++) {
spectrum_avg[i] /= sample_cnt;
}
int g_start_idx = 1;
//int g_stop_idx = 20; // or spectrumSize
int g_stop_idx = spectrumSize;
int g_step = 1;
// print out the spectrum
if (single) {
for (int i = g_start_idx; i < g_stop_idx; i++) {
Serial.print((i * sampleRate) / fftSize); // the starting frequency
Serial.print("\t"); //
Serial.println(spectrum_avg[i]); // the spectrum value
}
} else {
// print out the spectrum, multiple lines
for (int i = g_start_idx; i < g_stop_idx; i += g_step) {
Serial.print((i * sampleRate) / fftSize); // the starting frequency
Serial.print("\t"); //
Serial.print(spectrum_avg[i]); // the spectrum value
Serial.print("\t"); //
}
Serial.println();
}
}
| true |
8fe103a5312c2bb5e32931fc2deaead7663cf716 | C++ | Falcon22/TowerDefense | /src/Units/Warrior/Warrior.cpp | UTF-8 | 1,678 | 2.984375 | 3 | [] | no_license | #include "Warrior.h"
Warrior::Warrior(Type type, const sf::Vector2f& position, const Map::LogicMap& logicMap, int cost,
float velocity, int hp)
: GameUnit(type, position),
logicMap_(logicMap),
direction_(0),
alive_(true),
finished_(false),
cost_(cost),
velocity_(velocity),
hp_(hp){
}
void Warrior::update(const sf::Time &dTime) {
if (!alive_) {
return;
}
if (logicMap_.finish.contains(position_)) {
finished_ = true;
return;
}
Map::Direction direction = Map::UP;
for (auto part : logicMap_.road) {
if (part.first.contains(position_)) {
direction = part.second;
break;
}
}
switch (direction) {
case Map::UP:
position_.y -= velocity_ * dTime.asSeconds();
direction_ = 270;
break;
case Map::DOWN:
position_.y += velocity_ * dTime.asSeconds();
direction_ = 90;
break;
case Map::LEFT:
position_.x -= velocity_ * dTime.asSeconds();
direction_ = 180;
break;
case Map::RIGHT:
position_.x += velocity_ * dTime.asSeconds();
direction_ = 0;
break;
}
}
float Warrior::getDirection() const {
return direction_;
}
int Warrior::getHp() const {
return hp_;
}
const int Warrior::getCost() const {
return cost_;
}
bool Warrior::isAlive() const {
return alive_;
}
bool Warrior::isFinished() const {
return finished_;
}
void Warrior::suffer(int damage) {
hp_ -= damage;
if (hp_ <= 0) {
alive_ = false;
}
}
| true |
0d200ce3c5bf289a5040ff7bc67e04197763ec54 | C++ | yunqingjia/feron_drone | /ATtiny85 Code/ATtiny85_ESC_Test/ATtiny85_ESC_test.ino | UTF-8 | 1,686 | 3.234375 | 3 | [] | no_license | // Simple program to test the ATtiny85's
// ability to control ESCs/Brushless Motors
#include "SoftwareSerial.h"
#include "Servo8Bit.h"
#define ESC_PIN (0) // PWM pin for signaling ESC
#define RX_PIN (3) // RX pin for SoftwareSerial
#define TX_PIN (4) // TX pin for SoftwareSerial
#define DRIVE_PIN (1) // Drive pin for power MOSFET
// Initialize SoftwareSerial pins
SoftwareSerial mySerial(RX_PIN, TX_PIN);
// Create an Servo8Bit object
Servo8Bit ESC;
int speed = 0;
void arm(){
digitalWrite(DRIVE_PIN, HIGH);
setSpeed(0); //Sets speed variable
delay(1000);
}
/* Callibrate ESC's PWM range for first use */
void callibrate(Servo8Bit *ESC) {
digitalWrite(DRIVE_PIN, LOW); // Disconnect ESC from power
delay(500); // Wait 500ms
setSpeed(1000); // Request full speed
digitalWrite(DRIVE_PIN, HIGH); // Reconnect ESC to power
delay(5000); // Wait 5s
setSpeed(0); // Request 0 speed
}
void setSpeed(int input_speed){
int us = map(input_speed, 0, 1000, 1000, 2000); //Sets servo positions to different speed
ESC.writeMicroseconds(us);
}
void setup() {
// Initialize serial communication
mySerial.begin(9600);
// Configure MOSFET drive pin
pinMode(DRIVE_PIN, OUTPUT);
digitalWrite(DRIVE_PIN, LOW);
ESC.attach(0); //Adds ESC to certain pin.
arm();
}
void loop() {
if (mySerial.available()) {
if (mySerial.peek() == ' ') {
mySerial.println("Callibrating ESC");
callibrate(&ESC);
mySerial.read();
} else {
speed = mySerial.parseInt();
mySerial.println(speed);
setSpeed(speed);
}
}
}
| true |
333266c3c59421fdc7018b1caba3bab5064ac39f | C++ | menghuadong/FaceAndEyeDetect | /main.cpp | GB18030 | 4,218 | 2.703125 | 3 | [] | no_license | //--üʵּ
//--By Steven Meng 2012.11.29
//עӦobject.dllļ.xml
//ļŵǰĹĿ¼
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/ml/ml.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
//--
void detectAndDisplay(Mat);
//--ȫֱ
string eyes_cascade_name="./haarcascade_eye_tree_eyeglasses.xml";
string face_cascade_name="./haarcascade_frontalface_alt.xml";
string window_name="Capture-Face detection";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
RNG rng(12345);
int main()
{
CvCapture* capture;//CvCaptureΪṹ
cv::Mat frame;
//--1.ļ
if (!face_cascade.load(face_cascade_name))
{
printf("Error loading .xml file");
return 1;
}
if (!eyes_cascade.load(eyes_cascade_name))
{
printf("Error loading .xml file");
return 1;
}
//--2.ͷ
capture=cvCaptureFromCAM(-1);
if (capture)
{
printf("Open Carmer Success.");
while (true)
{
frame=cvQueryFrame(capture);//ȡ
//--3.Եǰʹ÷м
if (!frame.empty())
{
detectAndDisplay(frame);
}
else
{
printf("No Capture frame --Break!");
break;
}
int key=waitKey(10);//C
if ((char)key=='c')
{
break;
}
}
}
return 0;
}
//--岿
void detectAndDisplay(Mat frame)
{
double scale = 1.3;
std::vector<Rect> faces;//
std::vector<Rect> eyes;
Mat frame_gray,small_image(cvRound(frame.rows/scale),cvRound(frame.cols/scale),CV_8UC1);//ͼƬߴСڼӿٶȣЧ
//--תɻҶͼһ
cv::cvtColor(frame,frame_gray,CV_BGR2GRAY);
cv::resize(frame_gray,small_image,small_image.size(),0,0,INTER_LINEAR);//ߴС1/scaleԲ
cv::equalizeHist(small_image,small_image);
//-- ⲿ
//detectMultiScalesmall_imgeʾҪͼΪsmallImgfacesʾĿУ1.1ʾ
//ÿͼߴСıΪ1.12ʾÿһĿҪ3βĿ(ΪΧغͲͬĴڴ
//СԼ),CV_HAAR_SCALE_IMAGEʾŷ⣬ͼSize(30, 30)ΪĿ
//Сߴ
face_cascade.detectMultiScale(small_image,faces,1.1,2,0|CV_HAAR_SCALE_IMAGE,Size(30,30));
/*--ûСͼƬߴķ
for (int i=0;i<faces.size();i++)
{
Point center( (faces[i].x + faces[i].width*0.5), (faces[i].y + faces[i].height*0.5) );
ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
Mat faceROI = frame_gray( faces[i] );
std::vector<Rect> eyes;
//-- ÿϼ˫
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( int j = 0; j < eyes.size(); j++ )
{
Point center( (faces[i].x + eyes[j].x + eyes[j].width*0.5), (faces[i].y + eyes[j].y + eyes[j].height*0.5 ));
int radius = cvRound( (eyes[j].width + eyes[i].height)*0.25 );
circle( frame, center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 );
}
}*/
for (vector<Rect>::const_iterator r=faces.begin();r!=faces.end();r++)
{
Point center;
int radius=cvRound((r->width+r->height)*0.25*scale);
center.x=cvRound((r->x+r->width *0.5)*scale);
center.y=cvRound((r->y+r->height *0.5)*scale);
cv::circle(frame,center,radius,cv::Scalar(0,0,255),3,8,0);
//ϵ۾
cv::Mat small_image_ROI=small_image(*r);
eyes_cascade.detectMultiScale(small_image_ROI,eyes,1.1,2,0|CV_HAAR_SCALE_IMAGE,Size(30,30));
for (vector<Rect>::const_iterator r1=eyes.begin();r1!=eyes.end();r1++)
{
int radius=cvRound((r1->width+r1->height)*0.25*scale);
center.x=cvRound((r->x+r1->x+r1->width *0.5)*scale);
center.y=cvRound((r->y+r1->y+r1->height *0.5)*scale);
cv::circle(frame,center,radius,cv::Scalar(0,255,0),3,8,0);
}
}
imshow(window_name,frame);
} | true |
cb476ae9c5c4d3e62c5d16748ba83754a6a03b92 | C++ | kityprincess/ponder12-spellchecker | /sp/sp/spellCheck.cpp | UTF-8 | 5,630 | 3.328125 | 3 | [] | no_license | /***********************************************************************
* Module:
* Week 12, Spell Check
* Brother Helfrich, CS 235
* Author:
* <your name here>
* Summary:
* This program will implement the spellCheck() function
************************************************************************/
#ifdef DEBUG
#define Debug(x) (x);
#else
#define Debug(x)
#endif
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "spellCheck.h"
#include "hash.h"
#include <vector>
using namespace std;
void readDictionary(SHash & dictionaryTable);
void readFile(SHash & dictionaryTable, vector <string> & missSpelled);
/****************************************
* SPELL CHECK
* Prompt the user for a file to spell-check
****************************************/
void spellCheck()
{
// Lets create a table to store the words.
// tested bucket counts between 2 and 256
// and found 179 has the best range and no
// empty buckets
SHash dictionaryTable = SHash(179);
// Lets store the strings in a vector
vector <string> missSpelled = vector <string>();
readDictionary(dictionaryTable);
readFile(dictionaryTable, missSpelled);
// Time to check for misspelled words and go through them one by one
if (missSpelled.size() > 0)
{
cout << "Misspelled: ";
// Going through the misspelled words and showing them
cout << missSpelled[0];
for (int i = 1; i < missSpelled.size(); i++)
{
cout << ", ";
cout << missSpelled[i];
}
cout << endl;
}
// If there are no misspelled words, we will let them know
else
cout << "File contains no spelling errors\n";
}
/*******************************************************
* READ DICTIONARY
* Opens and reads the dictionary file
*********************************************************/
void readDictionary(SHash & dictionaryTable)
{
string word;
// since the dictionary file is always the same, we just
// enter it into the ifstream ourselves
//
#ifdef DEBUG
ifstream fin("dictionary.txt");
#else
ifstream fin("/home/cs235/week12/dictionary.txt");
#endif
if (fin.fail())
{
cout << "Error, cannot read file";
fin.close();
}
// lets bring the whole file in now
while (!fin.eof() && fin >> word)
{
// lets insert our incoming data into the table
dictionaryTable.insert(word);
}
fin.close();
Debug(cout << "Empty Bucket Count: " << dictionaryTable.emptyBucketCount() << endl);
#ifdef DEBUG
int min, max, range;
range = dictionaryTable.bucketCountRange(min, max);
cout << "Bucket Range: " << range << "(" << min << ".." << max << ")\n";
#endif
Debug(dictionaryTable.displayDistribution());
}
/*******************************************************
* READ FILE
* Opens and reads a file
*********************************************************/
void readFile(SHash & dictionaryTable, vector <string> & missSpelled)
{
string word;
string fileName;
string lowerCaseWord;
// lets pull in the file from the user and make sure it opens
cout << "What file do you want to check? ";
cin >> fileName;
ifstream fin(fileName.c_str());
if (fin.fail())
{
cout << "Error, cannot read file";
fin.close();
}
// It opened so we are going to bring in the file
while (!fin.eof() && fin >> word)
{
// Lets make sure the file converts our letters to lowercase
// since that is what compares to the dictionary words
lowerCaseWord = word;
lowerCaseWord[0] = tolower(lowerCaseWord[0]);
// If the user file doesn't match the dictionary file, lets
// separate it so we can keep track
if (!dictionaryTable.find(lowerCaseWord))
{
missSpelled.push_back(word);
}
}
fin.close();
}
#ifdef DEBUG
/****************************************************************************
* SHASH :: EMPTY BUCKET COUNT
* For debugging purposes only. Counts the number of buckets in the hash table
* that are empty
****************************************************************************/
int SHash::emptyBucketCount() const
{
int countBucket = 0;
for (int i = 0; i < numBuckets; i++)
{
if (table[i].size() == 0)
countBucket++;
}
return countBucket++;
}
/****************************************************************************
* SHASH :: BUCKET COUNT RANGE
* For debugging purposes only. Gets the range of the length of chains in each
* bucket of a hash table.
****************************************************************************/
int SHash::bucketCountRange(int & min, int & max) const
{
for (int i = 0; i < numBuckets; i++)
{
if (i == 0)
min = max = table[i].size();
else if (table[i].size() < min)
min = table[i].size();
else if (table[i].size() > max)
max = table[i].size();
}
return max - min;
}
/****************************************************************************
* SHASH :: DISPLAY DISTRIBUTION
* For debugging purposes only. Shows a "graph of the distribution of a hash
* table's buckets
****************************************************************************/
void SHash :: displayDistribution() const
{
int cols = 50;
for (int i = 0; i < capacity(); i++)
{
cout << "[" << setw(3) << i << "]: ";
int j;
for (j = 1; j <= table[i].size(); j++)
{
if (j == cols)
break;
cout << ".";
}
if (j < table[i].size())
cout << "+" << table[i].size() - cols;
cout << endl;
}
}
#endif
| true |
433047da52b214c2b1246116900d0b84b70687c5 | C++ | leandro-araujo-silva/Estrutura-de-dados | /Estruturas/fila.cpp | UTF-8 | 1,923 | 3.984375 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
typedef int TipoItem;
const int max_itens = 100;
class fila
{
private:
int primeiro, ultimo;
TipoItem *estrutura;
public:
fila();
~fila();
bool estavazio();
bool estacheio();
void inserir(TipoItem item);
TipoItem remover();
void imprimir();
};
fila::fila() // construtor
{
primeiro = 0;
ultimo = 0;
estrutura = new TipoItem[max_itens];
}
fila::~fila() // destrutor
{
delete[] estrutura;
}
bool fila::estavazio()
{
return (primeiro == ultimo);
}
bool fila::estacheio()
{
return (ultimo - primeiro == max_itens);
}
void fila::inserir(TipoItem item)
{
if (estacheio())
{
cout << "A fila esta cheia\n";
cout << "Esse elemento nao pode ser inserido";
}
else
{
estrutura[ultimo % max_itens] = item;
ultimo++;
}
}
TipoItem fila::remover()
{
if (estavazio())
{
cout << "A fila esta vazia!\n";
cout << "Nenhum elemento foi removido!\n";
return 0;
}
else
{
primeiro++;
return estrutura[(primeiro - 1) % max_itens];
}
}
void fila::imprimir()
{
cout << "Fila: [";
for (int i = primeiro; i < ultimo; i++)
{
cout << estrutura[i % max_itens] << " ";
}
cout << "]\n";
}
int main()
{
fila fila1;
int opcao;
TipoItem item;
cout << "Programa gerador de filas:\n";
do
{
cout << "Digite 0 para parar o programa.\n";
cout << "Digite 1 para inserir um elemento.\n";
cout << "Digite 2 para remover um elemento.\n";
cout << "Digite 3 para imprimir a fila.\n";
cin >> opcao;
if (opcao == 1)
{
cout << "Digite o elemento a ser inserido na fila:\n";
cin >> item;
fila1.inserir(item);
}
else if (opcao == 2)
{
item = fila1.remover();
cout << "O elemento removido e: " << item << endl;
}
else if (opcao == 3)
{
fila1.imprimir();
}
cout << endl;
} while (opcao != 0);
return 0;
}
| true |
8daecf70ac995f048d78ee873e1338736b034a44 | C++ | zhaowei-rs/crane | /crane/logger.h | UTF-8 | 3,540 | 2.9375 | 3 | [] | no_license | #ifndef CRANE_LOGGER_H_
#define CRANE_LOGGER_H_
#include <string>
#include <memory>
#include <iostream>
#include <fstream>
#include <sstream>
#include <mutex>
using namespace std;
#define USE_LOGGING 1
#define STD_OUTPUT 1
#define LOG_FILE "crane.log"
class log_policy_interface
{
public:
virtual void open_ostream(const std::string& name) = 0;
virtual void close_ostream() = 0;
virtual void write(const std::string& msg) = 0;
};
/*
* Implementation which allow to write into a file
*/
class file_log_policy : public log_policy_interface
{
std::unique_ptr< std::ofstream > out_stream;
public:
file_log_policy() : out_stream(new std::ofstream) {}
void open_ostream(const std::string& name);
void close_ostream();
void write(const std::string& msg);
~file_log_policy();
};
enum severity_type
{
debug = 1,
error,
warning
};
template< typename log_policy >
class logger
{
unsigned log_line_number;
std::string get_time();
std::string get_logline_header();
std::stringstream log_stream;
log_policy* policy;
std::mutex write_mutex;
//Core printing functionality
void print_impl();
template<typename First, typename...Rest>
void print_impl(First parm1, Rest...parm);
public:
logger(const std::string& name);
template< severity_type severity, typename...Args >
void print(Args...args);
~logger();
};
template< typename log_policy >
logger< log_policy >::logger(const std::string& name)
{
log_line_number = 0;
policy = new log_policy;
if (!policy)
{
throw std::runtime_error("LOGGER: Unable to create the logger instance");
}
policy->open_ostream(name);
}
template< typename log_policy >
template< severity_type severity, typename...Args >
void logger< log_policy >::print(Args...args)
{
write_mutex.lock();
switch (severity)
{
case severity_type::debug:
log_stream << "<DEBUG> :";
break;
case severity_type::warning:
log_stream << "<WARNING> :";
break;
case severity_type::error:
log_stream << "<ERROR> :";
break;
};
print_impl(args...);
write_mutex.unlock();
}
template< typename log_policy >
logger< log_policy >::~logger()
{
if (policy)
{
policy->close_ostream();
delete policy;
}
}
template< typename log_policy >
void logger< log_policy >::print_impl()
{
#if STD_OUTPUT
cout << log_stream.str() << endl;
#endif // STD_OUTPUT
string line = get_logline_header() + log_stream.str();
policy->write(line);
log_stream.str("");
}
template< typename log_policy >
template<typename First, typename...Rest >
void logger< log_policy >::print_impl(First parm1, Rest...parm)
{
log_stream << parm1;
print_impl(parm...);
}
template< typename log_policy >
std::string logger< log_policy >::get_time()
{
time_t raw_time;
time(&raw_time);
struct tm *time_info = localtime(&raw_time);
char buffer[80];
strftime(buffer, 80, "%F %X", time_info);
std::string time_str(buffer);
return time_str;
}
template< typename log_policy >
std::string logger< log_policy >::get_logline_header()
{
std::stringstream header;
header.str("");
header.fill('0');
header.width(7);
header << log_line_number++ << " | " << get_time() << " ";
header.fill('0');
header.width(7);
header << clock() << " | ";
return header.str();
}
extern logger< file_log_policy > log_inst;
#if USE_LOGGING
#define LOG log_inst.print< severity_type::debug >
#define LOG_ERR log_inst.print< severity_type::error >
#define LOG_WARN log_inst.print< severity_type::warning >
#else
#define LOG(...)
#define LOG_ERR(...)
#define LOG_WARN(...)
#endif
#endif //!CRANE_LOGGER_H_
| true |
36992c79f9c26a9fd69ccc0397028e5659e326d7 | C++ | Cataclysm234/SP01-Trap-la-pist | /SP1Framework/game.cpp | UTF-8 | 21,600 | 2.515625 | 3 | [] | permissive | // This is the main file for the game logic and function
// gud day 14/8/2018
//
#include "game.h"
#include "Framework\console.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <string>
#include <Windows.h>
#pragma comment (lib,"Winmm.lib")
using namespace std;
double g_dElapsedTime;
double g_dDeltaTime;
double g_dTrapTime;
double g_fTrapTime;
double g_dTrapTime2;
double g_dTrapTime3;
double g_dBouncingTrap;
double g_dRandomeMovementTrapTime;
double g_sTrapTime;
double g_leftFanTrapTime, g_rightFanTrapTime, g_upFanTrapTime, g_downFanTrapTime;
bool g_abKeyPressed[K_COUNT];
int Choice;
char mapStorage[100][100];
string NumberOfLives;
int LevelSelected = 0;
bool bGotTrapPos;
bool bGotTrapPos2;
// Game specific variables here
SGameChar g_sChar;
SGameMovingTrap g_sMovingTrap[8];
SGameTrap g_fTrap[34];
SGameTrap g_sDoublePivotTrap;
SGameTrap g_sBouncingTrap;
SGameTrap g_sChargeTrap[12];
SGameTrap g_sRandomMovementTrap[28];
SGameTrap g_sStalkerTrap[7];
SGameTrap g_leftFanTrap[5], g_rightFanTrap[5], g_upFanTrap[5], g_downFanTrap[5];
storage lineArray[100];
int ChangesArrayOne[50];
int ChangesArrayTwo[50];
EGAMESTATES g_eGameState = S_GAMEMENU;
double g_dBounceTime; // this is to prevent key bouncing, so we won't trigger keypresses more than once
// Console object
Console g_Console(180, 35, "SP1 Framework");
//--------------------------------------------------------------
// Purpose : Initialisation function
// Initialize variables, allocate memory, load data from file, etc.
// This is called once before entering into your main loop
// Input : void
// Output : void
//--------------------------------------------------------------
void init( void )
{
// Set precision for floating point output
g_dElapsedTime = 0.0;
g_dBounceTime = 0.0;
g_dTrapTime = 0.0;
g_fTrapTime = 0.0;
g_dTrapTime2 = 0.0;
g_dBouncingTrap = 0.0;
g_sTrapTime = 0.0;
g_dRandomeMovementTrapTime = 0.0;
g_leftFanTrapTime = 0.0, g_rightFanTrapTime = 0.0, g_upFanTrapTime = 0.0, g_downFanTrapTime = 0.0;
// sets the initial state for the game
g_eGameState = S_GAMEMENU;
g_sChar.m_cLocation.X = 1;
g_sChar.m_cLocation.Y = 28;
g_sChar.m_bActive = true;
g_sChar.m_iLife = 3;
g_sChar.m_iRespawnX = 1;
g_sChar.m_iRespawnY = 28;
g_sBouncingTrap.m_cLocation.X = 40;
g_sBouncingTrap.m_cLocation.Y = 8;
// sets the width, height and the font name to use in the console
g_Console.setConsoleFont(0, 16, L"Consolas");
Choice = 1;
bGotTrapPos = false;
bGotTrapPos2 = false;
initMovingTrap(g_sMovingTrap);
initFallingTrap(g_fTrap);
ChangesArrayOne[50] = { 0, };
ChangesArrayTwo[50] = { 0, };
}
//--------------------------------------------------------------
// Purpose : Reset before exiting the program
// Do your clean up of memory here
// This is called once just before the game exits
// Input : Void
// Output : void
//--------------------------------------------------------------
void shutdown( void )
{
// Reset to white text on black background
colour(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
g_Console.clearBuffer();
}
//--------------------------------------------------------------
// Purpose : Getting all the key press states
// This function checks if any key had been pressed since the last time we checked
// If a key is pressed, the value for that particular key will be true
//
// Add more keys to the enum in game.h if you need to detect more keys
// To get other VK key defines, right click on the VK define (e.g. VK_UP) and choose "Go To Definition"
// For Alphanumeric keys, the values are their ascii values (uppercase).
// Input : Void
// Output : void
//--------------------------------------------------------------
void getInput( void )
{
g_abKeyPressed[K_UP] = isKeyPressed(VK_UP) || isKeyPressed(0x57); // "WASD" added
g_abKeyPressed[K_DOWN] = isKeyPressed(VK_DOWN) || isKeyPressed(0x53);
g_abKeyPressed[K_LEFT] = isKeyPressed(VK_LEFT) || isKeyPressed(0x41);
g_abKeyPressed[K_RIGHT] = isKeyPressed(VK_RIGHT) || isKeyPressed(0x44);
g_abKeyPressed[K_SPACE] = isKeyPressed(VK_SPACE);
g_abKeyPressed[K_ESCAPE] = isKeyPressed(VK_ESCAPE);
g_abKeyPressed[K_ENTER] = isKeyPressed(VK_RETURN);
g_abKeyPressed[K_RESET] = isKeyPressed(0x52);
g_abKeyPressed[K_HOME] = isKeyPressed(0x48);
g_abKeyPressed[K_INSTRUCTIONS] = isKeyPressed(0x49);
g_abKeyPressed[K_RESUME] = isKeyPressed(0x4F);
}
//--------------------------------------------------------------
// Purpose : Update function
// This is the update function
// double dt - This is the amount of time in seconds since the previous call was made
//
// Game logic should be done here.
// Such as collision checks, determining the position of your game characters, status updates, etc
// If there are any calls to write to the console here, then you are doing it wrong.
//
// If your game has multiple states, you should determine the current state, and call the relevant function here.
//
// Input : dt = deltatime
// Output : void
//--------------------------------------------------------------
void update(double dt)
{
// get the delta time
g_dElapsedTime += dt;
g_dDeltaTime = dt;
g_dTrapTime += dt;
g_fTrapTime += dt;
g_dTrapTime2 += dt;
g_dTrapTime3 += dt;
g_dBouncingTrap += dt;
g_sTrapTime += dt;
g_dRandomeMovementTrapTime += dt;
g_leftFanTrapTime += dt, g_rightFanTrapTime += dt, g_downFanTrapTime += dt, g_upFanTrapTime += dt;
switch (g_eGameState)
{
case S_GAMEMENU : gameMenu(); // game logic for the splash screen
break;
case S_GAME: gameplay(); // gameplay logic when we are in the game
break;
}
}
//--------------------------------------------------------------
// Purpose : Render function is to update the console screen
// At this point, you should know exactly what to draw onto the screen.
// Just draw it!
// To get an idea of the values for colours, look at console.h and the URL listed there
// Input : void
// Output : void
//--------------------------------------------------------------
void render()
{
clearScreen(); // clears the current screen and draw from scratch
switch (g_eGameState)
{
case S_GAMEMENU: renderGameMenu();
break;
case S_GAME: renderGame();
break;
case S_DEFEAT: renderDefeatScreen();
break;
case S_VICTORY: renderVictoryScreen();
break;
case S_INSTRUCTIONS: renderInstructionScreen();
break;
}
renderFramerate(); // renders debug information, frame rate, elapsed time, etc
renderToScreen(); // dump the contents of the buffer to the screen, one frame worth of game
}
void gameMenu()
{
g_eGameState = S_GAMEMENU;
bool bSelection = false;
if (g_dBounceTime > g_dElapsedTime)
return;
if (g_abKeyPressed[K_DOWN] && Choice != 4)
{
Choice += 1;
bSelection = true;
}
if (g_abKeyPressed[K_UP] && Choice != 1)
{
Choice -= 1;
bSelection = true;
}
if (bSelection)
{
// set the bounce time to some time in the future to prevent accidental triggers
g_dBounceTime = g_dElapsedTime + 0.125; // 125ms should be enough
}
if (g_abKeyPressed[K_ENTER]) { // Press enter to start game
switch (Choice) {
case 1: // set LevelSelected values (for hard-coding level assets)
changeMapStorageLevel1();
g_eGameState = S_GAME;
break;
case 2:
changeMapStorageLevel2();
g_eGameState = S_GAME;
break;
case 3:
g_eGameState = S_INSTRUCTIONS;
break;
case 4: g_bQuitGame = true;
break;
}
}
}
void changeMapStorageLevel1() {
if (LevelSelected != 1) {
string line;
ifstream myfile("maze.txt");
int i = 0;
int pos = 0;
if (myfile.is_open())
{
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
while (getline(myfile, line))
{
for (int j = 0; j < 80; j++)
{
mapStorage[i][j] = line[j]; // WHY IS IT Y,X
}
i++;
}
myfile.close();
}
LevelSelected = 1;
}
resetGame(g_sChar, ChangesArrayOne, g_fTrap, bGotTrapPos);
}
void changeMapStorageLevel2() {
if (LevelSelected != 2) {
string line;
ifstream myfile("HellMode.txt");
int i = 0;
int pos = 0;
if (myfile.is_open())
{
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
while (getline(myfile, line))
{
for (int j = 0; j < 80; j++)
{
mapStorage[i][j] = line[j]; // WHY IS IT Y,X
}
i++;
}
myfile.close();
}
LevelSelected = 2;
}
resetGame2(g_sChar, ChangesArrayTwo, bGotTrapPos2);
}
void gameplay() // gameplay logic
{
processUserInput(); // checks if you should change states or do something else with the game, e.g. pause, exit
moveCharacter(); // moves the character, collision detection, physics, etc
if (LevelSelected == 1) {
movingTrap(g_dTrapTime, g_sMovingTrap);
fallingTrap(g_fTrapTime, g_fTrap);
FanFunctionMain(g_sChar, mapStorage, g_Console, g_leftFanTrap, g_rightFanTrap, g_upFanTrap, g_downFanTrap);
leftFanMovement(g_leftFanTrapTime, g_sChar, mapStorage, g_leftFanTrap);
rightFanMovement(g_rightFanTrapTime, g_sChar, mapStorage, g_rightFanTrap);
upFanMovement(g_upFanTrapTime, g_sChar, mapStorage, g_upFanTrap);
downFanMovement(g_downFanTrapTime, g_sChar, mapStorage, g_downFanTrap);
}
else if (LevelSelected == 2) {
doublePivotTrap(g_dTrapTime, g_sDoublePivotTrap, g_dTrapTime2);
bouncingTrap(g_dBouncingTrap, g_sBouncingTrap, lineArray);
StalkerFunctionMain(g_sChar, mapStorage, g_sStalkerTrap);
StalkerFunctionMovement(g_sTrapTime, g_sChar, mapStorage, g_sStalkerTrap);
chargeTrap(g_dTrapTime3, g_sChargeTrap);
randomMovementTrap(g_dRandomeMovementTrapTime, g_sRandomMovementTrap);
}
collisionChecker(LevelSelected, g_sChar, mapStorage, g_sMovingTrap, g_fTrap, g_sDoublePivotTrap, g_sBouncingTrap, g_sStalkerTrap, g_sChargeTrap, g_sRandomMovementTrap, lineArray);
// sound can be played here too.
}
void moveCharacter()
{
bool bSomethingHappened = false;
if (g_dBounceTime > g_dElapsedTime)
return;
// Updating the location of the character based on the key press
// providing a beep sound whenver we shift the character
if (g_abKeyPressed[K_UP] && g_sChar.m_cLocation.Y > 2) // FOR "UP"
{
//Beep(1440, 30);
if (mapStorage[(int)g_sChar.m_cLocation.Y - 2][(int)g_sChar.m_cLocation.X] != '#')
{
if (mapStorage[(int)g_sChar.m_cLocation.Y - 2][(int)g_sChar.m_cLocation.X] != 'D')
{
g_sChar.m_cLocation.Y--;
bSomethingHappened = true;
}
}
}
if (g_abKeyPressed[K_LEFT] && g_sChar.m_cLocation.X > 0 && g_sChar.m_cLocation.X < 79) // FOR "LEFT"
{
//Beep(1440, 30);
if (mapStorage[(int)g_sChar.m_cLocation.Y - 1][(int)g_sChar.m_cLocation.X - 1] != '#')
{
if (mapStorage[(int)g_sChar.m_cLocation.Y - 1][(int)g_sChar.m_cLocation.X - 1] != 'D')
{
g_sChar.m_cLocation.X--;
bSomethingHappened = true;
}
}
}
if (g_abKeyPressed[K_DOWN] && g_sChar.m_cLocation.Y < g_Console.getConsoleSize().Y - 7) // FOR "DOWN"
{
//Beep(1440, 30);
if (mapStorage[(int)g_sChar.m_cLocation.Y][(int)g_sChar.m_cLocation.X] != '#')
{
if (mapStorage[(int)g_sChar.m_cLocation.Y][(int)g_sChar.m_cLocation.X] != 'D')
{
g_sChar.m_cLocation.Y++;
bSomethingHappened = true;
}
}
}
if (g_abKeyPressed[K_RIGHT] && g_sChar.m_cLocation.X < g_Console.getConsoleSize().X - 41) // FOR "RIGHT"
{
//Beep(1440, 30);
if (mapStorage[(int)g_sChar.m_cLocation.Y - 1][(int)g_sChar.m_cLocation.X + 1] != '#')
{
if (mapStorage[(int)g_sChar.m_cLocation.Y - 1][(int)g_sChar.m_cLocation.X + 1] != 'D')
{
g_sChar.m_cLocation.X++;
bSomethingHappened = true;
}
}
}
if (g_abKeyPressed[K_SPACE])
{
g_sChar.m_bActive = !g_sChar.m_bActive;
bSomethingHappened = true;
}
if (g_abKeyPressed[K_RESET])
{
playerKilled(g_sChar);
bSomethingHappened = true;
}
if (g_abKeyPressed[K_HOME])
{
//resetGame();
gameMenu();
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
}
if (g_abKeyPressed[K_INSTRUCTIONS])
{
g_eGameState = S_INSTRUCTIONS;
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
}
if (LevelSelected == 1) {
//FanFunctionMain(g_sChar, mapStorage, g_Console); // calls main fan function
if (bSomethingHappened)
{
// set the bounce time to some time in the future to prevent accidental triggers
g_dBounceTime = g_dElapsedTime + 0.125; // 125ms should be enough
ArrayLevelOneDetect(g_sChar, ChangesArrayOne); // Detect pressure plates etc presses
}
}
else if (LevelSelected == 2) {
/*FanFunctionMain(g_sChar, mapStorage, g_Console);*/
if (bSomethingHappened)
{
// set the bounce time to some time in the future to prevent accidental triggers
g_dBounceTime = g_dElapsedTime + 0.1;
g_dBounceTime = g_dElapsedTime + 0.125; // 125ms should be enough
ArrayLevelTwoDetect(g_sChar, ChangesArrayTwo); // Detect pressure plates etc presses
}
}
}
void processUserInput() {
// quits the game if player hits the escape key
if (g_abKeyPressed[K_ESCAPE]) {
g_bQuitGame = true;
}
}
void clearScreen()
{
// Clears the buffer with this colour attribute
g_Console.clearBuffer(0x00);
}
void renderGameMenu() // renders the game menu //TODO: change this to game menu
{
COORD c = g_Console.getConsoleSize();
COORD d;
string line;
ifstream myfile("Name.txt");
char NameStorage[100][100];
int i = 0, j = 0;
int pos = 0;
int p = 0;
if (myfile.is_open())
{
PlaySound(TEXT("MainMenu.wav"), NULL, SND_FILENAME | SND_NOSTOP | SND_ASYNC);
while (getline(myfile, line))
{
d.Y = i;
p = 0;
for (j = 0; j < 120; j++)
{
NameStorage[i][j] = line[j]; // Y,X
d.X = p;
if (NameStorage[i][j] == '#')
{
g_Console.writeToBuffer(d, NameStorage[i][j], 0x33);
}
else
{
g_Console.writeToBuffer(d, NameStorage[i][j], 0x03);
}
p++;
}
i++;
}
myfile.close();
}
c.Y = 17;
c.X = c.X / 2 - 49;
g_Console.writeToBuffer(c, "Normal Stage (more like ez)", 0x03);
c.Y += 1;
c.X = g_Console.getConsoleSize().X / 2 - 49;
g_Console.writeToBuffer(c, "HELL Stage (HEHEHEHAHAHOHO)", 0x03);
c.Y += 1;
c.X = g_Console.getConsoleSize().X / 2 - 49;
g_Console.writeToBuffer(c, "Instructions (YOU BETTER READ THIS)", 0x03);
c.Y += 1;
c.X = g_Console.getConsoleSize().X / 2 - 49;
g_Console.writeToBuffer(c, "Exit Game (noooo pls :<)", 0x03);
c.Y = 16 + Choice; //Arrow location
c.X = g_Console.getConsoleSize().X / 2 - 52;
g_Console.writeToBuffer(c, "->", 0x03);
}
void renderInstructionScreen()
{
COORD c = g_Console.getConsoleSize();
COORD d;
string line;
ifstream myfile("Instructions.txt");
char NameStorage[100][100];
int i = 0, j = 0;
int pos = 0;
int p = 0;
if (myfile.is_open())
{
while (getline(myfile, line))
{
d.Y = i;
p = 0;
for (j = 0; j < 120; j++)
{
NameStorage[i][j] = line[j]; // Y,X
d.X = p;
if (NameStorage[i][j] == '#') {
g_Console.writeToBuffer(d, NameStorage[i][j], 0x33);
}
else
{
g_Console.writeToBuffer(d, NameStorage[i][j], 0x03);
}
p++;
}
i++;
}
if (g_abKeyPressed[K_HOME])
{
gameMenu();
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
}
if (g_abKeyPressed[K_RESUME])
{
g_eGameState = S_GAME;
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
}
myfile.close();
}
}
void renderDefeatScreen()
{
COORD c = g_Console.getConsoleSize();
COORD d;
string line;
ifstream myfile("Defeat.txt");
char NameStorage[100][100];
int i = 0, j = 0;
int pos = 0;
int p = 0;
if (myfile.is_open())
{
PlaySound(TEXT("Defeat.wav"), NULL, SND_FILENAME | SND_NOSTOP | SND_ASYNC);
while (getline(myfile, line))
{
d.Y = i;
p = 0;
for (j = 0; j < 120; j++)
{
NameStorage[i][j] = line[j]; // Y,X
d.X = p;
if (NameStorage[i][j] == '#') {
g_Console.writeToBuffer(d, NameStorage[i][j], 0x44);
}
else
{
g_Console.writeToBuffer(d, NameStorage[i][j], 0x04);
}
p++;
}
i++;
}
if (g_abKeyPressed[K_HOME])
{
gameMenu();
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_NOSTOP | SND_ASYNC);
}
myfile.close();
}
}
void renderVictoryScreen()
{
COORD c = g_Console.getConsoleSize();
COORD d;
string line;
ifstream myfile("Victory.txt");
char NameStorage[100][100];
int i = 0, j = 0;
int pos = 0;
int p = 0;
if (myfile.is_open())
{
while (getline(myfile, line))
{
d.Y = i;
p = 0;
for (j = 0; j < 120; j++)
{
NameStorage[i][j] = line[j]; // Y,X
d.X = p;
if (NameStorage[i][j] == '#') {
g_Console.writeToBuffer(d, NameStorage[i][j], 0xEE);
}
else
{
g_Console.writeToBuffer(d, NameStorage[i][j], 0x0E);
}
p++;
}
i++;
}
if (g_abKeyPressed[K_HOME])
{
gameMenu();
PlaySound(TEXT("Silent.wav"), NULL, SND_FILENAME | SND_ASYNC);
}
myfile.close();
}
}
void renderGame()
{
renderCollisionCheck(g_Console);
renderMap(); // renders the map to the buffer first
renderCharacter(g_Console, g_sChar); // renders the character into the buffer
renderLives(g_sChar, NumberOfLives, g_eGameState);
PlaySound(TEXT("Game.wav"), NULL, SND_FILENAME | SND_NOSTOP | SND_ASYNC);
if (LevelSelected == 1) {
renderMovingTrap(g_Console, g_sMovingTrap);
renderFallingTrap(g_Console, g_fTrap);
renderUI(g_Console, NumberOfLives, g_sChar);
}
else if (LevelSelected == 2) {
renderDoublePiovtTrap(g_Console, g_sDoublePivotTrap);
renderUI2(g_Console, NumberOfLives, g_sChar);
renderBouncingTrap(g_Console, g_sBouncingTrap, lineArray);
renderStalkerTrap(g_Console, g_sStalkerTrap);
renderChargeTrap(g_Console, g_sChargeTrap);
renderRandomMvementTrap(g_Console, g_sRandomMovementTrap);
}
}
void renderMap()
{
COORD c;
int pos = 0;
string line;
int i = 0;
if (LevelSelected == 1) // FOR LEVEL ONE
{
for (int k = 0; k < 30; k++) // Reset Traps loop
{
for (int j = 0; j < 80; j++)
{
if (mapStorage[k][j] == ',')
{
mapStorage[k][j] = 'D';
}
else if (mapStorage[k][j] == '.')
{
mapStorage[k][j] = 'E';
}
else if (mapStorage[k][j] == 'b')
{
mapStorage[k][j] = 'S';
}
else if (mapStorage[k][j] == 'l')
{
mapStorage[k][j] = 'N';
}
}
}
ArrayLevelOneActivate(g_sChar, ChangesArrayOne, mapStorage, g_fTrap, g_eGameState); // Activate traps
}
if (LevelSelected == 2)
{
for (int k = 0; k < 30; k++) // Reset Traps loop
{
for (int j = 0; j < 80; j++)
{
if (mapStorage[k][j] == ',')
{
mapStorage[k][j] = 'D';
}
}
}
ArrayLevelTwoActivate(g_sChar, ChangesArrayTwo, mapStorage, g_eGameState); // Activate traps
}
for (int k = 0; k < 30; k++) {
int pos2 = 0;
c.Y = 1 + pos;
for (int j = 0; j < 80; j++) {
c.X = pos2;
if (mapStorage[k][j] == '#') {
g_Console.writeToBuffer(c, mapStorage[k][j], 0x88);
}
else if (mapStorage[k][j] == 'S')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0x40);
}
else if (mapStorage[k][j] == 'D')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0xF0);
}
else if (mapStorage[k][j] == 'E')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0xC0);
}
else if (mapStorage[k][j] == 'P')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0x21);
}
else if (mapStorage[k][j] == '!') // fake pressure plate // act as spikes
{
g_Console.writeToBuffer(c, 'P', 0x21);
}
else if (mapStorage[k][j] == 'Z' || mapStorage[k][j] == 'X' || mapStorage[k][j] == 'N' || mapStorage[k][j] == 'M') // fans
{
g_Console.writeToBuffer(c, 'F', 0xE0);
}
else if (mapStorage[k][j] == 'W')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0x35);
}
else if (mapStorage[k][j] == 'C')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0xB0);
}
else if (mapStorage[k][j] == 'G')
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0xE0);
}
else if (mapStorage[k][j] == '~')
{
g_Console.writeToBuffer(c, "WIN" , 0xE0);
}
else
{
g_Console.writeToBuffer(c, mapStorage[k][j], 0x00);
}
pos2++;
}
pos++;
}
if (bGotTrapPos == false && LevelSelected == 1)
{
getMovingTrapPos(mapStorage, g_sMovingTrap);
getFallingTrapPos(mapStorage, g_fTrap);
getFanTrapPos(mapStorage, g_leftFanTrap, g_rightFanTrap, g_upFanTrap, g_downFanTrap);
bGotTrapPos = true;
}
else if (bGotTrapPos2 == false && LevelSelected == 2) {
getDoublePiovtTrapPos(mapStorage, g_sDoublePivotTrap);
getStalkerTrapPos(mapStorage, g_sStalkerTrap);
getChargeTrapPos(mapStorage, g_sChargeTrap);
getRandomMovementTrapPos(mapStorage, g_sRandomMovementTrap);
bGotTrapPos2 = true;
}
}
void renderFramerate()
{
COORD c;
// displays the framerate
std::ostringstream ss;
ss << std::fixed << std::setprecision(3);
ss << "Frame Rate: " << 1.0 / g_dDeltaTime << "fps";
c.X = g_Console.getConsoleSize().X; //THIS IS WHERE THE FRAMERATE THINGY AT Initial TOP RIGHT SHOWS UP
c.Y = g_Console.getConsoleSize().Y - 2;
g_Console.writeToBuffer(c, ss.str());
// displays the elapsed time
ss.str("");
ss << "Elapsed Time: " << g_dElapsedTime << "secs";
c.X = 0;
c.Y = g_Console.getConsoleSize().Y - 2;
g_Console.writeToBuffer(c, ss.str());
}
void renderToScreen()
{
// Writes the buffer to the console, hence you will see what you have written
g_Console.flushBufferToConsole();
} | true |
82e83c7001ac2f66045af87e16bbab470813c6b0 | C++ | JeffBobbo/Interpreter | /C++/Interpreter.h | UTF-8 | 4,143 | 2.890625 | 3 | [] | no_license | #ifndef INTERPRETER_H_INCLUDE
#define INTERPRETER_H_INCLUDE
#include <cctype> // std::isalpha, std::isalnum, std::isdigit, etc
#include <string>
#include <cmath>
#include <map>
#include "Parser.h"
#include "Token.h"
class Interpreter
{
public:
Interpreter(Parser* p) : parser(p), tree(nullptr) {};
~Interpreter() { if (tree) delete tree; delete parser; };
inline void error(const std::string& msg) { throw std::string("Interpreter: ") + msg; };
double visit(AST* node)
{
switch (node->getType())
{
case AST::Type::NO_OP:
visitNoOp(/*static_cast<NoOp*>(node)*/);
break;
case AST::Type::OP_UNARY:
return visitUnaryOp(static_cast<UnaryOp*>(node));
case AST::Type::OP_BINARY:
return visitBinaryOp(static_cast<BinaryOp*>(node));
case AST::Type::NUMBER:
return visitNumber(static_cast<Number*>(node));
case AST::Type::VARIABLE:
return visitVariable(static_cast<Variable*>(node));
case AST::Type::COMPOUND:
visitCompound(static_cast<Compound*>(node));
break;
case AST::Type::ASSIGN:
visitAssign(static_cast<Assign*>(node));
break;
default:
error(std::string("Unknown visit: ") + AST::fromType(node->getType()));
}
return 0.0; // may happen, but if it does we don't care
}
void visitNoOp(/*NoOp* node*/)
{
return;
}
double visitUnaryOp(UnaryOp* node)
{
if (node->tokenType() == Token::ADDITION)
return visit(node->getNode());
else if (node->tokenType() == Token::SUBTRACTION)
return -visit(node->getNode());
else if (node->tokenType() == Token::BITWISE_NOT)
return ~static_cast<int64_t>(visit(node->getNode()));
error("bad unary op visit");
return 0.0; // not going to happen
}
double visitBinaryOp(BinaryOp* node)
{
switch (node->tokenType())
{
case Token::Type::ADDITION:
return visit(node->getLeft()) + visit(node->getRight());
case Token::Type::SUBTRACTION:
return visit(node->getLeft()) - visit(node->getRight());
case Token::Type::MULTIPLICATION:
return visit(node->getLeft()) * visit(node->getRight());
case Token::Type::DIVISION:
return visit(node->getLeft()) / visit(node->getRight());
case Token::Type::MODULO:
return static_cast<int64_t>(visit(node->getLeft())) % static_cast<int64_t>(visit(node->getRight()));
case Token::Type::POWER:
return std::pow(visit(node->getLeft()), visit(node->getRight()));
case Token::Type::BITWISE_AND:
return static_cast<int64_t>(visit(node->getLeft())) & static_cast<int64_t>(visit(node->getRight()));
case Token::Type::BITWISE_OR:
return static_cast<int64_t>(visit(node->getLeft())) | static_cast<int64_t>(visit(node->getRight()));
case Token::Type::BITWISE_XOR:
return static_cast<int64_t>(visit(node->getLeft())) ^ static_cast<int64_t>(visit(node->getRight()));
case Token::Type::BITSHIFT_L:
return static_cast<int64_t>(visit(node->getLeft())) << static_cast<int64_t>(visit(node->getRight()));
case Token::Type::BITSHIFT_R:
return static_cast<int64_t>(visit(node->getLeft())) >> static_cast<int64_t>(visit(node->getRight()));
default:
error("bad binary op visit");
}
return 0.0; // not going to happen
}
double visitNumber(Number* node)
{
return node->getValue();
}
double visitVariable(Variable* node)
{
auto it = GLOBAL_SCOPE.find(node->getName());
if (it == std::end(GLOBAL_SCOPE))
error(std::string("variable used before assignment: ") + node->getName());
return it->second;
}
void visitCompound(Compound* node)
{
for (AST* child : node->getChildren())
visit(child);
}
void visitAssign(Assign* node)
{
GLOBAL_SCOPE[node->getName()] = visit(node->getRight());
}
void interpret()
{
tree = parser->parse();
visit(tree);
for (auto&& it : GLOBAL_SCOPE)
std::cout << it.first << ": " << it.second << "\n";
}
private:
Parser* parser;
AST* tree;
std::map<std::string, double> GLOBAL_SCOPE;
};
#endif
| true |
1b4b9da205ad4c89f29c9f8d0f31b7fd6097642a | C++ | fivard/Laboratory-works-sem2-2019-2020-academic-year | /lab1/message.cpp | UTF-8 | 3,149 | 3.15625 | 3 | [] | no_license | #include "message.h"
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void MessageLog::coutElem() {
cout << this->id << ' ' << this->countWords << ' ' << this->text << ' ' << this->timeCreated.year << ' ' << this->timeCreated.month
<< ' ' << this->timeCreated.day << ' ' << this->timeCreated.hour << ' ' << this->timeCreated.minutes << ' ' << this->timeCreated.sec
<< ' ' << this->typeOfError << ' ' << this->priority << ' ' << this->loading << ' ' << '\n' ;
}
void MessageLog::saveToDisk(){
ofstream file("data.txt", ios_base::app);
if (!file){
cout << "txt is closed \n";
return;
}
file << this->id << ' ' << this->countWords << ' ' << this->text << ' ' << this->timeCreated.year << ' ' << this->timeCreated.month
<< ' ' << this->timeCreated.day << ' ' << this->timeCreated.hour << ' ' << this->timeCreated.minutes << ' ' << this->timeCreated.sec
<< ' ' << this->typeOfError << ' ' << this->priority << ' ' << this->loading << '\n' ;
file.close();
ofstream bin("binary.txt", ios_base::binary|ios_base::app);
if (!bin){
cout << "bin is closed \n";
return;
}
bin.write((char*)&this->id, sizeof(this->id)); //id
int lengthText = this->text.size();
bin.write((char*)&this->countWords, sizeof(this->countWords));
bin.write((char*)&lengthText, sizeof(lengthText));
bin << this->text; //text
bin.write((char*)&this->timeCreated.year, sizeof(this->timeCreated.year));
bin.write((char*)&this->timeCreated.month, sizeof(this->timeCreated.month));
bin.write((char*)&this->timeCreated.day, sizeof(this->timeCreated.day));
bin.write((char*)&this->timeCreated.hour, sizeof(this->timeCreated.hour));
bin.write((char*)&this->timeCreated.minutes, sizeof(this->timeCreated.minutes));
bin.write((char*)&this->timeCreated.sec, sizeof(this->timeCreated.sec)); //time
int lengthTypeOfError = this->typeOfError.size();
bin.write((char*)&lengthTypeOfError, sizeof(lengthTypeOfError));
bin << this->typeOfError; //typeOfError
bin.write((char*)&this->priority, sizeof(this->priority)); //priority
bin.write((char*)&this->loading, sizeof(this->loading)); //loading
bin.close();
}
bool FullTime::moreThen(FullTime secondTime) {
if (year == secondTime.year)
;
else
return year > secondTime.year;
if (month == secondTime.month)
;
else
return month > secondTime.month;
if (day == secondTime.day)
;
else
return day > secondTime.day;
if (hour == secondTime.hour)
;
else
return hour > secondTime.hour;
if (minutes == secondTime.minutes)
;
else
return minutes > secondTime.minutes;
if (sec == secondTime.sec)
;
else
return sec > secondTime.sec;
return true;
}
void FullTime::coutTime() {
cout << year << ' ' << month << ' ' << day << ' ' << hour << ' ' << minutes << ' ' << sec << endl;
} | true |
3a4146d3beb4f70c5602b229f3f3a795edda0506 | C++ | delcanovega/AER | /317/main.cpp | UTF-8 | 1,457 | 2.578125 | 3 | [] | no_license | #include <cstdio>
#include <string>
#include <set>
using namespace std;
int main() {
int size;
scanf("%d", &size);
while (size != 0) {
set<string> hash;
char key[5];
for (int i = 0; i < size; ++i) {
scanf("%s", key);
string k(key);
hash.insert(k);
}
char c_str[1003];
scanf("%s\n", c_str );
string str(c_str);
bool error{false};
unsigned long long opt{1};
for (unsigned long int pos{str.size() - 1}; pos > 0; pos--) {
bool one_dig{false};
bool two_dig{false};
bool thr_dig{false};
if (str[pos] != '0') {
string str_1{str.substr(pos, 1)};
if (hash.find(str_1) != hash.end()) {
one_dig = true;
}
if (pos > 0) {
string str_2{str.substr(pos - 1, 2)};
if (hash.find(str_2) != hash.end()) {
two_dig = true;
if (one_dig) {
opt++;
}
}
}
if (pos > 1) {
string str_3{str.substr(pos - 2, 3)};
if (hash.find(str_3) != hash.end()) {
thr_dig = true;
if (one_dig || two_dig) {
opt++;
}
}
}
if (!one_dig && !two_dig && !thr_dig) {
error = true;
break;
}
}
}
if (error) {
printf("0\n");
}
else {
opt = opt % 1000000007;
printf("%llu\n", opt);
}
scanf("%d", &size);
}
} | true |
8177465064530eb0d4dde8e066147626727b9d13 | C++ | clab/dynet | /dynet/training.h | UTF-8 | 24,388 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /**
* \file training.h
* \defgroup optimizers
* \brief Training procedures
*
* The various trainers are defined here.
* All trainers are structures inheriting from the `Trainer` struct.
*
*
*/
#ifndef DYNET_TRAINING_H_
#define DYNET_TRAINING_H_
#include <vector>
#include <iostream>
#include "dynet/model.h"
#include "dynet/shadow-params.h"
#define DYNET_TRAINER_DEFINE_DEV_IMPL() \
void update_params(real gscale, size_t idx) override; \
void update_lookup_params(real gscale, size_t idx, size_t lidx) override; \
void update_lookup_params(real gscale, size_t idx) override; \
template <class MyDevice> \
void update_rule_dev(const MyDevice & dev, real gscale, const std::vector<Tensor*> & values); \
void update_rule(real gscale, const std::vector<Tensor*> & values) override;
namespace dynet {
enum struct MovingAverage
{
None,
Cumulative,
Exponential
};
std::ostream& operator<<(std::ostream& os, const MovingAverage& o);
std::istream& operator>>(std::istream& is, MovingAverage& o);
/**
* \ingroup optimizers
*
* \struct Trainer
* \brief General trainer struct
*
*/
struct Trainer {
/**
* \brief General constructor for a Trainer
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
*/
explicit Trainer(ParameterCollection& m, real learning_rate) :
learning_rate(learning_rate),
clipping_enabled(true),
clip_threshold(5),
clips(),
updates(),
clips_since_status(),
updates_since_status(),
sparse_updates_enabled(true),
aux_allocated(0),
aux_allocated_lookup(0),
ema_beta(0.f),
ma_mode(MovingAverage::None),
ma_params_swapped(false),
ma_params_saved(false),
ma_update_freq(1u),
ma_updates(0u),
ma_aux_allocated(0),
ma_aux_allocated_lookup(0),
model(&m)
{}
virtual ~Trainer();
/**
* \brief Update parameters
* \details Update the parameters according to the appropriate update rule
*/
virtual void update();
/**
* \brief Update subset of parameters
* \details Update some but not all of the parameters included in the model. This
* is the update_subset() function in the Python bindings. The
* parameters to be updated are specified by index, which can be found
* for Parameter and LookupParameter objects through the "index" variable
* (or the get_index() function in the Python bindings).
*
* \param updated_params The parameter indices to be updated
* \param updated_lookup_params The lookup parameter indices to be updated
*/
void update(const std::vector<unsigned> & updated_params, const std::vector<unsigned> & updated_lookup_params);
void update_epoch(real r = 1.0);
/**
* @brief Restarts the optimizer
* @details Clears all momentum values and assimilate (if applicable).
* This method does not update the current hyperparameters
*. (for example the bias parameter of the AdadeltaTrainer is left unchanged).
*/
virtual void restart() = 0;
/**
* @brief Restarts the optimizer with a new learning rate
* @details Clears all momentum values and assimilate (if applicable) and resets the learning rate.
* This method does not update the current hyperparameters
*. (for example the bias parameter of the AdadeltaTrainer is left unchanged).
*
* \param learning_rate New learning rate
*/
void restart(real lr);
/**
* @brief Save the optimizer state
* @details Write all hyperparameters, momentum values and assimilate (if applicable) to stream.
* If the parameters are swapped with their moving averages, only the latters are saved.
*
* \param os Output stream
*/
virtual void save(std::ostream& os);
/**
* @brief Load the optimizer state
* @details Read all hyperparameters, momentum values and assimilate (if applicable) from stream.
*
* \param os Input stream
*/
virtual void populate(std::istream& is);
/**
* @brief Load the optimizer state
* @details Read all hyperparameters, momentum values and assimilate (if applicable) from stream.
*
* \param os Input stream
* \param lr New learning rate
*/
void populate(std::istream& is, real lr);
/**
* \brief Clip gradient
* \details If clipping is enabled and the gradient is too big, return the amount to
* scale the gradient by (otherwise 1)
*
*
* \return The appropriate scaling factor
*/
float clip_gradients();
// TODO: This is unprotected temporarily until there is a better solution
// for serializing the weight decay when saving models
// Rescale all the parameters handled by this model
void rescale_and_reset_weight_decay();
// learning rate
real learning_rate;
// clipping
bool clipping_enabled;
real clip_threshold;
real clips;
real updates;
// the number of clips and status since the last print
real clips_since_status;
real updates_since_status;
/**
* \brief Whether to perform sparse updates
* \details DyNet trainers support two types of updates for lookup parameters,
* sparse and dense. Sparse updates are the default. They have the
* potential to be faster, as they only touch the parameters that have
* non-zero gradients. However, they may not always be faster (particulary
* on GPU with mini-batch training), and are not precisely numerically
* correct for some update rules such as MomentumTrainer and AdamTrainer.
* Thus, if you set this variable to false, the trainer will perform dense
* updates and be precisely correct, and maybe faster sometimes.
*/
bool sparse_updates_enabled;
unsigned aux_allocated;
unsigned aux_allocated_lookup;
protected:
real ema_beta; // Exponential Moving Averaged only
MovingAverage ma_mode;
bool ma_params_swapped; // true if params and moving av. of params have been swapped
bool ma_params_saved; // true if params have been saved when swapping
unsigned ma_update_freq; // the moving average will be updated each ema_update_frequency updates
unsigned ma_updates; // number of times the moving av. has been updated
unsigned ma_aux_allocated;
unsigned ma_aux_allocated_lookup;
// Shadow parameters used for moving average
std::vector<ShadowParameters> ma_p;
std::vector<ShadowLookupParameters> ma_lp;
std::vector<ShadowParameters> ma_saved_p;
std::vector<ShadowLookupParameters> ma_saved_lp;
public:
/**
* Whether the the trainer is storing the moving average of parameters
*
* \return The moving average mode
*/
MovingAverage moving_average();
/**
* Enable the computation of the exponential moving average of parameters.
* \details This function must be called before any update.
*
* \param beta The degree of weighting decrease
* \param update_freq Frequency of update of the EMA
*/
void exponential_moving_average(float beta, unsigned update_freq=1u);
/**
* Enable the computation of the cumulative moving average of parameters.
* \details This function must be called before any update.
*
* \param update_freq Frequency of update of the moving average
*/
void cumulative_moving_average(unsigned update_freq=1u);
/**
* Set the network parameters to their moving average
* \details If the current weights are not saved, the optimizer cannot be used
* anymore (e.g. the update() function will throw an exception)
*
* \param save_weights Whether to save the current weights.
* \param bias_bias_correction Whether to apply bias correction (used for exponential moving average only)
*/
void swap_params_to_moving_average(bool save_weights=true, bool bias_correction=false);
/**
* Restore the parameters of the model if they are set to their moving average
*/
void swap_params_to_weights();
void status() {
std::cerr << "[lr=" << learning_rate << " clips=" << clips_since_status << " updates=" << updates_since_status << "] ";
updates_since_status = clips_since_status = 0;
}
ParameterCollection* model; // parameters and gradients live here
protected:
Trainer() {}
virtual unsigned alloc_impl() {
return static_cast<unsigned>(model->parameters_list().size()) - aux_allocated;
}
virtual unsigned alloc_lookup_impl() {
return static_cast<unsigned>(model->lookup_parameters_list().size()) - aux_allocated_lookup;
}
/**
* \brief The actual rule to update the parameters
*
* \param scale Scale of the update (i.e. learning rate)
* \param gscale Gradient scale based on clipping
* \param values Values specific to the particular update rule being implemented
*/
virtual void update_rule(real gscale, const std::vector<Tensor*> & values) = 0;
/**
* \brief Parameter update function
*
* \param scale Scale of the update (i.e. learning rate)
* \param gscale Gradient scale based on clipping
* \param idx The ID of the parameter to update
*/
virtual void update_params(real gscale, size_t idx) = 0;
/**
* \brief Sparse lookup parameter update function
*
* \param scale Scale of the update (i.e. learning rate)
* \param gscale Gradient scale based on clipping
* \param idx The ID of the parameter to update
* \param lidx Index of the specific entry within the lookup parameter object
*/
virtual void update_lookup_params(real gscale, size_t idx, size_t lidx) = 0;
/**
* \brief Dense lookup parameter update function
*
* \param scale Scale of the update (i.e. learning rate)
* \param gscale Gradient scale based on clipping
* \param idx The ID of the parameter to update
*/
virtual void update_lookup_params(real gscale, size_t idx) = 0;
template <class MyDevice> void update_ma_rule_dev(const MyDevice& dev, Tensor* ma, Tensor* p);
void update_ma_rule(Tensor* ma, Tensor* p);
template <class MyDevice> void swap_params_to_ma_rule_dev(const MyDevice& dev, bool bias_correction, bool save_weights, Tensor* p, Tensor* mem, Tensor* ma);
void swap_params_to_ma_rule(bool bias_correction, bool save_weights, Tensor* p, Tensor* mem, Tensor* ma);
template <class MyDevice> void swap_params_to_weights_rule_dev(const MyDevice& dev, Tensor* p, Tensor* mem);
void swap_params_to_weights_rule(Tensor* p, Tensor* mem);
};
/**
* \ingroup optimizers
*
* \brief Stochastic gradient descent trainer
* \details This trainer performs stochastic gradient descent, the goto optimization procedure for neural networks.
* In the standard setting, the learning rate at epoch \f$t\f$ is \f$\eta_t=\frac{\eta_0}{1+\eta_{\mathrm{decay}}t}\f$
*
* Reference : [reference needed](ref.need.ed)
*
*/
struct SimpleSGDTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
*/
explicit SimpleSGDTrainer(ParameterCollection& m, real learning_rate = 0.1) : Trainer(m, learning_rate) {}
void restart() override {};
using Trainer::restart;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
private:
SimpleSGDTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief Cyclical learning rate SGD
* \details This trainer performs stochastic gradient descent with a cyclical learning rate as proposed in [Smith, 2015](https://arxiv.org/abs/1506.01186).
*
* This uses a triangular function with optional exponential decay.
*
* More specifically, at each update, the learning rate \f$\eta\f$ is updated according to :
*
* \f$
* \begin{split}
* \text{cycle} &= \left\lfloor 1 + \frac{\texttt{it}}{2 \times\texttt{step_size}} \right\rfloor\\
* x &= \left\vert \frac{\texttt{it}}{\texttt{step_size}} - 2 \times \text{cycle} + 1\right\vert\\
* \eta &= \eta_{\text{min}} + (\eta_{\text{max}} - \eta_{\text{min}}) \times \max(0, 1 - x) \times \gamma^{\texttt{it}}\\
* \end{split}
* \f$
*
*
* Reference : [Cyclical Learning Rates for Training Neural Networks](https://arxiv.org/abs/1506.01186)
*
*/
struct CyclicalSGDTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate_min Lower learning rate
* \param learning_rate_max Upper learning rate
* \param step_size Period of the triangular function in number of iterations (__not__ epochs). According to the original paper, this should be set around (2-8) x (training iterations in epoch)
* \param gamma Learning rate upper bound decay parameter
* \param edecay Learning rate decay parameter. Ideally you shouldn't use this with cyclical learning rate since decay is already handled by \f$\gamma\f$
*/
explicit CyclicalSGDTrainer(ParameterCollection& m, float learning_rate_min = 0.01, float learning_rate_max = 0.1, float step_size = 2000, float gamma = 1.0, float edecay = 0.0) : Trainer(m, learning_rate_min), e_min(learning_rate_min), e_max(learning_rate_max), step_size(step_size), gamma(gamma), it(0) {}
void restart() override {};
using Trainer::restart;
void update() override {
Trainer::update();
cyclic_update_eta();
}
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
void cyclic_update_eta() {
float cycle = std::floor(1 + ((float) it) / (2 * step_size));
float x = std::abs( ((float) it) / step_size - 2 * cycle + 1);
learning_rate = e_min + ((1 - x) > 0 ? (e_max - e_min) * (1 - x) * (real)std::pow(gamma, it) : 0);
it++;
}
float e_min;
float e_max;
float step_size;
float gamma;
unsigned it;
private:
CyclicalSGDTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief Stochastic gradient descent with momentum
* \details This is a modified version of the SGD algorithm with momentum to stablize the gradient trajectory.
* The modified gradient is \f$\theta_{t+1}=\mu\theta_{t}+\nabla_{t+1}\f$ where \f$\mu\f$ is the momentum.
*
* Reference : [reference needed](ref.need.ed)
*
*/
struct MomentumSGDTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
* \param mom Momentum
*/
explicit MomentumSGDTrainer(ParameterCollection& m, real learning_rate = 0.01, real mom = 0.9) :
Trainer(m, learning_rate), momentum(mom) {}
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
// the following represent the current velocity
// The shadow parameters are made public for testing, ideally they shouldn't be
std::vector<ShadowParameters> vp;
std::vector<ShadowLookupParameters> vlp;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
real momentum;
private:
MomentumSGDTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief Adagrad optimizer
* \details The adagrad algorithm assigns a different learning rate to each parameter according to the following formula :
* \f$\delta_\theta^{(t)}=-\frac{\eta_0}{\epsilon+\sum_{i=0}^{t-1}(\nabla_\theta^{(i)})^2}\nabla_\theta^{(t)}\f$
*
* Reference : [Duchi et al., 2011](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
*
*/
struct AdagradTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
* \param eps Bias parameter \f$\epsilon\f$ in the adagrad formula
*/
explicit AdagradTrainer(ParameterCollection& m, real learning_rate = 0.1, real eps = 1e-20) :
Trainer(m, learning_rate), epsilon(eps) {}
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
real epsilon;
std::vector<ShadowParameters> vp;
std::vector<ShadowLookupParameters> vlp;
private:
AdagradTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief AdaDelta optimizer
* \details The AdaDelta optimizer is a variant of Adagrad where
* \f$\frac{\eta_0}{\sqrt{\epsilon+\sum_{i=0}^{t-1}(\nabla_\theta^{(i)})^2}}\f$ is replaced by
* \f$\frac{\sqrt{\epsilon+\sum_{i=0}^{t-1}\rho^{t-i-1}(1-\rho)(\delta_\theta^{(i)})^2}}{\sqrt{\epsilon+\sum_{i=0}^{t-1}(\nabla_\theta^{(i)})^2}}\f$,
* hence eliminating the need for an initial learning rate.
*
* Reference : [ADADELTA: An Adaptive Learning Rate Method](https://arxiv.org/pdf/1212.5701v1)
*
*/
struct AdadeltaTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param eps Bias parameter \f$\epsilon\f$ in the adagrad formula
* \param rho Update parameter for the moving average of updates in the numerator
*/
explicit AdadeltaTrainer(ParameterCollection& m, real eps = 1e-6, real rho = 0.95) :
Trainer(m, 1.0), epsilon(eps), rho(rho) {}
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
real epsilon;
real rho;
std::vector<ShadowParameters> hg; // History of gradients
std::vector<ShadowLookupParameters> hlg;
std::vector<ShadowParameters> hd; // History of deltas
std::vector<ShadowLookupParameters> hld;
private:
AdadeltaTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief RMSProp optimizer
* \details The RMSProp optimizer is a variant of Adagrad where the squared sum of previous gradients is replaced with a moving average with parameter \f$\rho\f$.
*
* Reference : [reference needed](ref.need.ed)
*
*/
struct RMSPropTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
* \param eps Bias parameter \f$\epsilon\f$ in the adagrad formula
* \param rho Update parameter for the moving average (`rho = 0` is equivalent to using Adagrad)
*/
explicit RMSPropTrainer(ParameterCollection& m, real learning_rate = 0.1, real eps = 1e-20, real rho = 0.95) :
Trainer(m, learning_rate), epsilon(eps), rho(rho) {}
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
real epsilon;
real rho;
std::vector<ShadowParameters> hmsg; // History of gradients
std::vector<ShadowLookupParameters> hlmsg;
private:
RMSPropTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief Adam optimizer
* \details The Adam optimizer is similar to RMSProp but uses unbiased estimates
* of the first and second moments of the gradient
*
* Reference : [Adam: A Method for Stochastic Optimization](https://arxiv.org/pdf/1412.6980v8)
*
*/
struct AdamTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
* \param beta_1 Moving average parameter for the mean
* \param beta_2 Moving average parameter for the variance
* \param eps Bias parameter \f$\epsilon\f$
*/
explicit AdamTrainer(ParameterCollection& m, float learning_rate = 0.001, float beta_1 = 0.9, float beta_2 = 0.999, float eps = 1e-8) :
Trainer(m, learning_rate), beta_1(beta_1), beta_2(beta_2), epsilon(eps) {}
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
float beta_1;
float beta_2;
float epsilon;
std::vector<ShadowParameters> m; // History of gradients
std::vector<ShadowLookupParameters> lm;
std::vector<ShadowParameters> v; // History of deltas
std::vector<ShadowLookupParameters> lv;
private:
AdamTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief AMSGrad optimizer
* \details The AMSGrad optimizer is similar to Adam which uses unbiased estimates
* of the first and second moments of the gradient, however AMSGrad keeps the maximum of
* all the second moments and uses that instead of the actual second moments
*
* Reference : [On the Convergence of Adam and Beyond](https://openreview.net/forum?id=ryQu7f-RZ)
*
*/
struct AmsgradTrainer : public Trainer {
/**
* \brief Constructor
*
* \param m ParameterCollection to be trained
* \param learning_rate Initial learning rate
* \param beta_1 Moving average parameter for the mean
* \param beta_2 Moving average parameter for the variance
* \param eps Bias parameter \f$\epsilon\f$
*/
explicit AmsgradTrainer(ParameterCollection& m, float learning_rate = 0.001, float beta_1 = 0.9, float beta_2 = 0.999, float eps = 1e-8) :
Trainer(m, learning_rate), beta_1(beta_1), beta_2(beta_2), epsilon(eps) {}
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
float beta_1;
float beta_2;
float epsilon;
std::vector<ShadowParameters> m; // History of gradients
std::vector<ShadowLookupParameters> lm;
std::vector<ShadowParameters> v; // History of deltas
std::vector<ShadowLookupParameters> lv;
std::vector<ShadowParameters> vhat; // History of max moments
std::vector<ShadowLookupParameters> lvhat;
private:
AmsgradTrainer() {}
};
/**
* \ingroup optimizers
*
* \brief Exponentiated gradient optimizer with momentum and cyclical learning rate
* \details FIXME
*
* Reference : FIXME
*
*/
struct EGTrainer : public Trainer {
explicit EGTrainer(ParameterCollection& mod, real learning_rate = 0.1, real mom = 0.9, real ne = 0.0);
//-----------------------------------------------------------------------------------------
void enableCyclicalLR(float _learning_rate_min = 0.01, float _learning_rate_max = 0.1, float _step_size = 2000, float _gamma = 0.0) {
isCyclical = true;
e_min = _learning_rate_min;
e_max = _learning_rate_max;
step_size = _step_size;
gamma = _gamma;
it = 0;
}
virtual void update() override {
Trainer::update();
if (isCyclical) cyclic_update_eta();
}
//-----------------------------------------------------------------------------------------
void restart() override;
using Trainer::restart;
void save(std::ostream& os) override;
void populate(std::istream& is) override;
using Trainer::populate;
protected:
DYNET_TRAINER_DEFINE_DEV_IMPL()
virtual unsigned alloc_impl() override;
virtual unsigned alloc_lookup_impl() override;
//-----------------------------------------------------------------------------------------
real momentum;// with momentum
std::vector<ShadowParameters> hp; // (previous) history of parameters
std::vector<ShadowLookupParameters> hlp;
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
void cyclic_update_eta() {
float cycle = std::floor(1 + ((float) it) / (2 * step_size));
float x = std::abs( ((float) it) / step_size - 2 * cycle + 1);
learning_rate = e_min + ((1 - x) > 0 ? (e_max - e_min) * (1 - x) * (real) std::pow(gamma, it) : 0);
it++;
}
float e_min = 0;
float e_max = 0;
float step_size = 0;
float gamma = 0;
unsigned it = 0;
bool isCyclical;
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
// temporary tensors for EG calculation
Tensor zeg, meg;
//-----------------------------------------------------------------------------------------
private:
EGTrainer() {}
};
} // namespace dynet
#endif
| true |
4b27d4861014de4403a10a9e66cc5be3bcb12c3d | C++ | emresolugan/Robot-Turtles-Console-Game-with-Cpp- | /robot_turtles/main.cpp | WINDOWS-1258 | 9,333 | 3.296875 | 3 | [] | no_license | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char map[8][8];
char changed_map[8][8];
int i, j, flag_row, flag_column;
int k, move, l, direction=0, result;
char root;
// if move is L, flag is 0
// if move is R, flag is 1
// if direction is up, value is 8
// if direction is down, value is 2
// if direction is left, value is 4
// if direction is right, value is 6
// if result is 0, it is bug
// if result is 1 , it is diamond
for( i = 0; i < 8; i++ ) {
for( j = 0; j < 8; j++ ) {
cout << i+1 << ".row" << " and ";
cout << j+1 << ".column\n";
cin >> map[ i ][ j ];
}
}
map[7][0] = 'T';
for( i = 0; i < 8; i++ ) {
for( j = 0; j < 8; j++ ) {
changed_map[ i ][ j ] = map[ i ][ j ];
}
}
flag_row = 7;
flag_column = 0;
cout << "\nThis is your map that according to your values:\n";
for(int a=0; a<8; a++)
{
for(int b=0; b<8; b++)
cout<<" "<<map[a][b];
cout<<"\n";
}
cout << "\nEnter your move count:\n";
cin >> move;
for( k = 0; k < move; k++ ) {
cout << "\nEnter your root:\n";
cin >> root;
if(k == 0)
{
if(root == 'F')
{
if(map[7][1] == '.')
{
changed_map[7][1] = 'T';
changed_map[7][0] = '.';
flag_row = 7;
flag_column = 1;
direction = 6; //right
}
else if(map[7][1] == 'C')
{
//BUG
result = 0;
break;
}
else if(map[7][1] == 'I')
{
//BUG
result = 0;
break;
}
else if(map[7][1] == 'D')
{
//DAMOND
result = 1;
break;
}
}
else if(root == 'L')
{
direction = 8;
}
else if(root == 'R')
{
//RETURN BUG
result = 0;
break;
}
}
else
{
if(root == 'F')
{
if(direction == 2)
{
flag_row = flag_row + 1;
if(flag_row > 7)
{
//RETURN BUG
result = 0;
break;
}
else
{
if(changed_map[flag_row][flag_column] == '.'){
changed_map[flag_row - 1][flag_column] = '.';
changed_map[flag_row][flag_column] = 'T';
}
else if(changed_map[flag_row][flag_column] == 'I'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//FOUND DIAMOND
result = 1;
break;
}
}
}
else if(direction == 4)
{
if(flag_column == 0)
{
//RETURN BUG
result = 0;
break;
}
else
{
flag_column = flag_column - 1;
if(changed_map[flag_row][flag_column] == '.'){
changed_map[flag_row][flag_column + 1] = '.';
changed_map[flag_row][flag_column] = 'T';
}
else if(changed_map[flag_row][flag_column] == 'I'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//FOUND DIAMOND
result = 1;
break;
}
}
}
else if(direction == 6)
{
flag_column = flag_column + 1;
if(flag_column > 7)
{
//RETURN BUG
result = 0;
break;
}
else
{
if(changed_map[flag_row][flag_column] == '.'){
changed_map[flag_row][flag_column - 1] = '.';
changed_map[flag_row][flag_column] = 'T';
}
else if(changed_map[flag_row][flag_column] == 'I'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//FOUND DIAMOND
result = 1;
break;
}
}
}
else if(direction == 8)
{
if(flag_row == 0)
{
//RETURN BUG
result = 0;
break;
}
else
{
flag_row = flag_row - 1;
if(changed_map[flag_row][flag_column] == '.'){
changed_map[flag_row + 1][flag_column] = '.';
changed_map[flag_row][flag_column] = 'T';
}
else if(changed_map[flag_row][flag_column] == 'I'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//FOUND DIAMOND
result = 1;
break;
}
}
}
}
else if(root == 'L') // means rotate to left
{
if(direction == 2)
{
direction = 6;
}
else if(direction == 4)
{
direction = 2;
}
else if(direction == 6)
{
direction = 8;
}
else if(direction == 8)
{
direction = 4;
}
}
else if(root == 'R') // means rotate to right
{
if(direction == 2)
{
direction = 4;
}
else if(direction == 4)
{
direction = 8;
}
else if(direction == 6)
{
direction = 2;
}
else if(direction == 8)
{
direction = 6;
}
}
else if(root == 'X')
{
if(direction == 2)
{
flag_row = flag_row + 1;
if(flag_row > 7)
{
//RETURN BUG
result = 0;
break;
}
else
{
if(changed_map[flag_row][flag_column] == '.'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'I'){
changed_map[flag_row][flag_column] = '.';
flag_row = flag_row - 1;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//RETURN BUG
result = 0;
break;
}
}
}
else if(direction == 4)
{
if(flag_column == 0)
{
//RETURN BUG
result = 0;
break;
}
else
{
flag_column = flag_column - 1;
if(changed_map[flag_row][flag_column] == '.'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'I'){
changed_map[flag_row][flag_column] = '.';
flag_column = flag_column + 1;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//RETURN BUG
result = 0;
break;
}
}
}
else if(direction == 6)
{
flag_column = flag_column + 1;
if(flag_column > 7)
{
//RETURN BUG
result = 0;
break;
}
else
{
if(changed_map[flag_row][flag_column] == '.'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'I'){
changed_map[flag_row][flag_column] = '.';
flag_column = flag_column - 1;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//RETURN BUG
result = 0;
break;
}
}
}
else if(direction == 8)
{
if(flag_row == 0)
{
//RETURN BUG
result = 0;
break;
}
else
{
flag_row = flag_row - 1;
if(changed_map[flag_row][flag_column] == '.'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'I'){
changed_map[flag_row][flag_column] = '.';
flag_column = flag_column + 1;
}
else if(changed_map[flag_row][flag_column] == 'C'){
//RETURN BUG
result = 0;
break;
}
else if(changed_map[flag_row][flag_column] == 'D'){
//RETURN BUG
result = 0;
break;
}
}
}
}
}
cout << "\nThis is your map that according to your values:\n";
for(int e=0; e<8; e++)
{
for(int d=0; d<8; d++)
cout<<" "<<changed_map[e][d];
cout<<"\n";
}
}
if(result == 0)
{
printf("Bug!");
}
else
printf("Diamond!");
return 0;
}
| true |
f59911eec35dc18d41d5f2d95b699cd9560e6529 | C++ | jisukJ/network | /c05_TCP_base_server_and_client2/c5_op_server.cpp | UTF-8 | 2,031 | 2.59375 | 3 | [] | no_license | #include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
#define OPSZ 4
#define RLT_SIZE 4
void error_handling(char* message){
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
int main(int argc,char* argv[])
{
int serv_sock,clnt_sock;
char opinfo[BUF_SIZE];
int result,opnd_cnt;
int recv_cnt,recv_len;
struct sockaddr_in serv_addr,clnt_addr;
socklen_t clnt_adr_sz;
if(argc!=2){
printf("Usage : %s <port>\n",argv[0]);
exit(1);
}
serv_sock=socket(PF_INET,SOCK_STREAM,0);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
serv_addr.sin_port=htons(atoi(argv[2]));
if(bind(serv_sock,(sockaddr*)&serv_addr,sizeof(serv_addr))==-1){
error_handling("bind() error!");
}
if(listen(serv_sock,5)==-1){
error_handling("listen() error");
}
clnt_adr_sz=sizeof(clnt_addr);
for(int i=0;i<5;++i){
opnd_cnt=0;
clnt_sock=accept(serv_sock,(sockaddr*)&clnt_addr,&clnt_adr_sz);
read(clnt_sock,&opnd_cnt,1);
recv_len=0;
while(recv_len<(opnd_cnt*OPSZ+1)){
recv_cnt=read(clnt_sock,&opinfo[recv_len],BUF_SIZE-1);
recv_len+=recv_cnt;
}
result=calculate(opnd_cnt,(int*)opinfo,opinfo[recv_len-1]);
write(clnt_sock,(char*)&result,sizeof(result));
close(clnt_sock);
}
close(serv_sock);
return 0;
}
int calculate(int opnum,int opnds[],char op){
int result=opnds[0];
switch(op){
case '+':
for(int i=1;i<opnum;++i){
result+=opnds[i];
}
break;
case '-':
for(int i=1;i<opnum;++i){
result-=opnds[i];
}
break;
case '*':
for(int i=1;i<opnum;++i){
result*=opnds[i];
}
break;
}
} | true |
8f2da9bea6fcb82aa5ed484b174a1201252e0981 | C++ | Kitsch1/BOJ | /1436.cpp | UTF-8 | 502 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
int n,cnt = 1;
cin >> n;
if(n == 1){
cout << "666\n";
}
else{
for(int i=1666;i<10000000;i++){
string cur_str = to_string(i);
if(cur_str.find("666") != string::npos){
cnt += 1;
if(cnt == n){
cout << i << '\n';
break;
}
}
}
}
return 0;
} | true |
62491f1cfd2b525dd06d19f401bb30c8af62c8f2 | C++ | keyllalorraynna/AtividadesEmC | /Lista4/13questao.cpp | ISO-8859-1 | 750 | 3.390625 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<locale.h>
#include<iomanip>
using namespace std;
int main(void) {
setlocale(LC_ALL,"portuguese");
float altura, peso_ideal;
char sexo;
cout << " Informe a altura: ";
cin >> altura;
cout << " Informe o sexo sendo: " << endl;
cout << " F - Feminino | M - Masculino " << endl;
cin >> sexo;
if (sexo == 'M'){
peso_ideal = (72.7 * altura) - 58;
cout << fixed;
cout << setprecision(2) << " Seu peso ideal : " << peso_ideal << "Kg" << endl;
}
else
if (sexo == 'F'){
peso_ideal = (62.1 * altura) - 44.7;
cout << fixed;
cout << setprecision(2) << " Seu peso ideal : " << peso_ideal << "kg" << endl;
}
else
cout << " Opo invlida! " << endl;
return 0.0;
}
| true |
76cf150f6415c9f530fb4000cb3203d89cd6721d | C++ | boredbird/C_playground | /DataStructure/BOOK_G/第7章 图/图的表示_邻接矩阵/main.cpp | GB18030 | 3,742 | 3.46875 | 3 | [
"MIT"
] | permissive | // main7-1.cpp C7-1.cpp
#include "C1.h"
#include "C7-1.h"
void print(char *c)
{
printf("%s ", c);
}
bool LoopCommand(MGraph &g)
{
char command = '0';
int m;
VertexType v, w;
printf("\n");
printf("1-ͼ 2-Ҷ 3-붥 4-ɾ 5-Ķ\n");
printf("6-ӻ 7-ɾ 8-DFS 9-BFS 0-˳\n");
printf("\nҪִеIJţ");
fflush(stdin);
command = getchar();
fflush(stdin);
switch (command) {
case '1':
printf("\nͼڽӾ\n");
Display(g);
break;
case '2':
printf("ҪѯĶֵ");
scanf("%s", v);
m = LocateVex(g, v);
if (m < 0) {
printf("δѯ%s\n", v);
} else {
printf("%sͼеλΪ%d\n", v, m);
}
break;
case '3':
printf("ҪĶֵ");
scanf("%s", v);
InsertVex(g, v);
break;
case '4':
printf("ҪɾĶֵ");
scanf("%s", v);
DeleteVex(g, v);
break;
case '5':
printf("ҪĵĶֵֵ(ԿոΪ)");
scanf("%s%s", v, w);
PutVex(g, v, w);
break;
case '6':
printf("뻡βͻͷֵ(ԿոΪ)");
scanf("%s%s", v, w);
InsertArc(g, v, w);
break;
case '7':
printf("ɾĻβͻͷ(ԿոΪ)");
scanf("%s%s", v, w);
DeleteArc(g, v, w);
break;
case '8':
printf("ȱ\n");
DFSTraverse(g, print);
putchar('\n');
break;
case '9':
printf("ȱ\n");
BFSTraverse(g, print);
putchar('\n');
break;
case '0':
return false;
default:
printf("Ųڣ\n");
break;
}
return true;
}
void main()
{
MGraph g;
//printf("˳ѡͼ,,ͼ,\n");
CreateGraph(g);
while (LoopCommand(g));
DestroyGraph(g);
}
/*
void main()
{
int i,j,k,n;
MGraph g;
VertexType v1,v2;
printf("˳ѡͼ,,ͼ,\n");
for(i=0;i<4;i++) // ֤4
{
CreateGraph(g); // ͼg
Display(g); // ͼg
printf("¶㣬붥ֵ: ");
scanf("%s",v1);
InsertVex(g,v1);
printf("¶йصĻߣ뻡: ");
scanf("%d",&n);
for(k=0;k<n;k++)
{
printf("һֵ: ");
scanf("%s",v2);
if(g.kind<=1) //
{
printf("ͼһķ(0:ͷ 1:β): ");
scanf("%d",&j);
if(j) // v2ǻβ
InsertArc(g,v2,v1);
else // v2ǻͷ
InsertArc(g,v1,v2);
}
else //
InsertArc(g,v1,v2);
}
Display(g); // ͼg
printf("ɾ㼰صĻߣ붥ֵ: ");
scanf("%s",v1);
DeleteVex(g,v1);
Display(g); // ͼg
}
DestroyGraph(g); // ͼg
}
*/ | true |