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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9f605c409e74a8e5594d57dc7156e7318bbf5579 | C++ | luisthmn/ED_Parcial3 | /Graficas/funciones_lista_arcos.cpp | UTF-8 | 3,614 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include "Clases.cpp"
using namespace std;
//////////////////////////
// Lista Arcos
//////////////////////////
lista_arcos::lista_arcos(){
principio = NULL;
anterior = NULL;
siguiente = NULL;
Lugaragregado = NULL;
encontrado = NO;
donde = VACIO;
cuantos = 0;
}
//--------------------------------------------------
lista_arcos::~lista_arcos(){
caja1 *p;
while(principio){
p = principio;
principio = p ->siguiente;
delete p;
}
principio = NULL;
anterior = NULL;
siguiente = NULL;
Lugaragregado = NULL;
encontrado = NO;
donde = VACIO;
cuantos = 0;
}
//----------------------------------------------------------
void lista_arcos::buscar(int a){
caja1 *p;
if(principio == NULL){
encontrado = NO;
donde = VACIO;
return;
}
p = principio;
while(p){
if( p ->numNodo == a){
encontrado = SI;
if(p == principio){
donde = PRINCIPIO;
}
else if (p ->siguiente == NULL){
donde = FINAL;
}
else{
donde = ENMEDIO;
}
Lugaragregado = p;
return;
}
else if( p->numNodo < a){
encontrado = NO;
anterior = p;
p = p->siguiente;
}
else{
encontrado = NO;
if(p == principio){
donde = PRINCIPIO;
}
else{
donde = ENMEDIO;
}
return;
}
}
encontrado = NO;
donde = FINAL;
}
//------------------------------------------------------------
int lista_arcos::agregar(int a){
caja1 *p;
buscar(a);
if(encontrado == SI) return 0;
p = new caja1;
p->numNodo = a;
if(donde == VACIO){
p->siguiente = NULL;
principio = p;
}
else if(donde == PRINCIPIO){
p ->siguiente = principio;
principio = p;
}
else if (donde == FINAL){
p ->siguiente = NULL;
anterior ->siguiente = p;
}
else{
p ->siguiente = anterior ->siguiente;
anterior ->siguiente = p;
}
Lugaragregado = p;
cuantos++;
return 1;
}
//-----------------------------------------------------------------
int lista_arcos::borrar(int a){
caja1 *p;
buscar(a);
if(encontrado == NO) return 0;
if(donde == PRINCIPIO){
p = principio;
principio = p->siguiente;
}
else if(donde == ENMEDIO){
p = anterior ->siguiente;
anterior ->siguiente = p->siguiente;
}
else{
p = anterior ->siguiente;
anterior ->siguiente = NULL;
}
delete p;
cuantos--;
return 1;
}
//--------------------------------------------------------------------
void lista_arcos::pintar(){
caja1 *p;
p = principio;
while(p){
cout << p->numNodo;
// cout << ":" << p->direccion_nodo->numNodo;
cout << ":" << p->longitud;
if(p->siguiente != NULL) cout << ", ";
p = p->siguiente;
}
}
//------------------------------------------------------------------
int lista_arcos::Cuantos(){
return cuantos;
}
//-------------------------------------------------------------------
caja1* lista_arcos::lugar_agregado(){
return Lugaragregado;
}
//------------------------------------------------------------------
caja1* lista_arcos::Principio(){
return principio;
}
//--------------------------------------------------------------------
| true |
df53ccef2f1dfbbd45a886b6e09f1c274ddd4247 | C++ | jonaszell97/tblgen | /include/tblgen/Support/StringSwitch.h | UTF-8 | 1,158 | 3.1875 | 3 | [
"MIT"
] | permissive |
#ifndef TBLGEN_STRINGSWITCH_H
#define TBLGEN_STRINGSWITCH_H
#include "tblgen/Support/Optional.h"
#include <cassert>
#include <cstring>
namespace tblgen {
template<class T>
class StringSwitch {
private:
std::string strToMatch;
support::Optional<T> result;
public:
explicit StringSwitch(std::string_view strToMatch) : strToMatch(strToMatch)
{}
explicit StringSwitch(std::string &&strToMatch) : strToMatch(move(strToMatch))
{}
StringSwitch(const StringSwitch &) = delete;
void operator=(const StringSwitch &) = delete;
void operator=(StringSwitch &&other) = delete;
StringSwitch &Case(std::string_view match, const T& value)
{
if (!result.hasValue() && match == strToMatch)
{
result = value;
}
return *this;
}
T Default(const T& defaultValue)
{
if (result.hasValue())
{
return result.getValue();
}
return defaultValue;
}
[[nodiscard]] operator T()
{
assert(result.hasValue() && "StringSwitch does not have a value!");
return std::move(result.getValue());
}
};
} // namespace tblgen
#endif //TBLGEN_STRINGSWITCH_H
| true |
c487ce3f26d9c2d71d8ec7e6a42db8c2c60cb62d | C++ | vbhv17/DSA-Questions | /Array/28. Find the triplet that sum to a given value.cpp | UTF-8 | 1,926 | 3.78125 | 4 | [] | no_license | Naive Approach : Find all possible triplets using 3 nested for loops
bool find3Numbers(int A[], int n, int X)
{
for (int i = 0; i < n - 2; i++)
{
for (int j = i + 1; j < n - 1; j++)
{
for (int k = j + 1; k < n; k++)
{
if (A[i] + A[j] + A[k] == X)
return true;
}
}
}
return false;
}
TC: O(N^3)
SC :O(1)
Better Approach: Find two elements with two nested loops and do binary search for third element
bool find3Numbers(int A[], int n, int X)
{
sort(A, A + n); //Since we are gonna do binary search
for (int i = 0; i < n - 2; i++)
{
for (int j = i + 1; j < n - 1; j++)
{
int rem = X - A[i] - A[j];
int left = j + 1;
int right = n - 1;
while (left < right)
{
int mid = (left + right) / 2;
if (A[mid] < rem) {
left = mid + 1;
}
else if (A[mid] > rem) {
right = mid - 1;
}
else {
return true;
}
}
if (left == right and A[left] == rem)
return true;
}
}
return false;
}
TC: O(N^2LogN)
SC : O(1)
Optimal Solution: Find first element with one loop and then use two pointer to find
if remaining two elements are present in the array
class Solution {
public:
//Function to find if there exists a triplet in the
//array A[] which sums up to X.
bool find3Numbers(int A[], int n, int X)
{
sort(A, A + n); //since we are gonna use 2 pointer
for (int i = 0; i < n - 2; i++)
{
int left = i + 1;
int right = n - 1;
int rem = X - A[i];
while (left < right)
{
if (A[left] + A[right] > rem) {
right--;
}
else if (A[left] + A[right] < rem) {
left++;
}
else {
return true;
}
}
}
return false;
}
};
TC: O(N^2 + NLognN)
SC: O(1)
| true |
67d75dcc03efa83a04efdc00bb0b454b57826c6a | C++ | neilkakkar/NewBeginning | /618A.cpp | UTF-8 | 462 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define sz 1e6+6
int main()
{
int k;
cin>>k;
vector<int> ans;
ans.push_back(1);
k--;
while(k--)
{
ans.push_back(1);
while(ans[ans.size()-1]==ans[ans.size()-2])
{
ans[ans.size()-2]++;
//cout<<ans[ans.size()-2]<<endl;
ans.pop_back();
}
}
for(int i=0;i<ans.size();i++)
{
cout<<ans[i]<<" ";
}
}
| true |
8a08097783e0d17afc48ad195d797a8f8b0c3e0f | C++ | tyanmahou/Re-Abyss | /Re-Abyss/app/modules/Sfx/DeadEffect/DeadEffect.cpp | UTF-8 | 634 | 2.546875 | 3 | [] | no_license | #include <abyss/modules/Sfx/DeadEffect/DeadEffect.hpp>
namespace abyss::Sfx
{
constexpr ColorF defaultColor(1, 0, 0, 0.8);
DeadEffect::DeadEffect():
m_isValid(false)
{
m_shader
.setBlendMode(BlendMode::Color)
.setColor(defaultColor)
;
}
DeadEffect& DeadEffect::setColor(const s3d::ColorF& color)
{
m_shader.setColor(color);
return *this;
}
DeadEffect& DeadEffect::resetColor()
{
return setColor(defaultColor);
}
s3d::ScopedCustomShader2D DeadEffect::start() const
{
return m_shader.start();
}
}
| true |
8ffe9aa08ad26ddb968a94cf4b8a8a9ec78bcb6d | C++ | NikitaSTORM/ComplexNumber | /Source.cpp | UTF-8 | 1,757 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <clocale>
#include <vector>
#include <string>
#include <fstream>
#include <map>
#include <algorithm>
#include <cstdlib>
using namespace std;
class complex
{
public:
int a,
b;
void display();
void insert();
complex operator+(complex c2);
complex operator-(complex c2);
complex operator*(complex c2);
};
void complex::display() {
cout << a;
if (b < 0) {
cout << b << "i"<< endl;
}
else {
cout << " + " << b << "i" << endl;
}
}
void complex::insert()
{
cout << "Enter real & not real chast'(cherez probel)" << endl;
cin >>a >> b;
}
complex complex::operator+(complex c2) {
complex c1 = *this, c;
c.a = c1.a + c2.a;
c.b = c1.b + c2.b;
return c;
}
complex complex::operator-(complex c2) {
complex c1 = *this, c;
c.a = c1.a - c2.a;
c.b = c1.b - c2.b;
return c;
}
complex complex:: operator*(complex c2)
{
complex c1 = *this, c;
c.a = c1.a*c2.a - c1.b*c2.b;
c.b = c1.a*c2.b + c1.b*c2.a;
return c;
}
int main()
{
complex a, b, c;
cout << "slojenie" << endl;
a.insert();
cout << "Enter second chislo" << endl;
b.insert();
c = a + b;
cout<<"Result:"<<endl;
c.display();
cout << "---------------------------------" << endl;
cout << "vychitanie" << endl;
a.insert();
cout << "Enter second chislo" << endl;
b.insert();
c = a - b;
cout << "Result:" << endl;
c.display();
cout << "---------------------------------" << endl;
cout << "ymnojenie" << endl;
a.insert();
cout << "Enter second chislo" << endl;
b.insert();
c = a * b;
cout << "Result:" << endl;
c.display();
cout << "---------------------------------" << endl;
system("pause");
return 0;
}
| true |
987a74eb5876b30c8e59158df0e13a9317c042c6 | C++ | EhODavi/INF110 | /Aula 22/horariostruct.cpp | UTF-8 | 779 | 3.703125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
using namespace std;
struct Horario {
int horas, minutos;
};
void le(Horario &t) {
cin >> t.horas >> t.minutos;
}
void escreve(Horario t) {
cout << setfill('0') << setw(2) << t.horas << ":"
<< setfill('0') << setw(2) << t.minutos;
}
//Calcula a diferenca entre dois horarios
Horario calcdif (Horario i, Horario f) {
Horario t;
t.horas = f.horas - i.horas;
t.minutos = f.minutos - i.minutos;
if (t.minutos <0) {
t.minutos += 60;
t.horas -= 1;
}
return t;
}
int main() {
Horario inicio, fim;
le(inicio);
le(fim);
Horario diferenca;
diferenca = calcdif(inicio,fim);
cout << "De ";
escreve(inicio);
cout << " ate ";
escreve(fim);
cout << " tem ";
escreve(diferenca);
cout << " horas\n";
return 0;
}
| true |
c981fd2a5d55b5b63f56c5a844f6c92257cf39f6 | C++ | szamberlan/unipd_project | /P2_Project/ColiseumQT/pozione.cpp | UTF-8 | 1,054 | 2.890625 | 3 | [] | no_license | #include"pozione.h"
pozione::pozione(string n, int c, double a, int s, int d)
:oggettoAiuto(n,1,1,c,a), scelta(s), durata(d){}
pozione::~pozione(){}
int pozione::getCosto() const
{
if(durata)
return oggetto::getCosto();
else
return 0;
}
int pozione::getScelta() const {return scelta;}
int pozione::getDurata() const { return durata;}
double pozione::AiutoCaratteristiche(int sc, bool test)
{
if((sc==scelta)&&(durata))
{
if(test)
{
durata = durata-1;
return getAiuto();
}
else
return getAiuto();
}
else
return 0;
}
string pozione::getNomeUtilita(int) const
{
return "Aiuto";
}
string pozione::getInfoUtilita(int) const
{
std::ostringstream strs;
strs<<"Offrire Soccorso di "<< getAiuto()<<std::endl;
strs<<"Con un durata di utilizzo di "<<getDurata();
std::string str = strs.str();
return str;
}
string pozione::getTipologiaOggetto() const
{
return oggettoAiuto::getTipologiaOggetto() + " Pozione";
}
| true |
62484e60337efc8008f705f274598cf10a1bb028 | C++ | Gusyatnikova/SFML_study | /Snake/snake.cpp | UTF-8 | 4,941 | 2.9375 | 3 | [] | no_license | #include "snake.h"
Snake::Snake(int blockSize) {
m_size = blockSize;
m_lives = 3;
m_bodyCircle.setRadius(1.0f * m_size / 2);
Reset();
}
Snake::~Snake() {}
void Snake::Reset() {
m_snake_body.clear();
m_snake_body.push_back(SnakeSegment(15, 15));
m_snake_body.push_back(SnakeSegment(14, 15));
m_snake_body.push_back(SnakeSegment(13, 15));
m_dir = Direction::NONE;
m_speed = 12;
//m_lives = 3;
m_score = 0;
m_lost = false;
}
void Snake::SetDirection(Direction dir) { m_dir = dir; }
Direction Snake::GetDirection() const { return m_dir; }
Direction Snake::GetPhisicalDirection() const {
if (m_snake_body.size() < 2) { return Direction::NONE; }
const SnakeSegment& head = m_snake_body[0];
const SnakeSegment& neck = m_snake_body[1];
if (head.position.x == neck.position.x) {
return head.position.y > neck.position.y ? Direction::DOWN : Direction::UP;
}
else if (head.position.y == neck.position.y) {
return head.position.x > neck.position.x ? Direction::RIGHT : Direction::LEFT;
}
return Direction::NONE;
}
int Snake::GetSpeed() const { return m_speed; }
sf::Vector2i Snake::GetPosition() const {
return m_snake_body.empty() ? sf::Vector2i(1, 1) : m_snake_body.front().position;
}
int Snake::GetLives() const { return m_lives; }
int Snake::GetScore() const { return m_score; }
void Snake::IncreaseScore() { m_score += 10; }
bool Snake::HasLost() const { return m_lost; }
void Snake::Lose() { m_lost = true; --m_lives; }
void Snake::ToggleLost() { m_lost = !m_lost; }
void Snake::Extend() {
if (m_snake_body.empty()) { return; }
SnakeSegment& tail_head =
m_snake_body[m_snake_body.size() - 1];
if (m_snake_body.size() > 1) {
SnakeSegment& tail_bone =
m_snake_body[m_snake_body.size() - 2];
if (tail_head.position.x == tail_bone.position.x) {
if (tail_head.position.y > tail_bone.position.y) {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x, tail_head.position.y + 1));
}
else {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x, tail_head.position.y - 1));
}
}
else if (tail_head.position.y == tail_bone.position.y) {
if (tail_head.position.x > tail_bone.position.x) {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x + 1, tail_head.position.y));
}
else {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x - 1, tail_head.position.y));
}
}
}
else {
if (m_dir == Direction::UP) {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x, tail_head.position.y + 1));
}
else if (m_dir == Direction::DOWN) {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x, tail_head.position.y - 1));
}
else if (m_dir == Direction::LEFT) {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x + 1, tail_head.position.y));
}
else if (m_dir == Direction::RIGHT) {
m_snake_body.push_back(SnakeSegment(
tail_head.position.x - 1, tail_head.position.y));
}
}
}
void Snake::Tick() {
//update, fixed-time
if (m_snake_body.empty()) return;
if (m_dir == Direction::NONE) return;
Move();
CheckCollsion();
}
void Snake::Move() {
for (size_t i = m_snake_body.size() - 1; i > 0; --i) {
m_snake_body[i].position = m_snake_body[i - 1].position;
}
switch (m_dir)
{
case Direction::UP:
--m_snake_body[0].position.y;
break;
case Direction::DOWN:
++m_snake_body[0].position.y;
break;
case Direction::LEFT:
--m_snake_body[0].position.x;
break;
case Direction::RIGHT:
++m_snake_body[0].position.x;
break;
default:
break;
}
}
void Snake::CheckCollsion() {
if (m_snake_body.size() < 5) return;
SnakeSegment& head = *m_snake_body.begin();
for (auto it = std::next(m_snake_body.begin()); it != m_snake_body.end(); ++it) {
if (it->position == head.position) {
//int segments_cnt = m_snake_body.end() - it;
//Cut(segments_cnt);
m_dir = Direction::NONE;
m_lost = true;
break;
}
}
}
void Snake::Cut(int segments_cnt) {
m_snake_body.erase(std::next(m_snake_body.begin(), segments_cnt), m_snake_body.end());
--m_lives;
}
void Snake::Render(sf::RenderWindow& wnd) {
if (m_snake_body.empty()) return;
auto snake_head = m_snake_body.begin();
m_bodyCircle.setFillColor(sf::Color::Yellow);
m_bodyCircle.setPosition(
snake_head->position.x * m_size,
snake_head->position.y * m_size);
wnd.draw(m_bodyCircle);
m_bodyCircle.setFillColor(sf::Color::Green);
for (auto it = m_snake_body.begin() + 1; it != m_snake_body.end(); ++it) {
m_bodyCircle.setPosition(it->position.x * m_size, it->position.y * m_size);
wnd.draw(m_bodyCircle);
}
}
bool Snake::HasSegment(sf::Vector2i pos) const {
for (auto &segment : m_snake_body) {
if (segment.position.x == pos.x &&
segment.position.y == pos.y) return true;
}
return false;
}
| true |
4632d4cbe4078ceba44e52dc473a72e9cdd0fe4c | C++ | nallicock/CustomerInventoryOrders | /CustomerOrder.h | UTF-8 | 924 | 2.890625 | 3 | [] | no_license | /*
Name: Nicholas Allicock
Date: Dec 1 2019
Section: NFG
Email: nallicock@myseneca.ca
Student ID: 103099164
*/
#ifndef CUSTOMERORDER_H
#define CUSTOMERORDER_H
#include <string>
#include <iostream>
#include "Item.h"
struct ItemInfo
{
std::string m_itemName;
unsigned int m_serialNumber = 0;
bool m_fillState = false;
ItemInfo(std::string src) : m_itemName(src) {};
};
class CustomerOrder {
std::string m_name;
std::string m_product;
unsigned int m_cntItem;
ItemInfo** m_lstItem;
static size_t m_widthField;
public:
CustomerOrder();
CustomerOrder(std::string);
CustomerOrder(const CustomerOrder &);
CustomerOrder(CustomerOrder &&) noexcept;
~CustomerOrder();
CustomerOrder & operator=(CustomerOrder &&);
CustomerOrder & operator=(const CustomerOrder &) = delete;
bool getItemFillState(std::string) const;
bool getOrderFillState() const;
void fillItem(Item &, std::ostream &);
void display(std::ostream &) const;
};
#endif | true |
71788ff4d9313eec53ba5fd8656d36181003c538 | C++ | reverse-dusk/Game-Tank | /game-tank/TankFighting/PlayerTank.cpp | GB18030 | 2,902 | 2.90625 | 3 | [] | no_license | #include "PlayerTank.h"
PLAYERTANK::PLAYERTANK()
{
if (map.get_info(8, 18) == CMAP::GRAPH_BLACK)
{
set_coord(8, 18);
set_direction(OBJ_UP);
}
else
{
set_coord(12, 18);
set_direction(OBJ_UP);
}
write_coord_info(CMAP::PLAYERTANK_UP);
pBullet = nullptr;
}
PLAYERTANK::~PLAYERTANK()
{
if (pBullet != nullptr)
{
delete pBullet;
}
}
void PLAYERTANK::creat_bullet()//ӵ
{
if (pBullet == nullptr)
{
pBullet = new BULLET();
pBullet->set_belong(BULLET::PLAYER);
pBullet->set_direction(get_direction());
switch (get_direction())
{
case OBJ_UP:
pBullet->set_coord(get_x(), get_y() - 1);
break;
case OBJ_DOWN:
pBullet->set_coord(get_x(), get_y() + 1);
break;
case OBJ_LEFT:
pBullet->set_coord(get_x() - 1, get_y());
break;
case OBJ_RIGHT:
pBullet->set_coord(get_x() + 1, get_y());
break;
default:break;
}
}
}
void PLAYERTANK::destroy_bullet()//ݻӵ
{
if (pBullet != nullptr)
{
switch (map.get_info(pBullet->get_x(), pBullet->get_y()))
{
case CMAP::BULLET_UP:
case CMAP::BULLET_DOWN:
case CMAP::BULLET_LEFT:
case CMAP::BULLET_RIGHT:
pBullet->clear_coord_info();
break;
default:break;
}
delete pBullet;
pBullet = nullptr;
}
}
int PLAYERTANK::move_bullet()//ƶӵ
{
if (pBullet == nullptr)
{
return BULLET::CRASH_NONE;
}
return pBullet->move();
}
int PLAYERTANK::get_bullet_crash_bullet_x() const//ȡײӵ
{
if (pBullet != nullptr)
{
return pBullet->get_destroy_bullet_coord_x();
}
return 0;
}
int PLAYERTANK::get_bullet_crash_bullet_y() const//ȡײӵ
{
if (pBullet != nullptr)
{
return pBullet->get_destroy_bullet_coord_y();
}
return 0;
}
int PLAYERTANK::get_bullet_crash_tank_x() const//ȡײ̹˵
{
if (pBullet != nullptr)
{
return pBullet->get_enemy_coord_x();
}
return 0;
}
int PLAYERTANK::get_bullet_crash_tank_y() const//ȡײ̹˵
{
if (pBullet != nullptr)
{
return pBullet->get_enemy_coord_y();
}
return 0;
}
bool PLAYERTANK::has_bullet()
{
if (pBullet == nullptr)
{
return false;
}
return true;
}
int PLAYERTANK::get_bullet_x() const
{
if (pBullet != nullptr)
{
return pBullet->get_x();
}
return 0;
}
int PLAYERTANK::get_bullet_y() const
{
if (pBullet != nullptr)
{
return pBullet->get_y();
}
return 0;
} | true |
ba70f91040c51c6c47854324bcc202880a6de22c | C++ | Dheeraj-cyber/OpenGL-Samples | /ShadowMap.cpp | UTF-8 | 2,528 | 2.984375 | 3 | [] | no_license | #include "ShadowMap.h"
ShadowMap::ShadowMap()
{
FBO = 0;
shadowMap = 0;
}
bool ShadowMap::Init(GLuint width, GLuint height)
{
shadowWidth = width; shadowHeight = height;
glGenFramebuffers(1, &FBO); //Generates the frame buffer. A frame buffer is basically the screen. We will be creating another frame buffer that won't be visible on the screen and then, we are going to draw the texture to that, to reflect it on the actual screen, i.e. the default frame buffer
//Here 1 - no. of frame buffers. &FBO - reference of frame buffer object
glGenTextures(1, &shadowMap);
glBindTexture(GL_TEXTURE_2D, shadowMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowWidth, shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr); //0 - mipmap level, GL_DEPTH_COMPONENT - says how deep the image is based on the normalized coordinates
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); //GL_TEXTURE_WRAP_S specifies how to handle the image when it's around the border. S refers to the x-axis
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
float bColour[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, bColour);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //GL_LINEAR means when you zoom in to the image, if you zoom in or zoom out of the image, it will try and blend the pixels together
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, FBO); //binds the FBO ID with the frame buffer
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMap, 0); //Here, 0 specifies the mipmap level
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); //check for errors
if (status != GL_FRAMEBUFFER_COMPLETE)
{ //If the frame buffer failed
printf("Framebuffer Error: %i\n", status);
return false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0); //unbind the framebuffer
return true;
}
void ShadowMap::write()
{
glBindFramebuffer(GL_FRAMEBUFFER, FBO); //draws to the alternative frame buffer, i.e. the buffer which cannot be seen
}
void ShadowMap::Read(GLenum textureUnit)
{
glActiveTexture(textureUnit);
glBindTexture(GL_TEXTURE_2D, shadowMap);
}
ShadowMap::~ShadowMap()
{
if (FBO)
{
//if we have a FBO that is destroyed
glDeleteFramebuffers(1, &FBO);
}
if (shadowMap)
{ //if there is a shadow map
glDeleteTextures(1, &shadowMap);
}
}
| true |
8d68e03b579c4d0663235cda365afec050b7f387 | C++ | bogea-cis/testusblib | /source/common/CBasicStringList.h | UTF-8 | 5,574 | 3.109375 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
// Descricao:
// Autor: Amadeu Vilar Filho / Luis Gustavo de Brito
// Data de criacao: 11/12/2007
//
// Alteracoes:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _CBASIC_STRING_LIST_H_
#define _CBASIC_STRING_LIST_H_
#include <stdarg.h>
#include "CMutex.h"
const unsigned int DEFAULT_BLOCK_LEN = 8;
class CBasicStringList
{
public:
//construtor da classe
//parametros
CBasicStringList();
//destrutor da classe
virtual ~CBasicStringList();
//popula a lista com string separada por tokens
//parametros
//strList: string com separadores
//separators: separadores da string
static CBasicStringList* create(const char* strList, const char* separators);
bool lock ();
void unlock ();
//popula a lista com string separada por tokens binarios (usado nos campos lpszextra do WOSA)
//parametros
//strList: string com separadores
//separator: separador da string, serah usado para encontrar os separadores
//separatorLen: tamanho da string de separator
//terminator: terminador da string, serah usado para identificar o fim da string (no WOSA eh um \0\0)
//terminatorLen: tamanho da string de terminator
static CBasicStringList* create(const char* strList,
const unsigned char* separator,
int separatorLen,
const unsigned char* terminator,
int terminatorLen);
//adiciona uma string na lista
//parametros
//str: string que sera adicionada
void add(const char* str);
//adiciona strings separadas por tokens
//parametros
//strList: string com separadores
//separator: separadores da string
void add(const char* strList, const char* separator);
//adiciona todo o conteudo de uma CBasicStringList no objeto atual
//parametros
//bsl: lista de dados
void add(const CBasicStringList& bsl);
//adiciona um char ao objeto atual
//parametros
//c: char a ser adicionado
void add(const char c);
void addFormatted (const char* format, ...);
//atualiza o valor do conteudo de um determinado index
//parametros
//index: indice de onde se deseja fzer a altera��o
//newValue: novo valor que deve ser assumido
void update(int index, const char* newValue);
//remove um elemento da lista
//parametros
//index: indice do elemento que se deseja apagar
void remove(int index);
//remove um numero de elementos a partir de um determinado indice
//parametros
//index: indice inicial do(s) elemento(s) que se deseja(m) apagar
//count: numero de elementos que v�o ser apagados a partir do index inicial
void remove(int index, int count);
//retorna o numero de elementos
int count();
//apaga todos os elementos da lista
void clear();
//retorna o index da primeira ocorrencia de uma determinada string (str)
//parametros
//str: string que se deseja procurar
//caseSesitive: determina se a busca vai ser case sensitive ou n�o(default)
int indexOf(const char* str, bool caseSensitive = false);
//ordena a lista
//parametros
//ascending: determina se vai ordenar em ordem crescente(default) ou n�o
//caseSesitive: determina se vai ser case sensitive ou n�o(default)
void sort(bool ascending = true, bool caseSensitive = false);
//popula a lista com string separada por tokens
//parametros
//strList: string com separadores
//separators: separadores da string
void deserialize(const char* strList, const char* separators);
//cria uma string onde os elementos s�o separados por um dado separador(separator),
//esta string deve ser desalocada ap�s o uso com usando-se delete[]
//parametros
//separator: separador usado para separar os elementos
char* serialize(const char separator);
//popula a lista com string separada por tokens binarios (usado nos campos lpszextra do WOSA)
//parametros
//strList: string com separadores
//separator: separador da string, serah usado para encontrar os separadores
//separatorLen: tamanho da string de separator
//terminator: terminador da string, serah usado para identificar o fim da string (no WOSA eh um \0\0)
//terminatorLen: tamanho da string de terminator
void deserializeBin(const char* strList,
const unsigned char* separator,
int separatorLen,
const unsigned char* terminator,
int terminatorLen);
//separator: separador da string, serah usado para separar as strigs
//separatorLen: tamanho da string de separator
//terminator: terminador da string, serah appendado no final
//terminatorLen: tamanho da string de terminator
//retorno: um buffer que deve ser deletado apos o uso
char* serializeBin(const unsigned char* separator,
int separatorLen,
const unsigned char* terminator,
int terminatorLen);
static void bslFilter (CBasicStringList& input, const char* searchData, CBasicStringList& output);
//obtem um elemento de um dado indice
const char* operator[] (int idx);
//obtem um elemento de um dado indice
const char* elmtAt(int idx);
#ifdef _DEBUG
void show ();
#endif
private:
void allocMemory(int blocks);
void freeMemory(int blocks);
void quickSortMain(char** items, int count);
void quickSort(char** items, int left, int right);
char* createBuffer (const char* pStart, const char* pEnd);
private:
char** m_strArray;
unsigned int m_usedLen;
unsigned int m_realLen;
bool m_acending;
bool m_caseSensitive;
CMutex m_mutex;
};
#endif //_CBASIC_STRING_LIST_H_
| true |
c845b0bda0f50041e898f86263def236edc2429a | C++ | Fockewulf44/HeaterOperator | /src/HeaterOperator.cpp | UTF-8 | 6,289 | 2.578125 | 3 | [
"MIT"
] | permissive |
#include "HeaterOperator.h"
#include <Servo.h>
#include <Arduino.h>
#include "ArduinoJson.h"
// Servo servo1;
HeaterOperator::HeaterOperator(uint16_t servoPin, uint16_t dthPin)
{
this->servoPin = servoPin;
this->dthPin = dthPin;
this->servo1 = Servo();
this->isHeaterEnabled = false;
this->isHeaterHigh = false;
this->isStartedBySchedule = false;
this->IsSchedule1Enabled = false;
this->IsSchedule1Activated = false;
this->IsSchedule2Enabled = false;
this->IsSchedule2Activated = false;
//Predefining manually
struct tm predefined;
predefined.tm_hour = 6;
predefined.tm_min = 40;
this->Schedule1TurnOn = predefined;
predefined.tm_hour = 7;
predefined.tm_min = 50;
this->Schedule1TurnOff = predefined;
this->IsSchedule1Enabled = true;
}
HeaterOperator::~HeaterOperator()
{
this->servo1.~Servo();
}
void HeaterOperator::TurnOnHeater()
{
servo1.attach(servoPin);
servo1.write(50);
delay(200);
servo1.write(90);
delay(400);
this->servo1.detach();
isHeaterEnabled = true;
isHeaterHigh = false;
}
void HeaterOperator::TurnOffHeater()
{
servo1.attach(servoPin);
servo1.write(50);
delay(200);
servo1.write(90);
delay(400);
this->servo1.detach();
isHeaterEnabled = false;
isHeaterHigh = false;
}
void HeaterOperator::UpdateHeaterPower()
{
if (isHeaterEnabled)
{
servo1.attach(servoPin);
this->servo1.write(140);
delay(200);
this->servo1.write(90);
delay(400);
this->servo1.detach();
isHeaterHigh = !isHeaterHigh;
}
}
void HeaterOperator::PutServoNeutral()
{
servo1.attach(servoPin);
servo1.write(100);
delay(400);
servo1.detach();
delay(50);
servo1.attach(servoPin);
servo1.write(90);
delay(400);
servo1.detach();
}
void HeaterOperator::ProcessCommand(uint8_t *data)
{
StaticJsonBuffer<300> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject((const char *)data);
if (root.success())
{
if (root.containsKey("turnOnHeater"))
{
TurnOnHeater();
}
if (root.containsKey("turnOffHeater"))
{
TurnOffHeater();
}
if (root.containsKey("UpdateHeaterPower"))
{
UpdateHeaterPower();
}
if (root.containsKey("write"))
{
//Just for test
servo1.attach(servoPin);
servo1.write(root["write"]);
delay(200);
servo1.write(90);
delay(200);
this->servo1.detach();
// delay(400);
}
if (root.containsKey("detach"))
{
Serial.println(root["detach"].asString());
servo1.detach();
}
if (root.containsKey("attach"))
{
Serial.println(root["attach"].asString());
servo1.attach(servoPin);
}
}
else
{
}
}
void HeaterOperator::SetConfig(uint8_t *data)
{
StaticJsonBuffer<2000> jsonBuffer;
JsonObject &root = jsonBuffer.parseObject((const char *)data);
if (root.success())
{
if (root.containsKey("schedules"))
{
Serial.println("schedules");
JsonObject &schedules = root["schedules"];
if (schedules.containsKey("schedule1"))
{
JsonObject &schedule1 = schedules["schedule1"];
IsSchedule1Enabled = schedule1["isEnabled"] == 1 ? true : false;
JsonObject &turnOn = schedule1["turnOn"];
Schedule1TurnOn.tm_hour = turnOn["hour"];
Schedule1TurnOn.tm_min = turnOn["min"];
Schedule1TurnOn.tm_sec = 0;
JsonObject &turnOff = schedule1["turnOff"];
Schedule1TurnOff.tm_hour = turnOff["hour"];
Schedule1TurnOff.tm_min = turnOff["min"];
Schedule1TurnOff.tm_sec = 0;
}
if (schedules.containsKey("schedule2"))
{
JsonObject &schedule2 = schedules["schedule2"];
IsSchedule2Enabled = schedule2["isEnabled"] == 1 ? true : false;
JsonObject &turnOn = schedule2["turnOn"];
Schedule2TurnOn.tm_hour = turnOn["hour"];
Schedule2TurnOn.tm_min = turnOn["min"];
Schedule2TurnOn.tm_sec = 0;
JsonObject &turnOff = schedule2["turnOff"];
Schedule2TurnOff.tm_hour = turnOff["hour"];
Schedule2TurnOff.tm_min = turnOff["min"];
Schedule2TurnOff.tm_sec = 0;
}
}
}
}
void HeaterOperator::GetConfig(char *outputJSON)
{
StaticJsonBuffer<2000> JSONbuffer;
JsonObject &root = JSONbuffer.createObject();
JsonObject &Schedules = JSONbuffer.createObject();
JsonObject &Schedule1 = JSONbuffer.createObject();
JsonObject &turnOn = JSONbuffer.createObject();
JsonObject &turnOff = JSONbuffer.createObject();
turnOn["hour"] = Schedule1TurnOn.tm_hour;
turnOn["min"] = Schedule1TurnOn.tm_min;
turnOn["sec"] = Schedule1TurnOn.tm_sec;
turnOff["hour"] = Schedule1TurnOff.tm_hour;
turnOff["min"] = Schedule1TurnOff.tm_min;
turnOff["sec"] = Schedule1TurnOff.tm_sec;
Schedule1["isEnabled"] = IsSchedule1Enabled ? 1 : 0;
Schedule1["turnOn"] = turnOn;
Schedule1["turnOff"] = turnOff;
Schedules["schedule1"] = Schedule1;
root["schedules"] = Schedules;
root.printTo(outputJSON, 2000);
// Serial.println(outputJSON);
}
void HeaterOperator::BlinkBlueLed()
{
// LED 2
// ####Setupe### pinMode(LED, OUTPUT);
// delay(100);
// digitalWrite(LED, HIGH);
// delay(100);
// digitalWrite(LED, LOW);
}
void HeaterOperator::LoopProcessor()
{
try
{
struct tm timeinfo;
if (getLocalTime(&timeinfo))
{
if (IsSchedule1Enabled)
{
if (timeinfo.tm_hour == Schedule1TurnOn.tm_hour && timeinfo.tm_min == Schedule1TurnOn.tm_min && timeinfo.tm_sec == 00)
{
if (IsSchedule1Activated == false)
{
this->IsSchedule1Activated = true;
TurnOnHeater();
UpdateHeaterPower();
Serial.println("Turning on Heater");
}
}
else
{
IsSchedule1Activated = false;
}
if (timeinfo.tm_hour == Schedule1TurnOff.tm_hour && timeinfo.tm_min == Schedule1TurnOff.tm_min && timeinfo.tm_sec == 00)
{
if (IsSchedule1Activated == false)
{
this->IsSchedule1Activated = true;
TurnOffHeater();
Serial.println("Turning off Heater");
}
}
else
{
IsSchedule1Activated = false;
}
}
}
}
catch (std::exception err)
{
Serial.println(err.what());
}
} | true |
96613c2a0df361141b219bcc83483221ae596d82 | C++ | TomStevens7533/Europa | /Europa/src/Europa/structs.h | UTF-8 | 753 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <glm/glm.hpp>
#include <vector>
namespace Eu {
struct VertexInput
{};
struct ChunkVertexInput : VertexInput
{
glm::vec3 Position{};
int tex{};
int UV{};
};
struct Vertex_Input
{
Vertex_Input() = default;
Vertex_Input(glm::vec3 position, glm::vec3 color, glm::vec2 uv, glm::vec3 normal) : Position{position}, Color{color}, uv{uv}, Normal{normal}
{
}
glm::vec3 Position;
glm::vec3 Color;
glm::vec2 uv;
glm::vec3 Normal;
bool operator == (Vertex_Input rhs) {
if (this->Position == rhs.Position && this->uv == rhs.uv && this->Color == rhs.Color)
return true;
else return false;
}
};
struct OBJ {
std::vector<Vertex_Input> m_VertexBuffer;
std::vector<uint32_t> m_IndexBuffer;
};
}
| true |
21100ddbe784474f6a15598139a22616e5ef3990 | C++ | SunInTeo/ImageEditor-Parser | /Header Files/Exceptions.h | UTF-8 | 2,322 | 3.0625 | 3 | [] | no_license | /** @file Exceptions.h
* @brief Provides different exceptions.
*
* @author Teodor Karushkov
* @bug No known bugs.
*/
#pragma once
#include <iostream>
class NoFileOpened : public std::exception
{
const char *what() const throw()
{
return "No file is opened now.";
}
};
class InvalidOpenFunc : public std::exception
{
const char *what() const throw()
{
return "Invalid arguments for open(), correct usage: open [path]";
}
};
class InvalidNewFunc : public std::exception
{
const char *what() const throw()
{
return "Invalid arguments for new(), correct usage: new [width] [height] [fillColor]";
}
};
class InvalidSaveAsFunc : public std::exception
{
const char *what() const throw()
{
return "Invalid arguments for saveas(), correct usage: saveas [path]";
}
};
class InvalidCropFunc : public std::exception
{
const char *what() const throw()
{
return "Invalid arguments for crop(), correct usage: crop [point1 x] [point1 y] [point2 x] [point2 y]";
}
};
class InvalidResizeFunc : public std::exception
{
const char *what() const throw()
{
return "Invalid arguments used for resize(), correct ways to use the command:\n resize [width] [height]\n resize [percentage]";
}
};
class IncorrectPBMExtension : public std::exception
{
const char *what() const throw()
{
return "You have given an incorrect extension for this type of file(P1), please use .pbm";
}
};
class IncorrectPGMExtension : public std::exception
{
const char *what() const throw()
{
return "You have given an incorrect extension for this type of file(P2), please use .pgm";
}
};
class IncorrectPPMExtension : public std::exception
{
const char *what() const throw()
{
return "You have given an incorrect extension for this type of file(P3), please use .ppm";
}
};
class DitherComands : public std::exception
{
const char *what() const throw()
{
return "Unknown dither number, please use one of the following ones:\n1: basic 1-dimensional dither\n2: Floyd-Steinberg\n3: Fake Floyd-Steinberg\n4: Jarvis, Judice, and Ninke\n5: Stucki\n6: Atkinson\n7: Burkes\n8: Sierra\n9: Two-Row Sierra\n10: Sierra Lite\n11: 4x4 Bayer matrix\n12: 8x8 Bayer matrix\n";
}
}; | true |
d201a1277a21945b2206e18c3a996cb72682d9ce | C++ | scott0129/raytracer | /objectCollection.cpp | UTF-8 | 6,739 | 2.953125 | 3 | [] | no_license | #include "objectCollection.h"
#include <limits>
#include <stdlib.h>
void recInsert(BVH::BVHNode* subroot, Hittable* object) {
//every node it enters, if the object is bigger than the node, expand the node
for (int i = 0; i < 3; i++) {
if (object->hiCorner()[i] > subroot->hiPoint->get(i)) {
subroot->hiPoint->get(i) = object->hiCorner()[i];
}
if (object->loCorner()[i] < subroot->loPoint->get(i)) {
subroot->loPoint->get(i) = object->loCorner()[i];
}
}
if ( subroot->isLeaf() ) {
if (subroot->obj == NULL) {
//If it's a leaf and there's no object (only happens at root) put it there.
subroot->obj = object;
return;
} else {
/* If there IS an object there, divide the segment into 2 parts on a random axis.
Then, create 2 new subBoxes, and put each object in the respective upper/lower box.
If the objects overlap each other on that axis, adjust the 2 new Node's corners accordingly.
*/
subroot->axis = rand()%3;
int axis = subroot->axis;
double divide = (subroot->obj->getCenter()[axis] + object->getCenter()[axis])/2.0;
subroot->divide = divide;
Vector* newHi;
Vector* newLo;
//Deciding which axis to divide on
switch(axis) {
case 0:
newHi = new Vector(divide, subroot->hiPoint->y, subroot->hiPoint->z);
newLo = new Vector(divide, subroot->loPoint->y, subroot->loPoint->z);
break;
case 1:
newHi = new Vector(subroot->hiPoint->x, divide, subroot->hiPoint->z);
newLo = new Vector(subroot->loPoint->x, divide, subroot->loPoint->z);
break;
default:
newHi = new Vector(subroot->hiPoint->x, subroot->hiPoint->y, divide);
newLo = new Vector(subroot->loPoint->x, subroot->loPoint->y, divide);
}
subroot->left = new BVH::BVHNode(subroot->loPoint, newHi);
subroot->right = new BVH::BVHNode(newLo, subroot->hiPoint);
//Giving the appropriate subtree the appropriate object for easy searching.
if (subroot->obj->getCenter()[axis] < divide) {
subroot->left->obj = subroot->obj;
subroot->right->obj = object;
} else {
subroot->left->obj = object;
subroot->right->obj = subroot->obj;
}
//These next if statements allow for overlap, so that objects don't get "cut"
for (int i = 0; i < 3; i++) {
if (subroot->left->hiPoint->get(i) < subroot->left->obj->hiCorner()[i]) {
//@TODO there should be something weird with the hiPoint[]?
subroot->left->hiPoint->get(i) = subroot->left->obj->hiCorner()[i];
}
if (subroot->right->loPoint->get(i) > subroot->right->obj->loCorner()[i]) {
subroot->right->loPoint->get(i) = subroot->right->obj->loCorner()[i];
}
if (subroot->left->loPoint->get(i) > subroot->left->obj->loCorner()[i]) {
subroot->left->loPoint->get(i) = subroot->left->obj->loCorner()[i];
subroot->loPoint->get(i) = subroot->left->loPoint->get(i);
}
if (subroot->right->hiPoint->get(i) < subroot->right->obj->hiCorner()[i]) {
subroot->right->hiPoint->get(i) = subroot->right->obj->hiCorner()[i];
subroot->hiPoint->get(i) = subroot->right->hiPoint->get(i);
}
}
}
} else {
if (object->getCenter()[subroot->axis] < subroot->left->hiPoint->get(subroot->axis) ) {
recInsert(subroot->left, object);
} else {
recInsert(subroot->right, object);
}
}
}
BVH::BVH(std::vector<Hittable*> objArray, Vector* low, Vector* high) {
setSize(objArray.size());
root = new BVHNode(low, high);
for (size_t i = 0; i < objArray.size(); i++) {
recInsert(root, objArray[i]);
}
}
bool boxIntersect(Vector* origin, Vector* direction, Vector* lo, Vector* hi) {
double minT = std::numeric_limits<double>::min();
double maxT = std::numeric_limits<double>::max();
if (direction->x != 0) {
double x1t = (lo->x - origin->x)/direction->x;
double x2t = (hi->x - origin->x)/direction->x;
minT = std::max(minT, std::min(x1t, x2t));
maxT = std::min(maxT, std::max(x1t, x2t));
}
if (direction->y != 0) {
double y1t = (lo->y - origin->y)/direction->y;
double y2t = (hi->y - origin->y)/direction->y;
minT = std::max(minT, std::min(y1t, y2t));
maxT = std::min(maxT, std::max(y1t, y2t));
}
if (direction->z != 0) {
double z1t = (lo->z - origin->z)/direction->z;
double z2t = (hi->z - origin->z)/direction->z;
minT = std::max(minT, std::min(z1t, z2t));
maxT = std::min(maxT, std::max(z1t, z2t));
}
return maxT > minT;
}
Hittable* recIntersect(BVH::BVHNode* subroot, Vector* pos, Vector* vect) {
if (subroot == NULL) {
return NULL;
}
if (subroot->isLeaf()) {
if (isnan(subroot->obj->collideT(pos, vect))) {
return NULL;
} else {
return subroot->obj;
}
} else if (!boxIntersect(pos, vect, subroot->loPoint, subroot->hiPoint)) {
return NULL;
}
Hittable* leftResult = recIntersect(subroot->left, pos, vect);
Hittable* rightResult = recIntersect(subroot->right, pos, vect);
if (leftResult == NULL) {
return rightResult;
} else if (rightResult == NULL) {
return leftResult;
} else {
if (leftResult->collideT(pos, vect) < rightResult->collideT(pos, vect)) {
return leftResult;
} else {
return rightResult;
}
}
}
Hittable* BVH::intersect(Vector* pos, Vector* vect) {
return recIntersect(root, pos, vect);
}
//--------------------------------------non-bvh---------------------------------
nonBVH::nonBVH(std::vector<Hittable*> list, Vector low, Vector high) {
_list = list;
}
Hittable* nonBVH::intersect(Vector* pos, Vector* vect) {
double shortest = std::numeric_limits<double>::max();
Hittable* nearest = NULL;
for (Hittable* obj : _list) {
double dist = obj->collideT(pos, vect);
if (!isnan(dist)) {
if (shortest > dist) {
shortest = dist;
nearest = obj;
}
}
}
if (nearest != NULL) {
return nearest;
} else {
return NULL;
}
}
| true |
751e0ca950017276b7b5286c0cdfc6fe569572c6 | C++ | yussgrw/Code | /20181012/1.cpp | UTF-8 | 1,375 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
typedef struct {
int last;
int num;
} s;
s a[1000000+5],b[1000000+5];
int N,p[1000000+5],q[1000000+5];
int cnt=0;
const int P = 99999997;
inline int readin() {
register int x=0;
register char c=getchar();
while(c<'0'||c>'9') {
c=getchar();
}
while(c>='0'&&c<='9') {
x=x*10+c-'0';
c=getchar();
}
return x;
}
void read() {
N=readin();
register int n;
for(n=1;n<=N;n++) {
a[n].num=readin();
a[n].last=n;
}
for(n=1;n<=N;n++) {
b[n].num=readin();
b[n].last=n;
}
}
void msort(int l, int r, bool (*_comp) (int, int)) {
if(l==r) {
return ;
} else if(r-l==1) {
if(!_comp(p[l],p[r])) {
int tmp=p[l];
p[l]=p[r];
p[r]=tmp;
cnt ++;
cnt%=P;
}
} else {
int mid=(l+r)/2;
msort(l,mid,_comp);msort(mid+1,r,_comp);
int i=l,j=mid+1,k;
for(k=l;k<=r;k++) {
if(i>mid) {
q[k]=p[j++];
} else if(j>r) {
q[k]=p[i++];
} else if(!_comp(p[i],p[j])) {
cnt += (mid-i+1);
cnt%=P;
q[k]=p[j++];
} else {
q[k]=p[i++];
}
}
for(k=l;k<=r;k++) {
p[k]=q[k];
}
}
}
bool comp(s s1, s s2) {
return s1.num<s2.num;
}
bool comp2(int i1, int i2) {
return i1<=i2;
}
int main() {
read();
sort(a+1,a+N+1,comp);
sort(b+1,b+N+1,comp);
int n;
for(n=1;n<=N;n++) {
p[a[n].last]=b[n].last;
}
msort(1,N,comp2);
printf("%d\n",cnt);
return 0;
}
| true |
82fd506e1926d9aead11cd454514cdfcfa50c3a9 | C++ | timrobot/Tachikoma-Project | /robot/tachikoma/motiongraph.h | UTF-8 | 6,484 | 3.328125 | 3 | [
"MIT"
] | permissive | /*
* File: motiongraph.h
* ------------------
* MotionGraph.cpp is based on Standford's opensource
* graph.c by Marty Stepp
*/
#ifndef _motiongraph_h
#define _motiongraph_h
#include <string>
#include "graph.h"
#include "grid.h"
#include "observable.h"
#include "set.h"
/*
* Forward declarations of Vertex/Edge structures so that they can refer
* to each other mutually.
*/
struct Vertex;
struct Edge;
/*
* Canonical Vertex (Node) structure implementation needed by Graph class template.
* Each Vertex structure represents a single vertex in the graph.
*/
struct Vertex : public Observable {
public:
std::string name; // required by Stanford Graph; vertex's name
Set<Edge*> arcs; // edges outbound from this vertex; to neighbors
Set<Edge*>& edges; // alias of arcs; preferred name
/*
* The following three fields are 'supplementary data' inside each vertex.
* You can use them in your path-searching algorithms to store various
* information related to the vertex
*/
double cost; // cost to reach this vertex (initially 0; you can set this)
double& weight; // alias of cost; they are the same field
bool visited; // whether this vertex has been visited before (initally false; you can set this)
Vertex* previous; // vertex that comes before this one (initially NULL; you can set this)
/*
* The following pointer can point to any extra data needed by the vertex.
* This field is generally not necessary and can be ignored.
*/
void* extraData;
/*
* Constructs a vertex with the given name.
*/
Vertex(const std::string& name = "");
/*
* Copy constructor (rule of three).
*/
Vertex(const Vertex& other);
/*
* Frees up any memory dynamically allocated by this vertex.
*/
~Vertex();
/*
* Wipes the supplementary data of this vertex back to its initial state.
* Specifically, sets cost to 0, visited to false, and previous to NULL.
*/
void resetData();
/*
* Returns a string representation of this vertex for debugging, such as
* "Vertex{name=r13c42, cost=11, visited=true, previous=r12c41, neighbors={r12c41, r12c43}}".
*/
std::string toString() const;
/*
* Copy assignment operator (rule of three).
*/
Vertex& operator =(const Vertex& other);
/*
* Move assignment operator (rule of three).
*/
Vertex& operator =(Vertex&& other);
private:
};
/*
* You can refer to a Vertex as a Node if you prefer.
*/
#define Node Vertex
/*
* Canonical Edge (Arc) structure implementation needed by Graph class template.
* Each Edge structure represents a single edge in the graph.
*/
struct Edge {
public:
Vertex* start; // edge's starting vertex (required by Graph)
Vertex* finish; // edge's ending vertex (required by Graph)
Vertex*& end; // alias of finish; they are the same field
double cost; // edge weight (required by Graph)
double& weight; // alias of cost; they are the same field
bool visited; // whether this edge has been visited before (initally false; you can set this)
/*
* The following pointer can point to any extra data needed by the vertex.
* This field is generally not necessary and can be ignored.
*/
void* extraData;
/*
* Constructs a new edge between the given start/end vertices with
* the given cost.
*/
Edge(Vertex* start = NULL, Vertex* finish = NULL, double cost = 0.0);
/*
* Frees up any memory dynamically allocated by this edge.
*/
~Edge();
/*
* Wipes the supplementary data of this vertex back to its initial state.
* Specifically, sets visited to false.
*/
void resetData();
/*
* Returns a string representation of this edge for debugging, such as
* "Arc{start=r12c42, finish=r12c41, cost=0.75}".
*/
std::string toString() const;
/*
* Copy assignment operator (rule of three).
*/
Edge& operator =(const Edge& other);
/*
* Move assignment operator (rule of three).
*/
Edge& operator =(Edge&& other);
};
#define Arc Edge
class MotionGraph : public Graph<Vertex, Edge> {
public:
/*
* Newly added behavior in MotionGraph.
*/
MotionGraph();
void clearArcs();
void clearEdges();
bool containsArc(Vertex* v1, Vertex* v2) const;
bool containsArc(const std::string& v1, const std::string& v2) const;
bool containsArc(Edge* edge) const;
bool containsEdge(Vertex* v1, Vertex* v2) const;
bool containsEdge(const std::string& v1, const std::string& v2) const;
bool containsEdge(Edge* edge) const;
bool containsNode(const std::string& name) const;
bool containsNode(Vertex* v) const;
bool containsVertex(const std::string& name) const;
bool containsVertex(Vertex* v) const;
Edge* getArc(Vertex* v1, Vertex* v2) const;
Edge* getArc(const std::string& v1, const std::string& v2) const;
Edge* getEdge(Vertex* v1, Vertex* v2) const;
Edge* getEdge(const std::string& v1, const std::string& v2) const;
Edge* getInverseArc(Edge* edge) const;
Edge* getInverseEdge(Edge* edge) const;
bool isNeighbor(const std::string& v1, const std::string& v2) const;
bool isNeighbor(Vertex* v1, Vertex* v2) const;
void resetData();
void setResetEnabled(bool enabled);
virtual void scanArcData(TokenScanner& scanner, Edge* edge, Edge* inverse);
virtual void writeArcData(std::ostream& out, Edge* edge) const;
Edge* addEdge(const std::string& v1, const std::string& v2, double cost = 0.0, bool directed = true);
Edge* addEdge(Vertex* v1, Vertex* v2, double cost = 0.0, bool directed = true);
Edge* addEdge(Edge* e, bool directed = true);
Vertex* addVertex(const std::string& name);
Vertex* addVertex(Vertex* v);
const Set<Edge*>& getEdgeSet() const;
const Set<Edge*>& getEdgeSet(Vertex* v) const;
const Set<Edge*>& getEdgeSet(const std::string& v) const;
Vertex* getVertex(const std::string& name) const;
const Set<Vertex*>& getVertexSet() const;
void removeEdge(const std::string& v1, const std::string& v2, bool directed = true);
void removeEdge(Vertex* v1, Vertex* v2, bool directed = true);
void removeEdge(Edge* e, bool directed = true);
void removeVertex(const std::string& name);
void removeVertex(Vertex* v);
private:
bool m_resetEnabled;
};
#endif | true |
d074da97bd540cb5ebaad108502ee2d4cd9bb719 | C++ | hexu1985/cpp_book_code | /boost.intro/variant/demo6.cpp | UTF-8 | 1,434 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "boost/variant.hpp"
class stream_output_visitor :
public boost::static_visitor<void> {
std::ostream& os_;
public:
stream_output_visitor(std::ostream& os) : os_(os) {}
template <typename T> void operator()(T& t) const {
os_ << t << '\n';
}
};
class lexicographical_visitor :
public boost::static_visitor<bool> {
public:
template <typename LHS,typename RHS>
bool operator()(const LHS& lhs,const RHS& rhs) const {
return get_string(lhs)<get_string(rhs);
}
private:
template <typename T> static std::string
get_string(const T& t) {
std::ostringstream s;
s << t;
return s.str();
}
static const std::string& get_string(const std::string& s) {
return s;
}
};
int main() {
boost::variant<int,std::string> var1="100";
boost::variant<double> var2=99.99;
std::cout << "var1<var2: " <<
boost::apply_visitor(
lexicographical_visitor(),var1,var2) << '\n';
typedef std::vector<
boost::variant<int,std::string,double> > vec_type;
vec_type vec;
vec.push_back("Hello");
vec.push_back(12);
vec.push_back(1.12);
vec.push_back("0");
stream_output_visitor sv(std::cout);
std::for_each(vec.begin(),vec.end(),sv);
lexicographical_visitor lv;
std::sort(vec.begin(),vec.end(),boost::apply_visitor(lv));
std::cout << '\n';
std::for_each(vec.begin(),vec.end(),sv);
};
| true |
a70dee233a9b544120150a9989852b62ac033970 | C++ | merskip/kek-lang | /Source/main.cpp | UTF-8 | 2,946 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <fstream>
#include "Lexer/Lexer.h"
#include "Utilities/ParsingException.h"
#include "Utilities/Console.h"
#include "ParserAST/NodeASTParser.h"
#include "Printer/ASTPrinter.h"
#include "Utilities/Arguments.h"
#include "Compiler/LLVMCompiler.h"
#include "BuiltinTypes.h"
#include "Compiler/BackendCompiler.h"
#include <llvm/Support/raw_ostream.h>
void parse(const std::string &text, Console *console, const std::optional<std::string> &filename);
void compileFile(const std::string &filename);
void runConsole();
std::string replaceExtension(const std::string &filename, const std::string &newExtension);
int main(int argc, char *argv[]) {
arguments.initialize(argc, argv);
auto inputFile = arguments.getOption("-i");
if (inputFile.has_value())
compileFile(*inputFile);
else
runConsole();
return 0;
}
void compileFile(const std::string &filename) {
std::ifstream file(filename);
std::stringstream fileStream;
fileStream << file.rdbuf();
std::string fileContent = fileStream.str();
std::string outputFilename = replaceExtension(filename, "o");
parse(fileContent, nullptr, outputFilename);
}
void runConsole() {
auto console = Console("kek-lang> ");
console.begin([&](const std::string &inputText) {
try {
parse(inputText, &console, std::nullopt);
}
catch (ParsingException &e) {
console.printMarker(e.getOffset());
Console::printMessage("Error: " + e.getMessage());
}
});
}
void parse(const std::string &text, Console *console, const std::optional<std::string> &filename) {
Lexer tokenizer(text, builtin::operators);
auto tokens = tokenizer.getTokens();
if (arguments.isFlag("-dump-tokens")) {
for (const auto &token : tokens) {
if (console != nullptr)
console->printMarker(token.offset, token.text.size());
std::cout << "Token { " << token << " }" << std::endl;
}
}
NodeASTParser parser(tokens);
auto rootNode = parser.parse();
if (arguments.isFlag("-dump-ast")) {
ASTPrinter printer;
std::cout << printer.print(rootNode.get()) << std::endl;
}
LLVMCompiler llvmCompiler("kek-lang");
llvmCompiler.compile(rootNode.get());
auto module = llvmCompiler.getModule();
if (arguments.isFlag("-dump-llvm-ir"))
module->print(llvm::outs(), nullptr);
BackendCompiler backendCompiler;
backendCompiler.run(llvmCompiler.getModule(), filename.value_or("kek-console.o"));
}
std::string replaceExtension(const std::string &filename, const std::string &newExtension) {
std::string::size_type indexOfDot = filename.find_last_of('.');
std::string basename;
if (indexOfDot != std::string::npos) {
basename = filename.substr(0, indexOfDot);
} else {
basename = filename;
}
return basename + "." + newExtension;
}
| true |
68d79063d7234b014dc4033fca0cc6a7f310d06c | C++ | ming037/algorithm | /baekjoon/백준 2163번 초콜릿자르기.cpp | UTF-8 | 425 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
int dp[90001];
int solve(int num)
{
if (num == 1) return 0;
if (num == 2) return 1;
int &val = dp[num];
if (val != -1) return val;
val = 1+ solve(num / 2) + solve(num - num / 2);
return val;
}
int main()
{
int n, m;
scanf("%d %d", &n, &m);
memset(dp, -1, sizeof(dp));
printf("%d", solve(n*m));
}
| true |
b077eb7c12a821fdcdf6b479a472d28daed91310 | C++ | wingkitlee0/nbody-opengl | /src_c++2/window.cpp | UTF-8 | 2,242 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "log.h"
#include "window.hpp"
bool init_opengl() {
// Initialize Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Check for error
if(glGetError() != GL_NO_ERROR) {
return false;
}
//Initialize Modelview Matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Check for error
if(glGetError() != GL_NO_ERROR) {
return false;
}
// Initialize clear color
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Check for error
if(glGetError() != GL_NO_ERROR) {
return false;
}
return true;
}
Window::Window() {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
log_error("SDL could not initialize! SDL_Error: %s", SDL_GetError());
//return NULL;
}
// Use OpenGL 2.1
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
this->window = SDL_CreateWindow(
"NBody", // title
SDL_WINDOWPOS_UNDEFINED, // x
SDL_WINDOWPOS_UNDEFINED, // y
WINDOW_WIDTH, // w
WINDOW_HEIGHT, // h
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN // flags
);
if (this->window == NULL) {
log_error("Window could not be created! SDL_Error: %s", SDL_GetError());
}
this->context = SDL_GL_CreateContext(this->window);
if(this->context == NULL) {
log_error("OpenGL context could not be created! SDL_Error: %s", SDL_GetError());
}
if (SDL_GL_SetSwapInterval(1) < 0) {
log_warn("Unable to set VSync! SDL Error: %s", SDL_GetError());
}
if (!init_opengl()) {
log_error("Unable to initialize OpenGL!");
}
}
Window::~Window() {
if (this->context != NULL) {
SDL_GL_DeleteContext(this->context);
this->context = NULL;
}
if (this->window != NULL) {
SDL_DestroyWindow(this->window);
this->window = NULL;
}
SDL_Quit();
}
void Window::Window_update() {
//Update screen
SDL_GL_SwapWindow(this->window);
} | true |
f042d69e3108a99f01e63505776b975614dcf09b | C++ | sailfishos-mirror/kconfigwidgets | /src/kcommandbar.h | UTF-8 | 2,309 | 2.53125 | 3 | [] | no_license | /*
* SPDX-FileCopyrightText: 2021 Waqar Ahmed <waqar.17a@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.0-or-later
*/
#ifndef KCOMMANDBAR_H
#define KCOMMANDBAR_H
#include "kconfigwidgets_export.h"
#include <QMenu>
#include <memory>
/**
* @class KCommandBar kcommandbar.h KCommandBar
*
* @short A hud style menu which allows listing and executing actions
*
* KCommandBar takes as input a list of QActions and then shows them
* in a "list-like-view" with a filter line edit. This allows quickly
* executing an action.
*
* Usage is simple. Just create a KCommandBar instance when you need it
* and throw it away once the user is done with it. You can store it as
* a class member as well but there is little benefit in that. Example:
*
* @code
* void slotOpenCommandBar()
* {
* // `this` is important, you must pass a parent widget
* // here. Ideally it will be your mainWindow
* KCommandBar bar(this);
*
* // Load actions into the command bar
* // These actions can be from your menus / toolbars etc
* QList<ActionGroup> actionGroups = ...;
* bar.setActions(actionGroups);
*
* // Show
* bar.exec();
* }
* @endcode
*
* @since 5.83
* @author Waqar Ahmed <waqar.17a@gmail.com>
*/
class KCONFIGWIDGETS_EXPORT KCommandBar : public QMenu
{
Q_OBJECT
public:
/**
* Represents a list of action that belong to the same group.
* For example:
* - All actions under the menu "File" or "Tool"
*/
struct ActionGroup {
QString name;
QList<QAction *> actions;
};
/**
* constructor
*
* @p parent is used to determine position and size of the
* command bar. It *must* not be @c nullptr.
*/
explicit KCommandBar(QWidget *parent);
~KCommandBar() override;
/**
* @p actions is a list of {GroupName, QAction}. Group name can be the name
* of the component/menu where a QAction lives, for example in a menu "File -> Open File",
* "File" should be the GroupName.
*/
void setActions(const QList<ActionGroup> &actions);
public Q_SLOTS:
void show();
protected:
bool eventFilter(QObject *obj, QEvent *event) override;
private:
std::unique_ptr<class KCommandBarPrivate> const d;
};
Q_DECLARE_TYPEINFO(KCommandBar::ActionGroup, Q_RELOCATABLE_TYPE);
#endif
| true |
f9f3ffc5ea22460e90c04214aac6c1604c481afb | C++ | GugaDozero/observer-exercicio | /feedobserver.cpp | UTF-8 | 508 | 2.71875 | 3 | [] | no_license | #include "feedobserver.h"
#include "subject.h"
#include "feedsubject.h"
#include <iostream>
using std::cout;
using std::endl;
FeedObserver::FeedObserver() :
m_state()
{
}
FeedObserver::~FeedObserver()
{
}
void FeedObserver::update(Subject *subject, string feedName = "")
{
FeedSubject *observable = dynamic_cast<FeedSubject *>(subject);
cout << subject << " " << this << " " << observable->state() << " " << feedName << endl;
m_state = observable->state();
} | true |
e38e363a3a481f5a8335ea2cf156746560b670e6 | C++ | tetat/Codeforces-Problems-Sol | /Difficulty900/160A.cpp | UTF-8 | 512 | 2.765625 | 3 | [] | no_license | /// Problem Name: Twins
/// Problem Link: https://codeforces.com/problemset/problem/160/A
#include <bits/stdc++.h>
using namespace std;
int A, B;
int a[101];
int b[101];
int main()
{
int n, sum = 0;
scanf("%d", &n);
for (int i = 0;i < n;i++){
scanf("%d", &a[i]);
sum += a[i];
}
sort(a, a+n);
int ans = 0;
int S = 0;
for (int i = n-1;i >= 0;i--){
sum -= a[i];
S += a[i];
ans++;
if (sum < S)break;
}
printf("%d\n", ans);
return 0;
}
| true |
28877f8b5fd2b27eacaa2f218fc610eb9525c5fc | C++ | Raylands/Algorithms-and-datastructures-in-object-oriented-programming | /Midterm Exercise/Moving Average/Moving Average.cpp | UTF-8 | 4,318 | 2.875 | 3 | [] | no_license | #include "Global.hpp"
#include "Vector_implementation.hpp"
#include "Deque_implementation.hpp"
using namespace std;
extern deque<float> Deque::file_data;
extern vector<float> Vector::file_data;
int main(int argc, char** argv) {
START:
string file_location;
cout << "File name of input file (leave empty for data.txt): ";
std::getline(std::cin, file_location);
if (file_location.empty()) file_location = "data.txt";
cout << "What method should be used? (0) Performance test, (1) Use Vetor, (2) Use Deque: ";
string tmp;
std::getline(std::cin, tmp);
int using_method = stoi(tmp);
int filter_site_input = 0;
if (using_method != 0) {
cout << "What should be the filter size? (leave empty for whole dataset): ";
string tmp2;
std::getline(std::cin, tmp2);
if (!tmp2.empty())
filter_site_input = stoi(tmp2);
}
while (true)
{
if (GetAsyncKeyState(VK_SPACE) & 0x8000) break;
if (GetAsyncKeyState(VK_BACK) & 0x8000)
{
system("cls");
last_update = 0;
goto START;
}
if (!check_change(file_location)) continue;
switch (using_method)
{
case 0: // Performance test
{
cout << "First measuring Vector..." << endl << endl;
auto measure_start = chrono::high_resolution_clock::now();
if (!Vector::read_data(file_location, true, true)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
auto vector_measure_sort_steps = (chrono::duration<double>(chrono::high_resolution_clock::now() - measure_start)).count();
measure_start = chrono::high_resolution_clock::now();
if (!Vector::read_data(file_location, true, false)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
auto vector_measure_sort = (chrono::duration<double>(chrono::high_resolution_clock::now() - measure_start)).count();
measure_start = chrono::high_resolution_clock::now();
if (!Vector::read_data(file_location, false, true)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
auto vector_measure_steps = (chrono::duration<double>(chrono::high_resolution_clock::now() - measure_start)).count();
measure_start = chrono::high_resolution_clock::now();
if (!Vector::read_data(file_location, false, false)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
auto vector_measure_raw = (chrono::duration<double>(chrono::high_resolution_clock::now() - measure_start)).count();
cout << "\n\nNow measuring Deque..." << endl << endl;
measure_start = chrono::high_resolution_clock::now();
if (!Deque::read_data(file_location, true)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
auto deque_measure_steps = (chrono::duration<double>(chrono::high_resolution_clock::now() - measure_start)).count();
measure_start = chrono::high_resolution_clock::now();
if (!Deque::read_data(file_location, false)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
auto deque_measure_raw = (chrono::duration<double>(chrono::high_resolution_clock::now() - measure_start)).count();
cout << "\nResults: " << endl;
cout << "Vector with sorting and single step calculation: " << vector_measure_sort_steps << " seconds" << endl;
cout << "Vector with sorting: " << vector_measure_sort << " seconds" << endl;
cout << "Vector with single step calculation: " << vector_measure_steps << " seconds" << endl;
cout << "Vector no sort and end calculation: " << vector_measure_raw << " seconds" << endl << endl;
cout << "Deque with single step calculation: " << deque_measure_steps << " seconds" << endl;
cout << "Deque only end calculation: " << deque_measure_raw << " seconds" << endl;
}
break;
case 1: // Using Vector
{
if (!Vector::read_data(file_location, false, false, filter_site_input)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
}
break;
case 2: // Using Deque
{
if (!Deque::read_data(file_location, false, filter_site_input)) {
cout << "\nFile not found!" << endl;
return EXIT_FAILURE;
}
}
break;
default:
cout << "Invalid input! Terminating..." << endl;
return EXIT_FAILURE;
break;
}
cout << "\nJust update the file to update the data.\n\nPress BACK to select a new dataset or press SPACE to exit!\n";
}
return EXIT_SUCCESS;
} | true |
6195252297097d3c79308d82120d6cc0a96ee78b | C++ | YaoQian670/c_plus_plus_practice | /ListNode/ListNode/Source.cpp | UTF-8 | 2,064 | 3.59375 | 4 | [] | no_license |
#include <iostream>
#include <set>
using namespace std;
template <class T>
class ListNode {
public:
ListNode(T t) {
value = t;
next = NULL;
}
T value;
ListNode<T>* next;
};
template <class T>
void iterateList(ListNode<T>* head) {
ListNode<T>* tmp = head;
while (tmp != NULL) {
cout << tmp->value << "\t";
tmp = tmp->next;
}
cout << endl;
}
template <class T>
ListNode<T>* reverseList(ListNode<T>* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode<T>* tmp1 = head;
ListNode<T>* tmp2 = head->next;
head->next = NULL;
while (tmp2) {
ListNode<T>* tmp3 = tmp2->next;
tmp2->next = tmp1;
tmp1 = tmp2;
tmp2 = tmp3;
}
return tmp1;
}
template <class T>
bool ifCircle(ListNode<T>* head) {
set<ListNode<T>*> nodeAddSet;
ListNode<T>* tmp = head;
while (tmp != NULL) {
if (nodeAddSet.insert(tmp).second)
tmp = tmp->next;
else
return true;
}
return false;
}
template <class T>
ListNode<T>* pairReverse(ListNode<T>* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode<T>* tmp1 = head, * tmp2 = head->next, * tmp3 = head->next->next;
ListNode<T>* reversedListHead = tmp2;
while (1) {
tmp2->next = tmp1;
if (tmp3 == NULL || tmp3->next == NULL) {
tmp1->next = tmp3;
break;
}
tmp1->next = tmp3->next;
tmp1 = tmp3;
tmp2 = tmp3->next;
tmp3 = tmp2->next;
}
return reversedListHead;
}
int main() {
ListNode<int>* node1 = new ListNode<int>(1);
ListNode<int>* node2 = new ListNode<int>(2);
ListNode<int>* node3 = new ListNode<int>(3);
ListNode<int>* node4 = new ListNode<int>(4);
ListNode<int>* node5 = new ListNode<int>(5);
ListNode<int>* node6 = new ListNode<int>(6);
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
node5->next = node6;
node6->next = NULL;
iterateList(node1);
/*ListNode<int>* reversedListHead = reverseList(node1);
iterateList(reversedListHead);*/
/*node5->next = node1;
if (ifCircle(node1))
cout << "circle" << endl;
else
cout << "not circle" << endl;*/
iterateList(pairReverse(node1));
} | true |
d490439548a3fda2b1f3e1251fc25d420ef026b8 | C++ | RexCYJ/EECS2040-Data_Structure | /HW5/ShortestPath/ShortestPath.cpp | UTF-8 | 5,281 | 3.015625 | 3 | [] | no_license | #include "ShortestPath.h"
#include <deque>
#define INF 999999999
using std::deque;
Graph::Graph(int vertice = 0): n(vertice) {}
void Graph::Dijkstra(const int v)
{
int *s = new int [n];
int *dist = new int [n];
for (int i = 0; i < n; i++) {
s[i] = false;
dist[i] = edge[v][i];
}
int u; // the vertex that is not in S
int w; // u's pre-vertex
int mindist;
deque<int> *path = new deque<int> [n];
path[v].push_back(v);
// Column header
cout << " Iter vertex | ";
for (int i = 0; i < n; i++)
cout << std::setw(5) << "[" << i << ']';
cout << endl;
int *Setv = new int [n], setv;
for (int i = 0; i < n; i++) Setv[i] = -1;
Setv[0] = v;
s[v] = true;
dist[v] = 0;
for (int i = 0; i < n - 1; i++) { // n - 1 shortest path from v
u = v; mindist = INF;
for (int j = 0; Setv[j] != -1; j++) { // search the vertice in s
// if (s[j]) { // from the vertex in set s
setv = Setv[j];
for (int k = 0; k < n; k++) { // Check its adjacent out-edge
if (edge[setv][k] != INF && !s[k]) {
if (dist[setv] + edge[setv][k] < mindist) { // update dist
mindist = dist[setv] + edge[setv][k];
u = k; w = setv;
}
if (dist[k] > dist[setv] + edge[setv][k])
dist[k] = dist[setv] + edge[setv][k];
}
} // for 3
// }
} // for 2
if (u == v) break;
s[u] = true;
dist[u] = mindist;
path[u] = path[w];
path[u].push_back(u);
Setv[i + 1] = u;
// Output row
cout << '>' << std::setw(5) << i << std::setw(8) << u << " | ";
for (int j = 0; j < n; j++) {
if (dist[j] >= INF) cout << std::setw(7) << "-";
else cout << std::setw(7) << dist[j];
}
cout << endl;
} // for 1
cout << "\n Path length vertice on the path\n";
for (int i = 0; i < n; i++) {
cout << "<"<< v << ',' << i << ">";
if (dist[i] == INF) cout << std::setw(9) << "-" << " ";
else cout << std::setw(9) << dist[i] << " ";
while (!path[i].empty()) {
cout << std::setw(3) << path[i].front();
path[i].pop_front();
}
cout << endl;
}
delete [] path;
delete [] dist;
delete [] s;
}
void Graph::BellmanFord(const int v)
{
int *dist = new int [n];
bool *visited = new bool [n];
for (int i = 0; i < n; i++) {
dist[i] = edge[v][i];
if (edge[v][i] == INF) visited[i] = false;
else visited[i] = true;
}
dist[v] = 0;
visited[v] = true;
cout << std::setw(15) << "dist\n" << " k | ";
for (int i = 0; i < n; i++)
cout << " "<< '[' << i << ']';
cout << endl;
for (int k = 2; k < n; k++) { // dist(2)[] ~ dist(n-1)[]
cout << std::setw(4) << k << ' ' << '|';
for (int u = 0; u < n; u++) {
if (u != v) // for all u not v
for (int i = 0; i < n; i++)
if (visited[i] && edge[i][u] != INF) {
if (dist[u] > dist[i] + edge[i][u])
dist[u] = dist[i] + edge[i][u];
visited[u] = true;
}
if (dist[u] == INF) cout << std::setw(6) << "-";
else cout << std::setw(6) << dist[u];
}
cout << endl;
}
delete [] dist;
delete [] visited;
}
void Graph::Floyd()
{
int **a = new int* [n];
int **kay = new int* [n];
for (int i = 0; i < n; i++) {
a[i] = new int [n];
kay[i] = new int [n];
for (int j = 0; j < n; j++) {
if (i == j) a[i][j] = 0;
else a[i][j] = edge[i][j];
kay[i][j] = -1;
}
}
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (a[i][k] != INF && a[k][j] != INF && (a[i][j] > (a[i][k] + a[k][j])))
{kay[i][j] = k; a[i][j] = a[i][k] + a[k][j];}
cout << "a[i][j]" << std::setw(4*n+15) << "kay[i][j]" << endl;
cout << " j \\ i";
for (int i = 0; i < n; i++)
cout << std::setw(4) << i;
cout << " ";
cout << " j \\ i";
for (int i = 0; i < n; i++)
cout << std::setw(4) << i;
cout << endl;
for (int i = 0; i < n; i++) {
cout << std::setw(4) << i << " | ";
for (int j = 0; j < n; j++)
if (a[i][j] == INF) cout << std::setw(4) << " ";
else if (i == j) cout << std::setw(4) << 0;
else cout << std::setw(4) << a[i][j];
cout << " ";
cout << std::setw(4) << i << " | ";
for (int j = 0; j < n; j++)
if (a[i][j] == INF) cout << std::setw(4) << " ";
else if (kay[i][j] == -1) cout << std::setw(4) << "-";
else cout << std::setw(4) << kay[i][j];
cout << endl;
}
for (int i = 0; i < n; i++) {
delete [] a[i];
delete [] kay[i];
}
delete [] a;
delete [] kay;
}
istream& operator>>(istream& is, Graph& g)
{
if (g.n != 0) {
for (int i = 0; i < g.n; i++)
delete [] g.edge[i];
delete [] g.edge;
}
int n;
is >> n;
g.n = n;
g.edge = new int* [n];
for (int i = 0; i < n; i++) { // initialization
g.edge[i] = new int [n];
for (int j = 0; j < n; j++)
g.edge[i][j] = INF;
}
int u, v, weight;
is >> u >> v >> weight;
while (u != -1) {
if (u > n || v > n) throw "Wrong index";
g.edge[u][v] = weight;
is >> u >> v >> weight;
}
return is;
}
ostream& operator<<(ostream& os, Graph& g)
{
os << " ";
for (int i = 0; i < g.n; i++)
os << std::setw(5) << i;
os << endl;
for (int i = 0; i < g.n; i++) {
os << std::internal << std::setw(5) << i << ' ';
for (int j = 0; j < g.n; j++)
if (g.edge[i][j] == INF)
os << std::right << std::setw(5) << "-";
else
os << std::right << std::setw(5) << g.edge[i][j];
os << endl;
}
return os;
} | true |
201e5677fb60683f96893caa842fad062c3e3b37 | C++ | 892944774/C-plus-plus | /202010-14/202010-14/202010-14.cpp | GB18030 | 2,596 | 3.703125 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#if 0
class Test
{
public:
Test()
{
cout << "Test():" << this << endl;
}
~Test()
{
cout << "~test():" << this << endl;
}
private:
int _t;
};
void TestFunc()
{
//ҪڶϿһڴռ,Test͵Ķ
Test* pt = (Test*)malloc(sizeof(Test));
free(pt);
}
int main()
{
TestFunc();
return 0;
}
#endif
#if 0
int main()
{
//ռ
//뵥ռ
int* p1 = new int;
//뵥Ϳռ䲢ʼ
int* p2 = new int(10);
//һĿռ
int* p3 = new int[10];
//һĿռгʼ
int* p4 = new int[10]{1,2,3,4,5,6,7,8,9,0};
//ͷſռ
//ͷŵ͵Ŀռ
delete p1;
delete p2;
//ͷ͵Ŀռ
delete[] p3;
delete[] p4;
return 0;
}
#endif
#if 0
class Test
{
public:
Test()
{
cout << "Test():" << this << endl;
}
~Test()
{
cout << "~test():" << this << endl;
}
private:
int _t;
};
int main()
{
Test* pt1 = new Test;
Test* pt2 = new Test[10];
delete pt1;
delete[] pt2;
return 0;
}
#endif
#if 0
class Test
{
public:
Test(int t)
:_t(t)
{
cout << "Test():" << this << endl;
}
~Test()
{
cout << "~test():" << this << endl;
}
private:
int _t;
};
int main()
{
Test* pt1 = new Test(10);
Test* pt2 = new Test(20);
delete pt1;
delete pt2;
return 0;
}
#endif
#if 0
class Test
{
public:
Test(int t = 10)
:_t(t)
{
cout << "Test():" << this << endl;
}
~Test()
{
cout << "~test():" << this << endl;
}
private:
int _t;
};
int main()
{
//ע⣺ĿռʱǾεĻȫȱʡĹ캯
Test* pt1 = new Test[10];
delete pt1;
return 0;
}
#endif
class Test
{
public:
Test(int t = 10)
:_t(t)
{
p = new int;
cout << "Test():" << this << endl;
}
~Test()
{
delete p;
cout << "~test():" << this << endl;
}
private:
int _t;
int* p;
};
void TestFunc()
{
//mallocĶdeleteͷ
//ΪmallocIJһTest͵ĶTestʹСͬһοռ
//ͷŸÿռʱʹdeleteͷţΪڴл
//ҪԶpָָռеݽͷţmallocĿռûе
//p1гʼp1ָĿռеֵ
//Test* p1 = (Test*)malloc(sizeof(Test));
//delete p1;//
}
int main()
{
TestFunc();
return 0;
} | true |
921a987d32a1d23a9de55903144e426e50103b08 | C++ | kees-jan/cpp11training | /cpp11training/cpp11training/3.class_design.cpp | UTF-8 | 1,318 | 3.046875 | 3 | [] | no_license | #include "stdafx.h"
#include <gtest/gtest.h>
#include "class_design/Thing.h"
#include "class_design/Instrument.h"
#include "class_design/Piano.h"
#include "class_design/Vehicle.h"
#include "class_design/MyBike.h"
// TODO:
// visit Thing.h, and rename Thing::size_in_cm to size_in_m.
// The code still compiles. That's bad. Make it so that inheritors
// don't compile by accident.
//
// GOAL: learn to conciously design a class for inheritance
//
// HINT: use the `override` keyword
TEST(class_design, DISABLED_adding_constructors_should_be_trivial)
{
// TODO: add a constructor Thing(std::string)
// make Piano and MyBike inherit this constructor with the least amount of code
// and replication
//
// GOAL: make it trivial to add a base class constructors like Thing::Thing(std::string name)
//
// HINT: `using` is the key
Piano p; // { "my piano" };
MyBike b; // { "my bike" };
EXPECT_EQ("making music", p.purpose());
EXPECT_EQ("my piano", p.name());
EXPECT_EQ("transporting", b.purpose());
EXPECT_NEAR(60.0, b.size_in_cm(), 0.00001);
}
// TODO: alter the needed classes to make it impossible to copy things
// GOAL: learn to use `delete` qualifier
TEST(class_design, DISABLED_synthesized_functions)
{
Piano p; // { "" };
auto q = p; // should not compile.
}
| true |
92cd8eef49c804ecb6dd1ec1b111b0a4d420c35c | C++ | WinstonLy/MyMazeMap | /MazePerson.cpp | GB18030 | 4,452 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <Windows.h>
#include "MazePerson.h"
#include "MazeMap.h"
using namespace std;
int CMazePerson::count = -1;
//******* ĬϹ캯ʼԳʼλ *******//
CMazePerson::CMazePerson():m_cPerson('T'),m_cDirection('W')
{
// ĬԹijʼλ
m_iCurrentPositionX = 0;
m_iCurrentPositionY = 15;
m_iPreviousPositionX = 0;
m_iPreviousPositionY = 15;
m_iSpeed = NORMAL;
}
//******* *******//
CMazePerson::~CMazePerson()
{
}
//******* Թ˵ *******//
//******* _person:˵ַ *******//
//******* _direction:˵ǰ *******//
//******* _speed:ƶٶ *******//
void CMazePerson::SetPersonAttr(char _person, char _direction, int _speed)
{
m_cPerson = _person;
m_cDirection = _direction;
m_iSpeed = _speed;
}
//******* õǰλõĺᡢ *******//
void CMazePerson::SetCurrentPosition(int _x, int _y)
{
m_iCurrentPositionX = _x;
m_iCurrentPositionY = _y;
Gotoxy(m_iCurrentPositionX, m_iCurrentPositionY);
cout << m_cPerson;
Sleep(1000);
}
//******* ǰһλõĺᡢ *******//
void CMazePerson::SetPreviousPosition(int _x, int _y)
{
m_iPreviousPositionX = _x;
m_iPreviousPositionY = _y;
Gotoxy(0, 50);
cout << count;
Gotoxy(m_iCurrentPositionX, m_iCurrentPositionY);
count++;
if (count != 0)
{
cout << ' ';
}
Sleep(1000);
}
//******* ӡǰλõϢ *******//
void CMazePerson::GetCurrentPosition()
{
cout << "Current(" << m_iCurrentPositionX << ',' << m_iCurrentPositionY << ')' << endl;
}
//******* ӡǰһλõϢ *******//
void CMazePerson::GetPreviousPosition()
{
cout << "Previous(" << m_iPreviousPositionX << ',' << m_iPreviousPositionY << ')' << endl;
}
//******* ƶѰԹ *******//
void CMazePerson::PersonMove()
{
int tempX = 0;
int tempY = 0;
char tempDirection;
int successFlag = HI_FALSE;
while (!successFlag)
{
// жĸƶ
tempDirection = m_cDirection;
m_cDirection = CMazeMap::CheckNext(m_iCurrentPositionX, m_iCurrentPositionY, m_cDirection);
if (m_iSpeed == NORMAL)
{
switch (m_cDirection)
{
// ƶ
case w:
if ((m_iCurrentPositionX != m_iPreviousPositionX + 1) &&(m_cDirection != f) )
{
SetPreviousPosition(m_iCurrentPositionX, m_iCurrentPositionY);
SetCurrentPosition(m_iCurrentPositionX - 1, m_iCurrentPositionY);
}
else
m_cDirection = '1';
break;
// ƶ
case s:
if ((m_iCurrentPositionX != m_iPreviousPositionX - 1) &&(m_cDirection != f))
{
SetPreviousPosition(m_iCurrentPositionX, m_iCurrentPositionY);
SetCurrentPosition(m_iCurrentPositionX + 1, m_iCurrentPositionY);
}
else
m_cDirection = '2';
break;
// ƶ
case a:
if ((m_iCurrentPositionY != m_iPreviousPositionY + 1) && (m_cDirection != f))
{
SetPreviousPosition(m_iCurrentPositionX, m_iCurrentPositionY);
SetCurrentPosition(m_iCurrentPositionX, m_iCurrentPositionY - 1);
}
else
m_cDirection = '3';
break;
// ƶ
case d:
if ((m_iCurrentPositionY != m_iPreviousPositionY - 1) &&(m_cDirection != f))
{
SetPreviousPosition(m_iCurrentPositionX, m_iCurrentPositionY);
SetCurrentPosition(m_iCurrentPositionX, m_iCurrentPositionY + 1);
}
else
m_cDirection = '4';
break;
case f:
tempX = m_iPreviousPositionX;
tempY = m_iPreviousPositionY;
SetPreviousPosition(m_iCurrentPositionX, m_iCurrentPositionY);
CMazeMap::SetMazeArray(m_iPreviousPositionX, m_iPreviousPositionY);
SetCurrentPosition(tempX, tempY);
if (tempDirection == w)
m_cDirection = '1';
if (tempDirection == s)
m_cDirection = '2';
if (tempDirection == a)
m_cDirection = '3';
if (tempDirection == d)
m_cDirection = '4';
//m_cDirection = f;
break;
//
default:
cout << "input error" << endl;
break;
}
}
// жǷҵ
successFlag = CMazeMap::Success(m_iCurrentPositionX, m_iCurrentPositionY);
if (successFlag)
{
Gotoxy(2, 50);
cout << "Success, you go out maze!" << endl;
}
}
}
//******* ƹڿ̨ʾλ *******//
void CMazePerson::Gotoxy(int _x, int _y)
{
COORD cd;
cd.X = _y;
cd.Y = _x;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cd);
};
| true |
773bf43e05def089e984045751e89886c7e44b39 | C++ | emmanuelfils435/C-C-_memory | /每日一题/糖果/糖果/Main.cpp | UTF-8 | 679 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<algorithm>
using namespace std;
#if 0
int main()
{
int x1, x2, x3,x4;
cin >> x1 >> x2 >> x3>>x4;
int a = (x1 + x3) / 2;
int b = (x2 + x4) / 2;
int c = x4 - b;
if (x1 == (a - b) && x2 == (b - c) && x3 == (a + b) && x4 == (b + c))
{
cout << a << " " << b << " " << c << endl;
return 0;
}
cout << "No" << endl;
return 0;
}
#endif
int main()
{
char *arr= {"0123456789ABCDEF"};
int m, n;
cin >> m >> n;
string s;
int k = m;
if (k < 0)
{
k = -k;
}
while (k)
{
s += arr[k%n];
k /= n;
}
reverse(s.begin(), s.end());
if (m < 0)
{
cout <<"-"<<s << endl;
return 0;
}
cout << s << endl;
return 0;
} | true |
b797b8c10f4fec6ca136f4f52dab24d80475db4c | C++ | elissandro13/Problems-Solved | /Roteiros Ufmg/Roteiro 3/MEGADAMA.cpp | UTF-8 | 1,880 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n,m,score = 0;
int board[21][21];
bool move(int i,int j,int dx,int dy){
if(dx >= 0 && dy >= 0 && dx < n && dy < m){
if(board[i][j] == 2 && board[dx][dy] == 0){
return true;
}
}
return false;
}
void play(int i,int j,int num){
if(move(i + 1,j + 1,i + 2,j +2)){
board[i][j] = board[i+1][j+1] = 0;
board[i+2][j+2] = 1;
play(i+2,j+2,num+1);
board[i][j] = 1;
board[i+1][j+1] = 2;
board[i+2][j+2] = 0;
}
if(move(i - 1,j - 1,i - 2,j -2)){
board[i][j] = board[i-1][j-1] = 0;
board[i-2][j-2] = 1;
play(i-2,j-2,num+1);
board[i][j] = 1;
board[i-1][j-1] = 2;
board[i-2][j-2] = 0;
}
if(move(i - 1,j + 1,i - 2,j +2)){
board[i][j] = board[i-1][j+1] = 0;
board[i-2][j+2] = 1;
play(i-2,j+2,num+1);
board[i][j] = 1;
board[i-1][j+1] = 2;
board[i-2][j+2] = 0;
}
if(move(i + 1,j - 1,i + 2,j - 2)){
board[i][j] = board[i+1][j-1] = 0;
board[i+2][j-2] = 1;
play(i+2,j-2,num+1);
board[i][j] = 1;
board[i+1][j-1] = 2;
board[i+2][j-2] = 0;
}
score = max(num,score);
}
int main(){
while(cin >> n >> m){
if(n == 0 && m == 0)
break;
int piece;
vector <pair<int,int>> v;
v.clear();
memset (board, 3, sizeof (board));
for (int i = 0; i < n; i++)
{
for (int j = i%2; j < m; j += 2)
{
cin >> piece;
board[i][j] = piece;
if(piece == 1)
v.push_back(make_pair(i,j));
}
}
for (int i = 0; i < v.size(); i++)
{
play(v[i].first,v[i].second,0);
}
cout << score << "\n";
score = 0;
}
return 0;
} | true |
5ad3f200259af244cd27b07ac36cbe53514f457e | C++ | AnthonySuper/Experimental-2D-Engine | /src/component.cpp | UTF-8 | 584 | 2.796875 | 3 | [] | no_license | #include "component.hpp"
namespace NM {
Component::Component(EntityRef entity) : parentEntity(entity) {}
Component::Component() : parentEntity(nullptr, -1) {}
Entity& Component::getEntity() {
return parentEntity.get();
}
void NullComponent::receive(NM::Message &m) {
std::cerr << "NullComponent recieved message: ";
std::cerr << m.getType() << std::endl;
}
NullComponent::operator bool() {
return false;
}
std::string NullComponent::getName() {
return "NullComponent";
}
}
| true |
192bbc44e635c117a71c98e0fee9d8619deaaaa1 | C++ | NirobNabil/LFR | /main_archived/sensorReadings.ino | UTF-8 | 491 | 2.546875 | 3 | [] | no_license |
int ir_array[6];
char sensor_s[6];
int sensor;
void readData() {
ir_array[0] = analogRead(A0);
ir_array[1] = analogRead(A1);
ir_array[2] = analogRead(A2);
ir_array[3] = analogRead(A3);
ir_array[4] = analogRead(A4);
ir_array[5] = analogRead(A5);
sensor = 0;
for( int i=0; i<6; i++ ) {
sensor += ( ir_array[i] > IRminValueWhenOnBlack ? 1 : 0 ) * ( 1 << (i+1) );
sensor_s[i] = ( ir_array[i] > IRminValueWhenOnBlack ? '1' : '0' );
}
}
| true |
1e54e5d3605c5fa437dca3bbef1f7f4d7e884c4b | C++ | brianrhall/Assembly | /Chapter_11/Program_11.2_AVR_blink/Program_11.2_AVR_blink.ino | UTF-8 | 2,134 | 2.65625 | 3 | [
"MIT"
] | permissive | // Program 11.2
// Arduino Uno Blink Program in AVR Assembly
// Copyright (c) 2017 Hall & Slonka
#define LEDPort PORTB // Arduino pin 13 is bit 5 of port B
#define LEDPort_Direction DDRB // DDRB is the port B direction register (0=input, 1=output)
#define LEDBit 5 // Constant for bit 5
#define Clock_MHz 16
#define MilliSec 1000000
#define DelayTime (uint32_t)((Clock_MHz * MilliSec / 5)) // set to any rate desired
void setup() { // same as pinMode(13, OUTPUT)
asm volatile ( // shows default parameter use instead of our defines/names
"sbi %0, %1 \n\t" // sets port and bit direction
: : "I" (_SFR_IO_ADDR(DDRB)), "I" (DDB5) // I: 6-bit positive integer constant
);
}
void loop() {
asm volatile (
" mainLoop: " // move DelayTime to registers
" mov r16, %D2 \n\t" // LSB of DelayTime
" mov r17, %C2 \n\t" // A2, B2, C2, D2 each is 8 bits
" mov r18, %B2 \n\t"
" mov r19, %A2 \n\t" // MSB of DelayTime
" mov r20, %D2 \n\t"
" mov r21, %C2 \n\t"
" mov r22, %B2 \n\t"
" mov r23, %A2 \n\t"
" sbi %[port], %[ledbit] \n\t" // set I/O bit (turn LED on)
" onLoop: "
" subi r23, 1 \n\t" // subtract constant from register
" sbci r22, 0 \n\t" // subtract with carry constant from register
" sbci r21, 0 \n\t"
" sbci r20, 0 \n\t"
" brcc onLoop \n\t" // branch if carry cleared
" cbi %[port], %[ledbit] \n\t" // clear I/O bit (turn LED off)
" offLoop:"
" subi r19, 1 \n\t"
" sbci r18, 0 \n\t"
" sbci r17, 0 \n\t"
" sbci r16, 0 \n\t"
" brcc offLoop \n\t"
: // no output variables
: [port] "n" (_SFR_IO_ADDR(LEDPort)), // input variables
[ledbit] "n" (LEDBit), // n: integer with known value
"d" (DelayTime) // d: greater than r15
: "r16","r17","r18","r19","r20","r21","r22","r23" // clobbers
);
}
| true |
314f41aa7b011108438404eac4847ac4c759b287 | C++ | stranker/BackGE | /Clase1/Triangle.cpp | UTF-8 | 416 | 2.640625 | 3 | [] | no_license | #include "Triangle.h"
Triangle::Triangle(Renderer* renderer) : Entity(renderer)
{
}
Triangle::~Triangle()
{
}
void Triangle::Draw()
{
if (shoulDispose)
{
renderer->DrawBuffer(bufferID, vtxCount);
}
}
void Triangle::SetVertices(float * vertices, int _vtxCount)
{
vertex = vertices;
vtxCount = _vtxCount;
bufferID = renderer->GenBuffer(vertex, vtxCount);
shoulDispose = true;
}
| true |
3c6b6eeb94d676facc815d0d855de5422dbd1afb | C++ | Alipashaimani/Competitive-programming | /Codeforces/336A.cpp | UTF-8 | 455 | 2.828125 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
int x, x2, y, y2;
int main(){
int a ,b; cin >> a >> b;
if((a < 0 && b > 0) || (a > 0 && b < 0)){
x = 0 ;
y = -a + b;
x2 = a + -b;
y2 = 0;
}
else{
x = 0 ;
y = a + b;
x2 = a + b;
y2 = 0;
}
if(x > x2){
swap(x,x2);
swap(y,y2);
}
return cout << x << " " << y << " " << x2 << " "<< y2 << '\n', 0;
} | true |
1a0324b72c744689669d3807a78f5ae611f507de | C++ | jzx0614/Course | /acm/Summation of Polynomials.cpp | UTF-8 | 265 | 2.609375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void){
long long num[50000];
long n;
num[0]=1;
for(long long i=1;i<50000;i++)
{
num[i]=num[i-1]+((i+1)*(i+1)*(i+1));
}
while(cin >> n)
{
cout<<num[n-1]<<endl;
}
}
| true |
c54d19278eca4b5184e276afa800b7ef16a13fa6 | C++ | Abuenameh/Canonical-Transformation-Gutzwiller-Cusimann | /complex.hpp | UTF-8 | 1,509 | 2.71875 | 3 | [] | no_license | /*
* complex.hpp
*
* Created on: Sep 11, 2014
* Author: Abuenameh
*/
#ifndef COMPLEX_HPP_
#define COMPLEX_HPP_
//#include <complex>
//using std::complex;
#include "cudacomplex.cuh"
//#ifdef __CUDACC__
//#else
//#endif
template<class T>
struct complextype {
typedef T type;
__host__ __device__ static inline type make_complex(T a, T b);
};
template<>
struct complextype<float> {
typedef singlecomplex type;
__host__ __device__ static inline type make_complex(float a, float b) {
return make_singlecomplex(a, b);
}
};
template<>
struct complextype<double> {
typedef doublecomplex type;
__host__ __device__ static inline type make_complex(double a, double b) {
return make_doublecomplex(a, b);
}
};
//template<>
//struct complextype<float> {
//#ifdef __CUDACC__
// typedef singlecomplex type;
// static inline type make_complex(float a, float b) {
// return make_singlecomplex(a, b);
// }
//#else
// typedef complex<float> type;
// static inline type make_complex(float a, float b) {
// return type(a, b);
// }
//#endif
//};
//template<>
//struct complextype<double> {
//#ifdef __CUDACC__
// typedef doublecomplex type;
// static inline type make_complex(double a, double b) {
// return make_doublecomplex(a, b);
// }
//#else
// typedef complex<double> type;
// static inline type make_complex(double a, double b) {
// return type(a, b);
// }
//#endif
//};
//template<class T>
//complex<T> operator~(const complex<T> a) {
// return conj(a);
//}
#endif /* COMPLEX_HPP_ */
| true |
e54ed9c1f96790090224c60529e78eb74283e6f8 | C++ | Liew211/nbody | /window.cpp | UTF-8 | 677 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <stdexcept>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
GLFWwindow *initializeOpenGL()
{
/* Initialize the library */
if (!glfwInit())
throw std::runtime_error("GLFW not initialized");
/* Create a windowed mode window and its OpenGL context */
GLFWwindow *window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
throw std::runtime_error("Window not created");
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK)
throw std::runtime_error("GLEW not initialized");
std::cout << glGetString(GL_VERSION) << std::endl;
return window;
} | true |
b1620e96598371577c36ef629767ca7ad0349fae | C++ | Ujwalgulhane/Data-Structure-Algorithm | /Algorithms/NumberTheory/binaryExponentiation.cpp | UTF-8 | 625 | 2.921875 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
long long binaryExponentiation(long long a,long long b){
if(b==0)
return 1;
long long c=binaryExponentiation(a,b/2);
if(b%2)
return c*c*a;
else
return c*c;
}
long long binaryExponentiationFast(long long a,long long b){
long long r=1;
while(b>0){
if(b&1)
r*=a;
a*=a;
b>>=1;
}
return r;
}
int powerModulo(int a,int b,int m){
a%=m;
int r=1;
while(b>0){
if(b&1)
r=(r*a)%m;
a=(a*a)%m;
b>>=1;
}
return r;
}
int main(){
int n;
cin>>n;
cout<<binaryExponentiationFast(5,4)<<"\n";
cout<<powerModulo(5,5,5);
// cout<<computeModulo(5,4,6);
} | true |
92e16e7ce909718e99ab040312280d9da706f1b5 | C++ | JayThakkar17/DataStructuresAndAlgorithms | /Basic/Quotent&Remainder.cpp | UTF-8 | 381 | 3.15625 | 3 | [] | no_license | #include<iostream>
int main()
{
int dividend,divisour,remainder,quotent;
std::cout<<"Enter Dividend:";
std::cin>>dividend;
std::cout<<"Enter Divisour:";
std::cin>>divisour;
quotent = dividend / divisour;
remainder = dividend % divisour;
std::cout<<"Quotent is "<<quotent<<std::endl;
std::cout<<"Remainder is "<<remainder<<std::endl;
std::cin.get();
return 0;
}
| true |
825758d913ff33fcc74421cf8215ce4a807890c6 | C++ | QuinnRong/cplusplus | /interview/03_HIKVISION/2_MidNumber.cpp | UTF-8 | 456 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define MaxOfThree(a,b,c) ((a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c)))
#define MidOfThree(a,b,c) ((a)>(b)?((b)>(c)?(b):((a)>(c)?(c):(a))):\
((a)>(c)?(a):((b)>(c)?(c):(b))))
#define MinOfThree(a,b,c) ((a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c)))
int main()
{
cout << MaxOfThree(2,3,1) << endl;
cout << MidOfThree(2,3,1) << endl;
cout << MinOfThree(2,3,1) << endl;
} | true |
62bbe412f253430b312bcab5b0a006f4b76cdad2 | C++ | Arui1/shadow | /shadow/operators/roi_pooling_op.hpp | UTF-8 | 1,022 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef SHADOW_OPERATORS_ROI_POOLING_OP_HPP
#define SHADOW_OPERATORS_ROI_POOLING_OP_HPP
#include "core/operator.hpp"
namespace Shadow {
class ROIPoolingOp : public Operator {
public:
ROIPoolingOp(const shadow::OpParam &op_param, Workspace *ws)
: Operator(op_param, ws) {
pooled_h_ = get_single_argument<int>("pooled_h", 0);
pooled_w_ = get_single_argument<int>("pooled_w", 0);
CHECK_GT(pooled_h_, 0) << "pooled_h must be > 0";
CHECK_GT(pooled_w_, 0) << "pooled_w must be > 0";
spatial_scale_ = get_single_argument<float>("spatial_scale", 1.f / 16);
}
void Forward() override;
private:
int pooled_h_, pooled_w_;
float spatial_scale_;
};
namespace Vision {
template <typename T>
void ROIPooling(const T *in_data, const VecInt &in_shape, const T *roi_data,
int num_rois, int pooled_h, int pooled_w, float spatial_scale,
T *out_data, Context *context);
} // namespace Vision
} // namespace Shadow
#endif // SHADOW_OPERATORS_ROI_POOLING_OP_HPP
| true |
3bccf5c6f1d1d77693cf888116246e0875ae3d38 | C++ | ktekchan/Summer | /HackerRank/staircase.cpp | UTF-8 | 674 | 3.15625 | 3 | [] | no_license | /*-----------------------------------------------------------------------------
* Author: Khushboo Tekchandani
* Staircase problem
------------------------------------------------------------------------------
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
static void staircase(int n){
int i, j;
for (i=1; i<=n; i++){
for(j=1; j<=n-i; j++)
cout << " ";
for(j=1; j<=i; j++)
cout << "#";
cout << endl;
}
return;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin >> n;
staircase(n);
return 0;
}
| true |
7733fa25d07c1820d552439ba192b91a1baf346d | C++ | zv-proger/ol_programms | /acmp/0570.cpp | WINDOWS-1251 | 1,147 | 2.578125 | 3 | [] | no_license | /*
: (zv.proger@yandex.ru)
0570 acmp.ru
*/
#include<bits/stdc++.h>
using namespace std;
bool calc() {
char pl[1000][1000];
int l, r, t, b, n, m; cin >> n >> m;
l = m, r = 0, t = n, b = 0;
for (int i = 0; i < n; i++) {
cin >> pl[i];
for (int j = 0; j < m; j++) {
if (pl[i][j] == '.') continue;
l = min (l, j); r = max(r, j);
t = min (t, i); b = max(b, i);
}
}
if (r < l) return 0;
int a = max(max(r - l + 1, b - t + 1) - 4, 1);
for (int i = max(min(t + 2, b - a - 1), 1); i <= min(max(t + 2, b - a - 1), n - 2); i++) {
for (int j = max(min(l + 2, r - a - 1), 1); j <= min(max(l + 2, r - a - 1), m - 2); j++) {
for (int l = i; l < i + a; l++) {
for (int k = j; k < j + a; k++) {
if (pl[l][k] == '.')
goto nxt;
}
}
return 1;
nxt:;
}
}
return 0;
}
int main() {
cout << (calc() ? "SQUARE": "CIRCLE");
} | true |
7685d3c9c2e0ed14be2d89e6e44fe8be0ca1b40d | C++ | uwe-creative-technology/generative_systems | /session_1_visual_expression/activeDrawing/src/ofApp.cpp | UTF-8 | 2,846 | 3.140625 | 3 | [] | no_license | /*
Project Title: Active Drawing
Description:
©Daniel Buzzo 2020
dan@buzzo.com
http://buzzo.com
https://github.com/danbz
adapted from reas and fry 'processing' acive drawing
*/
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
numLines = 500;
currentLine = 0;
for (int i=0; i < numLines; i++){ // make all our new movingLine objects and put into our vector of lines
movingLine newLine;
lines.push_back(newLine);
}
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
for (int i=0; i < numLines; i++){
lines[i].display();
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
// loop through lines in our lines vector each frame and set each one to the current and previous mounse position
lines[currentLine].setPosition(mouseX, mouseY, ofGetPreviousMouseX(), ofGetPreviousMouseY());
if (currentLine <numLines -1){
currentLine++;
} else { // if we have set all our 500 lines then start again at line zero
currentLine=0;
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
movingLine::movingLine(){ // constructor for our moving line class
wobble = 0.2; // how much each line will move per frame as they decay
// uncomment this start our lines at initial random positions
// int w = ofGetWidth();
// int h = ofGetHeight();
// x1 = ofRandom(w);
// y1 = ofRandom(h);
// x2 = ofRandom(w);
// y2 = ofRandom(h);
}
movingLine::~movingLine(){
// destructor for our moving line class
}
//--------------------------------------------------------------
void movingLine::display(){
x1 += ofRandom(wobble) - wobble/2;
y1 += ofRandom(wobble) - wobble/2;
x2 += ofRandom(wobble) - wobble/2;
y2 += ofRandom(wobble) - wobble/2;
ofDrawLine(x1, y1, x2, y2);
}
//--------------------------------------------------------------
void movingLine::setPosition(int x, int y, int px, int py){
x1 = x;
y1 = y;
x2 = px;
y2 = py;
}
| true |
1b10f9427fbbcde90cf05bc69f716b2a6da62ff1 | C++ | petru-d/leetcode-solutions-reboot | /problems/p1123.h | UTF-8 | 1,682 | 3.046875 | 3 | [] | no_license | #pragma once
#include "util_binary_tree.h"
#include <unordered_map>
namespace p1123
{
class Solution
{
public:
TreeNode* lcaDeepestLeaves(TreeNode* root)
{
if (!root)
return nullptr;
auto depth = build_map(root, 0);
return search(root, depth);
}
TreeNode* search(TreeNode* root, int depth)
{
if (!root->left && !root->right)
return root;
if (!root->left)
return search(root->right, depth);
if (!root->right)
return search(root->left, depth);
auto depth_left = _subtreeDepthMap[root->left];
auto depth_right = _subtreeDepthMap[root->right];
if (depth_left == depth && depth_right == depth)
return root;
if (depth_left == depth)
return search(root->left, depth);
return search(root->right, depth);
}
int build_map(TreeNode* root, int curr_level)
{
if (!root)
return 0;
if (!root->left && !root->right)
{
_subtreeDepthMap[root] = curr_level;
return curr_level;
}
int left_depth = build_map(root->left, curr_level + 1);
int right_depth = build_map(root->right, curr_level + 1);
auto depth = std::max(left_depth, right_depth);
_subtreeDepthMap[root] = depth;
return depth;
}
// max depth of nodes in the subtree at the node
std::unordered_map<TreeNode*, int> _subtreeDepthMap;
};
}
| true |
0e6278390e5caf755ab1db51a24aa5c6c2190d50 | C++ | MikeMei/CSE335 | /CSE335_CompositeAndVisitorPattern/CSE335_inclass_CompositeAndVisitorPattern/EvaluationVisitor.h | UTF-8 | 2,175 | 2.96875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: EvaluationVisitor.h
* Author: laptop-pc
*
* Created on March 3, 2016, 1:14 PM
*/
#ifndef EVALUATIONVISITOR_H
#define EVALUATIONVISITOR_H
#include <stack>
#include "Visitor.h"
#include "Add.h"
#include "Subtract.h"
#include "Multiply.h"
#include "Divide.h"
#include "Negate.h"
#include "Literal.h"
using namespace std;
class EvaluationVisitor : public Visitor {
private:
stack<double> _myStack;
public:
double getValue() {double result = _myStack.top(); _myStack.pop(); return result;};
virtual void visitLiteral(Literal* lit) {
_myStack.push(lit->getValue());
};
virtual void visitNegate(Negate* neg) {
neg->getOperand()->Accept(this);
double val = _myStack.top();_myStack.pop();
_myStack.push(-val);
}
virtual void visitMultiply(Multiply* mul) {
mul->getLeftOperand()->Accept(this);
mul->getRightOperand()->Accept(this);
double rval = _myStack.top();_myStack.pop();
double lval = _myStack.top();_myStack.pop();
_myStack.push(lval * rval);
}
virtual void visitDivide(Divide* div) {
div->getLeftOperand()->Accept(this);
div->getRightOperand()->Accept(this);
double rval = _myStack.top();_myStack.pop();
double lval = _myStack.top();_myStack.pop();
_myStack.push(lval / rval);
}
virtual void visitAdd(Add* a) {
a->getLeftOperand()->Accept(this);
a->getRightOperand()->Accept(this);
double rval = _myStack.top();_myStack.pop();
double lval = _myStack.top();_myStack.pop();
_myStack.push(lval + rval);
}
virtual void visitSubtract(Subtract* sub) {
sub->getLeftOperand()->Accept(this);
sub->getRightOperand()->Accept(this);
double rval = _myStack.top();_myStack.pop();
double lval = _myStack.top();_myStack.pop();
_myStack.push(lval - rval);
}
};
#endif /* EVALUATIONVISITOR_H */
| true |
121ad9721a0eb105ac744bd64a7eb308e07b100e | C++ | kkuchar2/libmpeg7 | /sources/DESCRIPTORS/TEXTURE/TextureBrowsing/TextureBrowsing.h | UTF-8 | 874 | 2.609375 | 3 | [] | no_license | /** @file TextureBrowsing.h
* @brief Texture Browsing descriptor data,
* method for loading parameters, read and wirte to XML,
* modify and access data.
*
* @author Krzysztof Lech Kucharski
* @bug No bugs detected. */
#ifndef _TEXTUREBROWSING_H
#define _TEXTUREBROWSING_H
#include "../../Descriptor.h"
class TextureBrowsing : public Descriptor {
private:
int m_ComponentNumberFlag = 1;
int * m_Browsing_Component = NULL;
public:
TextureBrowsing();
void loadParameters(const char ** params);
void readFromXML(XMLElement * descriptorElement);
void SetComponentNumberFlag(int ComponentNumber);
void SetBrowsing_Component(int * PBC);
int GetComponentNumberFlag();
int * getBrowsingComponent();
std::string generateXML();
~TextureBrowsing();
};
#endif | true |
09f8c8058043ae325a740855c83c7cefa00f8ad0 | C++ | iintSjds/classical-lattice-monte-carlo | /src/old/oldlattice.h | UTF-8 | 5,348 | 3.390625 | 3 | [] | no_license | /********--Definitions of different lattice type--********/
/*
* Copyright (C) 2018 Xiansheng Cai. All rights reserved.
*/
#include <iostream>
#include <vector>
#include <cmath>
// a generic definition of Bravais Lattice
// Site_Type is provided outside by the required system. TBD in Model.
// all the rest of lattice feature is defined in this file, include lattice type, nearest neighbor, etc.
// special types of lattices can be inheritance from Lattice, which could be defined here or whenever needed.
// Kagomi lattice will be defined here as an example.
//predefined types indicating how to initialize
enum Lattice_Type {KAGOMI,TRIANGLE};
template <class Site_Type>
class Primitive_Cell{
//definition of primitive cell
private:
int dimension;//dimension of the system
std::vector<std::vector<double>> cell_vectors;//cell vectors, dimension x dimension
std::vector<Site_Type> sites;//sites of Site_Type,
int sites_number;//number of sites per primitive cell
std::vector<std::vector<double>> site_coordinates;//location of each site in primitive cell
public:
Primitive_Cell(Lattice_Type l_type);
int get_dimension() const {return dimension;}
int get_sites_number() const {return sites_number;}
std::vector<double> get_cell_vector(int index) const {return cell_vectors[index];}
std::vector<double> get_site_coordinates(int nos) const {return site_coordinates[nos];}
Site_Type& get_site(int nos) {return sites[nos];}
int print();//print all informations,used for debug
};
template <class Site_Type>
Primitive_Cell<Site_Type>::Primitive_Cell(Lattice_Type l_type){
if(l_type==KAGOMI){//predefined for Kagomi lattice
dimension=2;
cell_vectors={{1,0},{0.5,std::sqrt(3)/2}};
sites_number=3;
site_coordinates={{0.5,0},{0.25,std::sqrt(3)/4},{0.75,std::sqrt(3)/4}};
for(int i=0;i<sites_number;i++) sites.push_back(Site_Type());
}
if(l_type==TRIANGLE){
//TBA
}
}
template <class Site_Type>
int Primitive_Cell<Site_Type>::print(){
std::cout<<"dimension="<<dimension<<std::endl;
std::cout<<"sites_number="<<sites_number<<std::endl;
for(int i=0;i<dimension;i++){
std::cout<<"a"<<i<<"=(";
for(int j=0;j<dimension;j++) std::cout<<cell_vectors[i][j]<<"\t";
std::cout<<")"<<std::endl;
}
for(int i=0;i<sites_number;i++){
std::cout<<"n"<<i<<"=(";
for(int j=0;j<dimension;j++) std::cout<<site_coordinates[i][j]<<"\t";
std::cout<<")"<<std::endl;
}
return 1;
}
//definition of Lattice
//all defined to be periodic boundary condition
template <class Site_Type>
class Lattice{
private:
int dimension;
std::vector<int> Ls;
int sub_number;
std::vector<Primitive_Cell<Site_Type>> cells;
public:
Lattice(Lattice_Type l_type,int L);
int get_Ls(int i) const {return Ls[i];}
int get_dimension() const {return dimension;}
int get_lengths(int i) const {return Ls[i];}
int get_sub_number() const {return sub_number;}
Site_Type& get_site(std::vector<int> r,int sub);
Primitive_Cell<Site_Type>& get_cell(std::vector<int> r);
};
template <class Site_Type>
Lattice<Site_Type>::Lattice(Lattice_Type l_type,int L){
if(l_type==KAGOMI){
dimension=2;
sub_number=3;
for(int i=0;i<dimension;i++) Ls.push_back(L);
for(int i=0;i<std::pow(L,dimension);i++) cells.push_back(Primitive_Cell<Site_Type>(KAGOMI));
}
}
template <class Site_Type>
Primitive_Cell<Site_Type>& Lattice<Site_Type>::get_cell(std::vector<int> r){
int p=0;
for(int i=0;i<dimension;i++){// r[i] can be from -Ls[i] to Ls[i]
r[i]=(r[i]+Ls[i])%Ls[i];
}
//p=r1+r2*L1+r3*L1*L1+...
for(int i=0;i<dimension-1;i++){
p+=r[dimension-1-i];
p*=Ls[dimension-2-i];
}
p+=r[0];
return cells[p];
}
template <class Site_Type>
Site_Type& Lattice<Site_Type>::get_site(std::vector<int> r,int sub){
int p=0;
for(int i=0;i<dimension;i++){// r[i] can be from -Ls[i] to Ls[i]
r[i]=(r[i]+Ls[i])%Ls[i];
}
//p=r1+r2*L1+r3*L1*L1+...
for(int i=0;i<dimension-1;i++){
p+=r[dimension-1-i];
p*=Ls[dimension-2-i];
}
p+=r[0];
Primitive_Cell<Site_Type> &cell=cells[p];
return cell.get_site(sub);
}
template <class Site_Type>
class Kagomi_Lattice : public Lattice<Site_Type>
{
public:
Kagomi_Lattice(int L);
std::vector<Site_Type> get_nn_sites(std::vector<int> r,int sub);//get nearest neighbors of a site
};
template <class Site_Type>
std::vector<Site_Type> Kagomi_Lattice<Site_Type>::get_nn_sites(std::vector<int> r,int sub){
//return a vector of copies of nearest neighbors of the site
std::vector<std::vector<int>> nn_r_sub;
if(sub==0) nn_r_sub={{0,0,1},{0,0,2},{0,-1,2},{1,-1,1}};
if(sub==1) nn_r_sub={{0,0,0},{0,0,2},{-1,0,2},{-1,1,0}};
if(sub==2) nn_r_sub={{0,0,0},{0,0,1},{1,0,1},{0,1,0}};
std::vector<Site_Type> results;
for(int i=0;i<4;i++)
results.push_back(Lattice<Site_Type>::get_site({r[0]+nn_r_sub[i][0],r[1]+nn_r_sub[i][1]},nn_r_sub[i][2]));
return results;
}
template <class Site_Type>
Kagomi_Lattice<Site_Type>::Kagomi_Lattice(int L):
Lattice<Site_Type>(KAGOMI,L)
{}
| true |
945fd1ee06412a990f7e17a4a54411079fc6ed92 | C++ | cyberreefguru/WifiNeoPixels | /client/NeopixelWrapper.cpp | UTF-8 | 32,741 | 2.890625 | 3 | [
"MIT"
] | permissive | /*
* NeoPixelWrapper.cpp
*
* Created on: Sep 12, 2015
* Author: tsasala
*/
#define FASTLED_ALLOW_INTERRUPTS 0
#define FASTLED_ESP8266_RAW_PIN_ORDER
//#define FASTLED_ESP8266_NODEMCU_PIN_ORDER
#include "NeopixelWrapper.h"
CLEDController *ledController;
/**
* Constructor
*/
NeopixelWrapper::NeopixelWrapper()
{
leds = 0;
intensity = DEFAULT_INTENSITY;
}
/**
* Initializes the library
*/
boolean NeopixelWrapper::initialize(uint8_t numLeds, uint8_t intensity)
{
boolean status = false;
// Free memory if we already allocated it
if( leds != 0 )
{
free(leds);
}
// Allocate memory for LED buffer
leds = (CRGB *) malloc(sizeof(CRGB) * numLeds);
if (leds == 0)
{
Serial.println(F("ERROR - unable to allocate LED memory"));
}
else
{
// FastLED.addLeds<WS2812, D8>(leds, numLeds).setCorrection(TypicalLEDStrip); // string
ledController = &FastLED.addLeds<MY_CONTROLLER, MY_LED_PIN>(leds, numLeds).setCorrection(MY_COLOR_CORRECTION); // strip
Helper::workYield();
// // set master brightness control
// FastLED.setBrightness(intensity);
status = true;
}
return status;
}
/**
* Returns color of pixel, or null if out of bounds
*
*/
CRGB NeopixelWrapper::getPixel(int16_t index)
{
if( index <0 || index >= ledController->size() )
{
return leds[index];
}
else
{
#ifdef __DEBUG
Serial.print(F("WARN - pixel["));
Serial.print(index);
Serial.print(F("]="));
Serial.print(color, HEX);
Serial.println(F("-SKIPPING"));
#endif
return 0;
}
}
/**
* Sets the color of pixel. No action if pixel is out of bounds
*
*/
void NeopixelWrapper::setPixel(int16_t index, CRGB color, uint8_t s)
{
if( index <0 || index >= ledController->size() )
{
leds[index] = color;
if (s)
{
show();
// FastLED.show();
}
}
else
{
#ifdef __DEBUG
Serial.print(F("WARN - pixel["));
Serial.print(index);
Serial.print(F("]="));
Serial.print(color, HEX);
Serial.println(F("-SKIPPING"));
#endif
}
}
void NeopixelWrapper::show()
{
ledController->showLeds(intensity);
//
// FastLED.show();
}
/**
* Returns the hue update time
*/
uint8_t NeopixelWrapper::getIntensity()
{
return intensity;
// return FastLED.getBrightness();
}
/**
* Changes the amount of time to wait before updating the hue
*
*/
void NeopixelWrapper::setIntensity(uint8_t i)
{
intensity = i;
// FastLED.setBrightness(i);
}
/**
* fills all pixels with specified color
*
* @color - color to set
* @show - if true, sets color immediately
*/
void NeopixelWrapper::fill(CRGB color, uint8_t s)
{
resetIntensity();
for (uint8_t i = 0; i < ledController->size(); i++)
{
leds[i] = color;
}
worker();
if (s)
{
show();
// FastLED.show();
}
}
/**
* Fills pixels with specified pattern, starting at 0. 1 = on, 0 = off.
*
* Repeats pattern every 8 pixels.
*
*/
void NeopixelWrapper::fillPattern(uint8_t pattern, CRGB onColor, CRGB offColor)
{
resetIntensity();
setPattern(0, ledController->size(), pattern, 8, onColor, offColor, true);
}
/**
* Turns on LEDs one at time in sequence. LEFT = 0->n; RIGHT = n -> 0
*
* @direction - left (up) or right (down)
* @onColor - color to fill LEDs with
* @offColor - color to fill LEDs with
* @onTime - time to keep LED on
* @offTime - time to keep LED off
* @clearAfter - turn LED off after waiting
* @clearEnd - clear after complete
*/
void NeopixelWrapper::wipe(uint16_t repeat, uint32_t duration, uint8_t direction, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime, uint8_t clearAfter, uint8_t clearEnd)
{
uint16_t count = 0;
uint32_t endTime = millis() + duration;
resetIntensity();
// clear LEDs
fill(offColor, true);
while (isCommandAvailable() == false)
{
// Set start location
if( direction == LEFT )
{
// Loop through all LEDs
for(uint8_t j=0; j<ledController->size(); j++ )
{
leds[j] = onColor;
show();
// FastLED.show();
if( commandDelay(onTime) ) break;
if( clearAfter )
{
leds[j] = offColor;
show();
// FastLED.show();
if( commandDelay(offTime) ) break;
}
} // end for j
} // end if LEFT
else if(direction == RIGHT )
{
// Loop through all LEDs
for(int16_t j=ledController->size()-1; j>=0; j -=1 )
{
leds[j] = onColor;
show();
// FastLED.show();
if( commandDelay(onTime) ) break;
if( clearAfter )
{
leds[j] = offColor;
show();
// FastLED.show();
if( commandDelay(offTime) ) break;
}
} // end for j
} //end if RIGHT
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while
if( clearEnd )
{
fill(offColor, true);
}
}
/**
* Rotates a pattern across the strip; onTime determines pause between rotation
*
* NOTE: Starts at 0, and repeats every 8 pixels through end of strip
*/
void NeopixelWrapper::rotatePattern(uint16_t repeat, uint32_t duration, uint8_t pattern, uint8_t direction, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime)
{
uint16_t i = 0;
uint16_t count = 0;
uint32_t endTime = millis() + duration;
resetIntensity();
while (isCommandAvailable() == false)
{
setPattern(0, ledController->size(), pattern, 8, onColor, offColor, true);
if (commandDelay(onTime)) break;
if (direction == LEFT)
{
if (pattern & 0x80)
{
i = 0x01;
}
else
{
i = 0x00;
}
pattern = pattern << 1;
pattern = pattern | i;
}
else if (direction == RIGHT)
{
if (pattern & 0x01)
{
i = 0x80;
}
else
{
i = 0x00;
}
pattern = pattern >> 1;
pattern = pattern | i;
}
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while
}
/**
* Turns on LEDs one at time in sequence. LEFT = 0->n; RIGHT = n -> 0
*
* NOTE: starts with pattern "off" the screen and scrolls "on" the screen,
* then "off" the screen again
*
* @pattern - the pattern to wipe
* @direction - left (up) or right (down)
* @onColor - color to fill LEDs with
* @offColor - color to fill LEDs with
* @onTime - time to keep LED on
* @offTime - time to keep LED off
* @clearAfter - turn LED off after waiting
* @clearEnd - clear after complete
*/
void NeopixelWrapper::scrollPattern(uint16_t repeat, uint32_t duration, uint8_t pattern, uint8_t patternLength, uint8_t direction, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime, uint8_t clearAfter, uint8_t clearEnd)
{
uint16_t count = 0;
uint32_t endTime = millis() + duration;
CRGB pixels[patternLength];
int16_t curIndex;
resetIntensity();
// Initialize the pixel buffer
for(uint8_t i=0; i<patternLength; i++)
{
// rotates pattern and tests for "on"
if ((pattern >> i) & 0x01)
{
pixels[i] = onColor;
}
else
{
pixels[i] = offColor;
}
}
// clear LEDs
fill(offColor, true);
while (isCommandAvailable() == false)
{
// Loop through all LEDs (plus some)
for(int16_t j=0; j<(ledController->size()+patternLength-1); j++ )
{
// Set start location
if( direction == LEFT )
{
if( (j >= (patternLength-1)) && (j <= (ledController->size() - 1)) )
{
// copy all pixels to leds
curIndex = j;
for(uint8_t i=0; i<patternLength; i++)
{
leds[curIndex--] = pixels[i];
}
}
else if( j <= (patternLength-1) )
{
curIndex = j;
uint8_t bitsToCopy = j+1;
for(uint8_t i=0; i< bitsToCopy; i++)
{
leds[curIndex--] = pixels[i];
}
}
else if(j > (ledController->size()-1))
{
curIndex = ledController->size()-1;
uint8_t bitsToCopy = (patternLength-1) - (j-ledController->size());
uint8_t start = (patternLength-bitsToCopy);
#ifdef __DEBUG
Serial.print(F("j="));
Serial.print(j);
Serial.print(F(", curIndex="));
Serial.print(curIndex);
Serial.print(F(", bitsToCopy="));
Serial.print(bitsToCopy);
Serial.print(F(", start="));
Serial.println(start);
#endif
for(uint8_t i=start; i< 8; i++)
{
#ifdef __DEBUG
Serial.print(F("curIndex="));
Serial.print(curIndex);
Serial.print(F(", i="));
Serial.println(i);
#endif
leds[curIndex--] = pixels[i];
}
}
} // end if LEFT
else if(direction == RIGHT )
{
if( (j >= (patternLength-1)) && (j <= (ledController->size() - 1)) )
{
// copy all pixels to leds
curIndex = ledController->size() - j - 1;
for(uint8_t i=0; i<patternLength; i++)
{
leds[curIndex++] = pixels[i];
}
}
else if( j < (patternLength-1) )
{
curIndex = ledController->size() - j - 1;
uint8_t bitsToCopy = ledController->size() - curIndex;
for(uint8_t i=0; i< bitsToCopy; i++)
{
leds[curIndex++] = pixels[i];
}
}
else if(j > (ledController->size()-1))
{
curIndex = 0;
uint8_t bitsToCopy = (patternLength-1) - (j-ledController->size());
uint8_t start = (patternLength-bitsToCopy);
#ifdef __DEBUG
Serial.print(F("j="));
Serial.print(j);
Serial.print(F(", curIndex="));
Serial.print(curIndex);
Serial.print(F(", bitsToCopy="));
Serial.print(bitsToCopy);
Serial.print(F(", start="));
Serial.println(start);
#endif
for(uint8_t i=start; i< 8; i++)
{
#ifdef __DEBUG
Serial.print(F("curIndex="));
Serial.print(curIndex);
Serial.print(F(", i="));
Serial.println(i);
#endif
leds[curIndex++] = pixels[i];
}
}
} //end if RIGHT
show();
// FastLED.show();
commandDelay(onTime);
if( clearAfter )
{
fill(offColor, false);
}
} // end for j
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while
if( clearEnd )
{
fill(offColor, true);
}
}
/**
* Bounces the specified pattern the specified direction.
*
* NOTE: Pattern does not double flash at the ends.
*
*/
void NeopixelWrapper::bounce(uint16_t repeat, uint32_t duration, uint8_t pattern, uint8_t patternLength, uint8_t direction, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime, uint32_t bounceTime, uint8_t clearAfter, uint8_t clearEnd)
{
// custom bounce with 0-7, n-(n-7)
resetIntensity();
uint16_t count = 0;
uint32_t endTime = millis() + duration;
uint8_t first = true;
uint8_t lstart = 0;
uint8_t lend = 0;
uint8_t rstart = 0;
uint8_t rend = 0;
resetIntensity();
if (direction == LEFT)
{
lstart = 0;
lend = ledController->size() - patternLength;
rstart = ledController->size() - patternLength - 1;
rend = 0;
}
else if (direction == RIGHT)
{
rstart = ledController->size() - patternLength;
rend = 0;
lstart = 1;
lend = ledController->size() - patternLength;
}
else
{
return;
}
// Fill with off color
fill(offColor, true);
// work until we have a new command
while (isCommandAvailable() == false)
{
if( direction == LEFT )
{
for(int16_t i=lstart; i<=lend; i++ )
{
setPattern(i, patternLength, pattern, patternLength, onColor, offColor, true);
if (commandDelay(onTime)) break;
if( clearAfter )
{
fill(offColor, true);
if (commandDelay(offTime)) break;
}
}
if( clearEnd )
{
fill(offColor, true);
if (commandDelay(bounceTime)) break;
}
for(int16_t i=rstart; i>=rend; i-=1 )
{
setPattern(i, patternLength, pattern, patternLength, onColor, offColor, true);
if (commandDelay(onTime)) break;
if( clearAfter )
{
fill(offColor, true);
if (commandDelay(offTime)) break;
}
}
if( clearEnd )
{
fill(offColor, true);
if (commandDelay(bounceTime)) break;
}
if( first )
{
lstart = 1;
lend = ledController->size() - patternLength - 1;
rstart = ledController->size() - patternLength;
rend = 0;
first = false;
}
}
else if(direction == RIGHT )
{
for(int16_t i=rstart; i>=rend; i-=1 )
{
setPattern(i, patternLength, pattern, patternLength, onColor, offColor, true);
if (commandDelay(onTime)) break;
if( clearAfter )
{
fill(offColor, true);
if (commandDelay(offTime)) break;
}
}
if( clearEnd )
{
fill(offColor, true);
if (commandDelay(bounceTime)) break;
}
for(int16_t i=lstart; i<=lend; i++ )
{
setPattern(i, patternLength, pattern, patternLength, onColor, offColor, true);
if (commandDelay(onTime)) break;
if( clearAfter )
{
fill(offColor, true);
if (commandDelay(offTime)) break;
}
}
if( clearEnd )
{
fill(offColor, true);
if (commandDelay(bounceTime)) break;
}
if( first )
{
rstart = ledController->size() - patternLength -1;
rend = 0;
lstart = 1;
lend = ledController->size() - patternLength;
first = false;
}
}
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while
} // end bounce
/**
* Starts in the middle and works out; or starts in the end and works in
*/
void NeopixelWrapper::middle(uint16_t repeat, uint32_t duration, uint8_t direction, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime, uint8_t clearAfter, uint8_t clearEnd)
{
uint16_t count = 0;
uint32_t endTime = millis() + duration;;
uint8_t numPixels = ledController->size();
uint8_t halfNumPixels = numPixels/2;
resetIntensity();
fill(offColor, true);
while (isCommandAvailable() == false)
{
if(direction == IN)
{
for(uint8_t i=0; i<halfNumPixels; i++)
{
leds[i] = onColor;
leds[(numPixels-1)-i] = onColor;
show();
// FastLED.show();
if( commandDelay(onTime) ) return;
if( clearAfter == true )
{
leds[i] = offColor;
leds[(numPixels-1)-i] = offColor;
show();
// FastLED.show();
if( commandDelay(offTime) ) return;
}
}
}
else if( direction == OUT )
{
for(uint8_t i=0; i<halfNumPixels+1; i++)
{
leds[halfNumPixels-i] = onColor;
leds[halfNumPixels+i] = onColor;
show();
// FastLED.show();
if( commandDelay(onTime) ) return;
if( clearAfter == true )
{
leds[halfNumPixels-i] = offColor;
leds[halfNumPixels+i] = offColor;
show();
// FastLED.show();
if( commandDelay(offTime) ) return;
}
}
}
if(clearEnd)
{
fill(offColor, true);
}
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while
}
/**
* Flashes random LED with specified color
*/
void NeopixelWrapper::randomFlash(uint16_t repeat, uint32_t duration, uint32_t onTime, uint32_t offTime, CRGB onColor, CRGB offColor, uint8_t number)
{
uint16_t count = 0;
uint32_t endTime = millis() + duration;;
uint8_t i, j;
resetIntensity();
fill(offColor, true);
if( number == 0)
{
number = 1;
}
if( number > ledController->size() )
{
number = ledController->size();
}
while (isCommandAvailable() == false)
{
for(j=0; j<number; j++)
{
do
{
i = random(ledController->size());
} while( leds[i] != offColor );
if( onColor == (CRGB)RAINBOW )
{
leds[i] = CHSV(random8(0, 255), 255, 255);
}
else
{
leds[i] = onColor;
}
}
show();
if (commandDelay(onTime)) break;
fill(offColor, true);
// leds[i] = offColor;
if (commandDelay(offTime)) break;
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
}
fill(offColor, true);
} // randomFlash
/**
* Fades LEDs up or down with the specified time increment
*/
void NeopixelWrapper::fade(uint8_t direction, uint8_t fadeIncrement, uint32_t time, CRGB color)
{
int16_t i=0;
if( direction == DOWN )
{
// FastLED.setBrightness(255);
// FastLED.showColor(color);
intensity = 255;
}
else if( direction == UP )
{
// FastLED.setBrightness(0);
// FastLED.showColor(color);
intensity = 0;
}
ledController->showColor(color, intensity);
while(i<255)
{
if( commandDelay(time) ) break;
i = i+fadeIncrement;
if( i > 255)
{
i = 255;
}
if( direction == DOWN )
{
intensity = 255-i;
// FastLED.setBrightness(255-i);
}
else if( direction == UP)
{
intensity = i;
// FastLED.setBrightness(i);
}
ledController->showColor(color, intensity);
// FastLED.showColor(color);
}
}
/**
* Flashes LEDs
*/
void NeopixelWrapper::strobe(uint16_t repeat, uint32_t duration, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime )
{
uint16_t count = 0;
uint32_t endTime = millis() + duration;;
resetIntensity();
while( isCommandAvailable() == false )
{
fill(onColor, true);
if( commandDelay(onTime) ) break;
fill(offColor, true);
if( commandDelay(offTime) ) break;
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command
}
/**
* Creates lightning effort
*/
void NeopixelWrapper::lightning(uint16_t repeat, uint32_t duration, CRGB onColor, CRGB offColor)
{
uint16_t count = 0;
uint32_t endTime = millis() + duration;;
uint32_t large;
uint8_t i, b;
b = false;
resetIntensity();
while(isCommandAvailable() == false )
{
for(i=0; i<count; i++)
{
large = random(0,100);
fill(onColor, true);
if( large > 40 && b == false)
{
if( commandDelay(random(100, 350)) ) break;
b = true;
}
else
{
if( commandDelay(random(20, 50)) ) break;
}
fill(offColor, true);
if( large > 40 && b == false )
{
if( commandDelay(random(200, 500)) ) break;
}
else
{
if( commandDelay(random(30, 70)) ) break;
}
}
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command
}
/**
* Fills strip with rainbow pattern
*
* @glitter if true, randomly pops white into rainbow pattern
*/
void NeopixelWrapper::rainbow(uint32_t duration, uint8_t glitterProbability, CRGB glitterColor, uint32_t onTime, uint8_t hueUpdateTime)
{
uint8_t hue = 0;
uint32_t hueTime = 0;
uint32_t endTime = millis() + duration;
resetIntensity();
fill(BLACK, true);
while(isCommandAvailable() == false )
{
// FastLED's built-in rainbow generator
fill_rainbow(leds, ledController->size(), hue, 7);
if (glitterProbability > 0)
{
if (random8() < glitterProbability)
{
leds[random16(ledController->size())] += glitterColor;
}
}
show();
// FastLED.show();
commandDelay( onTime );
hueTime +=1;
if( hueTime == hueUpdateTime )
{
hueTime = 0;
hue += 1;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command
} // end rainbow
/**
* This function draws rainbows with an ever-changing,widely-varying set of parameters.
* https://gist.github.com/kriegsman/964de772d64c502760e5
*
*/
void NeopixelWrapper::rainbowFade(uint32_t duration, uint32_t onTime)
{
uint32_t endTime = millis() + duration;;
//TODO: Figure out to better control timing with FPS or hue update time
resetIntensity();
fill(BLACK, true);
while(isCommandAvailable() == false )
{
static uint16_t sPseudotime = 0;
static uint16_t sLastMillis = 0;
static uint16_t sHue16 = 0;
uint8_t sat8 = beatsin88(87, 220, 250);
uint8_t brightdepth = beatsin88(341, 96, 224);
uint16_t brightnessthetainc16 = beatsin88(203, (25 * 256), (40 * 256));
uint8_t msmultiplier = beatsin88(147, 23, 60);
uint16_t hue16 = sHue16; //gHue * 256;
uint16_t hueinc16 = beatsin88(113, 1, 3000);
uint16_t ms = millis();
uint16_t deltams = ms - sLastMillis;
sLastMillis = ms;
sPseudotime += deltams * msmultiplier;
sHue16 += deltams * beatsin88(400, 5, 9);
uint16_t brightnesstheta16 = sPseudotime;
for (uint16_t i = 0; i < (uint16_t) ledController->size(); i++)
{
hue16 += hueinc16;
uint8_t hue8 = hue16 / 256;
brightnesstheta16 += brightnessthetainc16;
uint16_t b16 = sin16(brightnesstheta16) + 32768;
uint16_t bri16 = (uint32_t) ((uint32_t) b16 * (uint32_t) b16) / 65536;
uint8_t bri8 = (uint32_t) (((uint32_t) bri16) * brightdepth) / 65536;
bri8 += (255 - brightdepth);
CRGB newcolor = CHSV(hue8, sat8, bri8);
uint16_t pixelnumber = i;
pixelnumber = (ledController->size() - 1) - pixelnumber;
nblend(leds[pixelnumber], newcolor, 64);
}
show();
// FastLED.show();
commandDelay( onTime );
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command
} // end rainbow fade
/**
* Creates random speckles of the specified color.
*
* 5-10 LEDs makes a nice effect
*
* NOTE: runTime has no effect at this time
*
*/
void NeopixelWrapper::confetti(uint32_t duration, CRGB color, uint8_t fadeBy, uint32_t onTime, uint8_t hueUpdateTime)
{
uint8_t hue = 0;
uint32_t hueTime = 0;
uint32_t endTime = millis() + duration;;
resetIntensity(); // reset intensity to full
fill(BLACK, true); // clear any previous colors
while(isCommandAvailable() == false )
{
// random colored speckles that blink in and fade smoothly
fadeToBlackBy(leds, ledController->size(), fadeBy);
int pos = random16(ledController->size());
if (color == (CRGB)RAINBOW)
{
leds[pos] += CHSV(hue + random8(64), 200, 255);
// do some periodic updates
if( hueTime == hueUpdateTime )
{
hueTime = 0;
hue += 1;
}
}
else
{
leds[pos] += color;
}
show();
// FastLED.show();
commandDelay( onTime );
hueTime += 1;
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command
} // end confetti
/**
* Creates "cylon" pattern - bright led followed up dimming LEDs back and forth
*
*/
void NeopixelWrapper::cylon(uint16_t repeat, uint32_t duration, CRGB color, uint32_t fadeTime, uint8_t fps, uint8_t hueUpdateTime)
{
uint8_t hue = 0;
uint32_t hueTime = 0;
uint16_t count = 0;
uint32_t endTime = millis() + duration;;
uint8_t flag = false; // flag to increment counter
resetIntensity();
fill( BLACK, true);
while(isCommandAvailable() == false )
{
fadeToBlackBy(leds, ledController->size(), 20);
int pos = beatsin16(fps, 0, ledController->size());
if (color == (CRGB)RAINBOW)
{
leds[pos] += CHSV(hue, 255, 192);
if( hueTime == hueUpdateTime)
{
hueTime = 0;
hue +=1;
}
}
else
{
leds[pos] += color;
}
show();
// FastLED.show();
commandDelay( fadeTime );
hueTime += 1;
if( pos == 0 && flag == false)
{
count += 1;
flag = true; // set flag
}
if( flag == true && pos != 0 )
{
flag = false; // wait for beats to go past 0
}
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command
} // end cylon
/**
* No clue how to explain this one...
*
*/
void NeopixelWrapper::bpm(uint32_t duration, uint32_t onTime, uint8_t hueUpdateTime)
{
uint8_t hue = 0;
uint32_t hueTime = 0;
uint32_t endTime = millis() + duration;;
resetIntensity();
fill( BLACK, true);
while(isCommandAvailable() == false )
{
// colored stripes pulsing at a defined Beats-Per-Minute (BPM)
uint8_t BeatsPerMinute = 62;
CRGBPalette16 palette = PartyColors_p;
uint8_t beat = beatsin8(BeatsPerMinute, 64, 255);
for (int i = 0; i < ledController->size(); i++)
{ //9948
leds[i] = ColorFromPalette(palette, hue + (i * 2), beat - hue + (i * 10));
}
if( hueTime == hueUpdateTime )
{
hueTime = 0;
hue +=1;
}
show();
// FastLED.show();
commandDelay( onTime );
hueTime += 1;
if( duration > 0 && millis() > endTime )
{
break;
}
}
}
/**
* No clue how to explain this one
*
*/
void NeopixelWrapper::juggle(uint32_t duration, uint32_t onTime)
{
uint32_t endTime = millis() + duration;;
//TODO: Figure out to better control hue update time
resetIntensity();
fill(BLACK, true);
while(isCommandAvailable() == false )
{
// eight colored dots, weaving in and out of sync with each other
fadeToBlackBy(leds, ledController->size(), 20);
byte dothue = 0;
for (int i = 0; i < 8; i++)
{
leds[beatsin16(i + 7, 0, ledController->size())] |= CHSV(dothue, 200, 255);
dothue += 32;
}
show();
// FastLED.show();
commandDelay( onTime );
if( duration > 0 && millis() > endTime )
{
break;
}
}
}
/**
* Stacks LEDs based on direction
*
*/
void NeopixelWrapper::stack(uint16_t repeat, uint32_t duration, uint8_t direction, CRGB onColor, CRGB offColor, uint32_t onTime, uint8_t clearEnd)
{
uint8_t index;
uint16_t count;
uint32_t endTime;
resetIntensity();
fill(offColor, true);
count = 0;
endTime = millis() + duration;
while(isCommandAvailable() == false )
{
if( direction == DOWN )
{
index = 0;
}
else
{
index = ledController->size()-1;
}
for(uint8_t i=0; i<ledController->size(); i++ )
{
if(direction == DOWN )
{
for(int16_t j=ledController->size(); j>index; j -= 1 )
{
if( onColor == (CRGB)RAINBOW )
{
leds[j] = CHSV(random8(0, 255), 255, 255);
}
else
{
leds[j] = onColor;
}
show();
// FastLED.show();
if( commandDelay( onTime) ) return;
leds[j] = offColor;
show();
// FastLED.show();
}
if( onColor == (CRGB)RAINBOW )
{
leds[index] = CHSV(random8(0, 255), 255, 255);
}
else
{
leds[index] = onColor;
}
show();
// FastLED.show();
index += 1;
}
else if( direction == UP )
{
for(int16_t j=0; j<index; j += 1 )
{
if( onColor == (CRGB)RAINBOW )
{
leds[j] = CHSV(random8(0, 255), 255, 255);
}
else
{
leds[j] = onColor;
}
show();
// FastLED.show();
if( commandDelay( onTime) ) return;
leds[j] = offColor;
show();
// FastLED.show();
}
if( onColor == (CRGB)RAINBOW )
{
leds[index] = CHSV(random8(0, 255), 255, 255);
}
else
{
leds[index] = onColor;
}
show();
// FastLED.show();
index -= 1;
}
} // end for size
if( clearEnd == true )
{
fill(offColor, true);
}
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // end while command == false
} // end stack
/**
* Randomly fills string with specified color
*
*/
void NeopixelWrapper::fillRandom(uint16_t repeat, uint32_t duration, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime, uint8_t clearAfter, uint8_t clearEnd)
{
uint8_t total;
uint8_t index;
uint16_t count;
uint32_t endTime;
uint8_t flag = false;
resetIntensity();
fill(offColor, true);
count = 0;
endTime = millis() + duration;
CRGB color = onColor;
while(isCommandAvailable() == false )
{
total = ledController->size();
while( total > 0 )
{
index = random8(0, ledController->size());
if( onColor == (CRGB)RAINBOW )
{
color = CHSV(random8(0, 255), 255, 255);
}
if( leds[index] == offColor || flag == true )
{
leds[index] = color;
show();
// FastLED.show();
total--;
if( commandDelay(onTime)) return;
if( clearAfter )
{
leds[index] = offColor;
if( commandDelay(offTime)) return;
}
}
}
flag = true;
if( clearEnd )
{
fill(offColor, true);
flag = false;
}
count += 1;
if( repeat > 0 && count >= repeat )
{
break;
}
if( duration > 0 && millis() > endTime )
{
break;
}
} // while command == false
} // end randomFill
////////////////////////////////////////
// BEGIN PRIVATE FUNCTIONS
////////////////////////////////////////
/**
* Sets the color of the specified LED for onTime time. If clearAfter
* is true, returns color to original color and waits offTime before returning.
*/
void NeopixelWrapper::setPatternTimed(int16_t startIndex, uint8_t pattern, CRGB onColor, CRGB offColor, uint32_t onTime, uint32_t offTime, uint8_t clearAfter)
{
CRGB currentColor[8];
for(uint8_t i=0; i<8; i++)
{
if(startIndex+i < ledController->size() && startIndex+i >= 0)
{
currentColor[i] = leds[startIndex+i];
}
}
setPattern(startIndex, 8, pattern, 8, onColor, offColor, true);
commandDelay(onTime);
if(clearAfter == true)
{
for(uint8_t i=0; i<8; i++)
{
if(startIndex+i < ledController->size() && startIndex+i >= 0)
{
leds[startIndex+i] = currentColor[i];
}
}
show();
// FastLED.show();
commandDelay(offTime);
}
}
/**
* Sets the color of the specified LED for onTime time. If clearAfter
* is true, returns color to original color and waits offTime before returning.
*/
void NeopixelWrapper::setPixelTimed(int16_t index, CRGB newColor, uint32_t onTime, uint32_t offTime, uint8_t clearAfter)
{
CRGB curColor;
curColor = leds[index];
leds[index] = newColor;
show();
// FastLED.show();
commandDelay(onTime);
if(clearAfter == true)
{
leds[index] = curColor;
show();
// FastLED.show();
commandDelay(offTime);
}
}
/**
* Fills the pixels with the specified pattern, starting at the specified index.
* Stops filling when length is hit.
*
*/
void NeopixelWrapper::setPattern(int16_t startIndex, uint8_t length, uint8_t pattern, uint8_t patternLength, CRGB onColor, CRGB offColor, uint8_t s)
{
int16_t index;
uint8_t patternIndex = 0;
#ifdef __DEBUG
Serial.print(F("setPattern(start="));
Serial.print(startIndex);
Serial.print(F(", len="));
Serial.print(length);
Serial.print(F(", pattern="));
Serial.print(pattern);
Serial.print(F(", pl="));
Serial.print(patternLength);
Serial.println(F(")"));
#endif
for(index=0; index<length; index++)
{
worker();
// Safety measure - allows pattern length to be > amount of pixels left
if( (startIndex+index) >= ledController->size())
{
#ifdef __DEBUG
Serial.print(F("WARN - pixel["));
Serial.print(startIndex+index);
Serial.print(F("]="));
Serial.print(onColor, HEX);
Serial.println(F("-SKIPPING"));
#endif
}
else if( (startIndex+index) < 0)
{
#ifdef __DEBUG
Serial.print(F("WARN - pixel["));
Serial.print(startIndex+index);
Serial.print(F("]="));
Serial.print(onColor, HEX);
Serial.println(F("-SKIPPING"));
#endif
}
else
{
// rotates pattern and tests for "on"
if ((pattern >> patternIndex) & 0x01)
{
leds[startIndex+index] = onColor;
#ifdef __DEBUG
Serial.print(F("INFO - pixel["));
Serial.print(startIndex+index);
Serial.print(F("]="));
Serial.println(onColor, HEX);
#endif
}
else
{
leds[startIndex+index] = offColor;
#ifdef __DEBUG
Serial.print(F("INFO - pixel["));
Serial.print(startIndex+index);
Serial.print(F("]="));
Serial.println(offColor, HEX);
#endif
}
}
// increases pattern index
patternIndex += 1;
// test if we need to reset pattern index
if( patternIndex == patternLength)
{
patternIndex = 0;
}
} // end for
if( s )
{
show();
// FastLED.show();
}
}
/**
* Sets the color of the specified LED.
*/
void NeopixelWrapper::setPixel(int16_t index, CRGB color)
{
if( index <0 || index >= ledController->size() )
{
leds[index] = color;
}
else
{
#ifdef __DEBUG
Serial.print(F("WARN - pixel["));
Serial.print(index);
Serial.print(F("]="));
Serial.print(color, HEX);
Serial.println(F("-SKIPPING"));
#endif
}
Helper::workYield(); // Give time to ESP
}
/**
* If current intensity is 0, reset to default
*
*/
void NeopixelWrapper::resetIntensity()
{
if(intensity == 0 )
{
intensity = DEFAULT_INTENSITY;
}
// if( FastLED.getBrightness() == 0)
// {
// FastLED.setBrightness( DEFAULT_INTENSITY );
// }
}
| true |
f224897387fc8aeb89b49b4b8fa72e1880bf41c6 | C++ | rex0yt/MyCods | /题解/POJ 3253 Fence Repair.cpp | GB18030 | 671 | 3.109375 | 3 | [] | no_license | /* ֱӶѽȶУ*/
#include <iostream>
#include <queue>
#include <string>
using namespace std;
const int NN = 20000 + 100;
struct cmp
{
bool operator ()(int &a,int &b)
{
return a>b;//Сֵ
}
};
priority_queue <int, vector<int>, cmp> pq;
int n;
long long sum = 0;
int main()
{
int x;
int a, b;
cin >> n;
while(n --)
{
cin >> x;
pq.push(x);
}
while(1)
{
a = pq.top();
pq.pop();
if(pq.empty())break;
b = pq.top();
pq.pop();
sum += a+b;
pq.push(a+b);
}
cout << sum << endl;
return 0;
}
| true |
180d720cd46b6b58f80adc324f0d8e88cd81c768 | C++ | annlie/oop | /hw1/hw01.cpp | UTF-8 | 3,721 | 3.9375 | 4 | [] | no_license | //
// Annlie Nguyen
// hw01
//
// Program for a medieval times game where warriors battle
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
struct Warrior {
string name;
int strength;
};
void createWarrior(vector<Warrior>& warVec, const string& name, const int& strength);
void battleWarriors(vector<Warrior>& warVec, const string& first, const string& second);
void displayStatus(const vector<Warrior>& warVec);
int main() {
vector<Warrior> warriorCollection;
ifstream warriorFile("warriors.txt");
if (!warriorFile) {
cerr << "File not opened" << endl;
exit(1);
}
string commandCheck;
string name;
int initialStrength;
string firstWarrior;
string secondWarrior;
while (warriorFile >> commandCheck) {
if (commandCheck == "Warrior") {
warriorFile >> name;
warriorFile >> initialStrength;
createWarrior(warriorCollection, name, initialStrength);
} else if (commandCheck == "Status") {
displayStatus(warriorCollection);
} else { //commandCheck == "Battle"
warriorFile >> firstWarrior;
warriorFile >> secondWarrior;
battleWarriors(warriorCollection, firstWarrior, secondWarrior);
}
}
return 0;
}
void createWarrior(vector<Warrior>& warVec, const string& name, const int& strength) {
Warrior newWarrior;
newWarrior.name = name;
newWarrior.strength = strength;
warVec.push_back(newWarrior);
}
void battleWarriors(vector<Warrior>& warVec, const string& first, const string& second) {
cout << first << " battles " << second << endl;
size_t firstPos = -1;
size_t secondPos = -1;
for (size_t i = 0; i < warVec.size(); i++) {
if (warVec[i].name == first) { //finds index of "first" warrior
firstPos = i;
}
if (warVec[i].name == second) { //finds index of "second" warrior
secondPos = i;
}
if (firstPos != -1 && secondPos != -1) { //ends loop once both are found
break;
}
}
if (warVec[firstPos].strength == 0 && warVec[secondPos].strength > 0) {
cout << "He's dead, " << second << endl;
} else if (warVec[firstPos].strength > 0 && warVec[secondPos].strength == 0) {
cout << "He's dead, " << first << endl;
} else if (warVec[firstPos].strength == warVec[secondPos].strength
&& warVec[firstPos].strength == 0) {
cout << "Oh, NO! They're both dead! Yuck!" << endl;
//only need to check if one strength equal to 0 since both equal anyways
} else if (warVec[firstPos].strength == warVec[secondPos].strength) {
warVec[firstPos].strength = 0;
warVec[secondPos].strength = 0;
cout << "Mutual Annihilation: " << first << " and " << second;
cout << " die at each other's hands" << endl;
} else if (warVec[firstPos].strength > warVec[secondPos].strength) {
warVec[firstPos].strength -= warVec[secondPos].strength;
warVec[secondPos].strength = 0;
cout << first << " defeats " << second << endl;
} else if (warVec[firstPos].strength < warVec[secondPos].strength) {
warVec[secondPos].strength -= warVec[firstPos].strength;
warVec[firstPos].strength = 0;
cout << second << " defeats " << first << endl;
}
}
void displayStatus(const vector<Warrior>& warVec) {
cout << "There are: " << warVec.size() << " warriors" << endl;
for (size_t i = 0; i < warVec.size(); i++) {
cout << "Warrior: " << warVec[i].name << ", ";
cout << "strength: " << warVec[i].strength << endl;
}
}
| true |
8055f05c5157e528a520d1365caeb519f07e84ce | C++ | Solpatium/LogicGame | /LogicGame/LogicPlaything.cpp | UTF-8 | 2,982 | 3.15625 | 3 | [
"MIT"
] | permissive | #include "LogicPlaything.h"
LogicPlaything::LogicPlaything(short int difficulty)
: difficulty(difficulty) {
generatePlaything();
}
LogicPlaything::~LogicPlaything() {
delete root;
}
string LogicPlaything::toString() {
int n = 0;
string toReturn = root->orderedSentences(n) + "\n";
n = 0;
toReturn += root->senencesToNumbers(n) + " in trinary logic is:";
return toReturn;
}
void LogicPlaything::generatePlaything() {
queue<LogicalNode*> q;
short int remaining = difficulty - 1;
root = randomConjunction();
q.push(root);
LogicalNode* temp;
// Proces all conjunction nodes
while (!q.empty()) {
temp = q.front();
q.pop();
/*
* Chances are 50/50 for each node to be conjunction
*/
//left node
if (remaining > 0 && Random::get() < 0.5) {
temp->left = randomConjunction();
q.push(temp->left);
remaining--;
}
// right node
if (remaining > 0 && Random::get() < 0.5) {
temp->right = randomConjunction();
q.push(temp->right);
remaining--;
}
/*
* If this was the last node to precess and we didn't add any conjunstions to it, while there are still conjunctions to make we have to add it anyway
*/
if (q.empty() && remaining > 0) {
// Neither left or right are conjunctions, if they were the queue woudn't be empty, let's prefer right child to add conjunction
temp->right = randomConjunction();
q.push(temp->right);
remaining--;
}
/*
* Any child being a null means we have to add sentence node
*/
if (temp->right == nullptr) temp->right = randomSentence();
if (temp->left == nullptr) temp->left = randomSentence();
}
}
ConjunctionNode* LogicPlaything::randomConjunction() {
double random = Random::get();
if (random <= 1.0 / 3.0) {
return new ConjunctionNode(LogicConjunction::AND);
}
else if (random <= 2.0 / 3.0) {
return new ConjunctionNode(LogicConjunction::OR);
}
else {
return new ConjunctionNode(LogicConjunction::IMPL);
}
}
SentenceNode* LogicPlaything::randomSentence() {
RandomLines randomLines = RandomLines::getInstance();
double random = Random::get();
if (random <= 1.0 / 3.0) {
return new SentenceNode( randomLines.getTrue() );
}
else if (random <= 2.0 / 3.0) {
return new SentenceNode( randomLines.getFalse() );
}
else {
return new SentenceNode( randomLines.getUnknown() );
}
}
Trilean LogicPlaything::getAnswer() {
return root->getValue();
}
string LogicPlaything::getSolve() {
string solve = "";
while( !root->isSimplified() ) {
solve += root->simplify() + "\n";
}
if( root->isNegated() )
solve += root->simplify() + "\n";
return solve;
} | true |
67b49776a49dc94e60e9345fdaef457585d9727e | C++ | Nalepa/2d_adventurer_game | /2d_game/Game_Saving.h | UTF-8 | 962 | 2.6875 | 3 | [] | no_license | #pragma once
#include "Main_Character.h"
#include "Environment.h"
#include <string>
#include <fstream>
#include "Exceptions.h"
class Game_Saving
{
protected:
Character_Stats* character_stats;
Main_Character* main_character;
Environment* environment;
std::string file_name;
std::ofstream file;
sf::Text text;
sf::Font font;
bool statement_displaying;
const float statement_time_period;
sf::Clock statement_clock;
public:
Game_Saving(Main_Character* main_character, Character_Stats* character_stats, Environment* environment, std::string file_name);
void save();
virtual void statement_support(sf::RenderWindow &window, const float &x, const float &y);
bool get_statement_displying();
~Game_Saving();
};
std::ostream& operator <<(std::ostream& output, Main_Character* main_character);
std::ostream& operator <<(std::ostream& output, Character_Stats* character_stats);
std::ostream& operator <<(std::ostream& output, Environment* environment);
| true |
658515fb673a8b6642169b0d667d0e92744261ec | C++ | dbousque/_test | /piscine_cpp/d02/ex04/List.hpp | UTF-8 | 343 | 2.953125 | 3 | [] | no_license |
#ifndef LIST_H
# define LIST_H
#include <string>
class List
{
public:
List();
List(List &other);
~List();
List &operator=(List &other);
void add(void *elt);
size_t length();
void *get(size_t n);
void *pop();
void *getTop();
private:
void **_elts;
size_t _len;
size_t _size;
void _doubleListSize();
};
#endif | true |
1b771432c90f732bc1debcb0dfe4439bfaf6aef8 | C++ | Siwwyy/3_Studying_Year | /ARTIFICIAL_INTELLIGENCE/!NEURAL_NETWORKS/Fourth/Fourth/main.cpp | UTF-8 | 5,749 | 2.921875 | 3 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <fstream>
#include <istream>
#include <iterator>
#include <time.h>
#include <random>
#include <iomanip>
#include <math.h>
#include <cstdint>
#include <windows.h>
#define NEW_LINE '\n'
//const __int16 const* const* Read_Inputs(const char * file_name, size_t & width, size_t & height);
__int16** Read_Inputs(const char* file_name, size_t& width, size_t& height);
const void Show_Memory(const __int16 const* const* Matrix, const size_t& width, const size_t& height);
const void Display_Matrix(const __int16 const* const* Matrix, const size_t& width, const size_t& height);
const void Display_Single_Matrix(const __int16 const* Matrix, const size_t& width);
const void Hopfield(__int16** Matrix, const size_t& width);
int main(int argc, char* argv[])
{
using _STD cout;
using _STD endl;
using _STD cin;
__int16** Matrix{};
size_t width{};
size_t height{};
Matrix = Read_Inputs("file.in", width, height);
//Display_Matrix(Matrix, width, height);
Hopfield(Matrix, width);
//DEALLOCATE ALLOCATED MEMORY
for (size_t i = 0; i < height; ++i)
{
delete[] Matrix[i];
}
delete[] Matrix;
system("pause");
return 0;
}
__int16** Read_Inputs(const char* file_name, size_t& width, size_t& height)
{
_STD fstream file_in;
file_in.open("file.in", std::ios_base::in | std::ios_base::binary);
__int16** Matrix{};
if (file_in.good() == false)
{
_STD cerr << "[WARRNING:0001] Invalid file_path\n";
}
else
{
char temp{};
auto to_bool = [](const char& _char) -> __int16 { if (_char == '1') { return 1; } else { return -1; }; };
file_in >> height;
file_in >> width;
Matrix = new __int16* [height];
for (size_t i = 0; i < height; ++i)
{
Matrix[i] = new __int16[width];
for (size_t j = 0; j < width; ++j)
{
file_in >> temp;
//_STD cout << to_bool(temp) << ' ';
Matrix[i][j] = to_bool(temp);
}
//_STD cout << NEW_LINE;
}
}
file_in.close();
return Matrix;
}
const void Show_Memory(const __int16 const* const* Matrix, const size_t& width, const size_t& height)
{
for (size_t i = 0; i < height; ++i)
{
_STD cout << "==========================================" << NEW_LINE;
_STD cout << "THE BEGINNING " << (Matrix + i) << NEW_LINE;
for (size_t j = 0; j < width; ++j)
{
if (j % 5 == 0 && j > 0)
{
_STD cout << NEW_LINE;
}
_STD cout << ((Matrix + i) + j) << ' ';
}
_STD cout << NEW_LINE;
_STD cout << "==========================================" << NEW_LINE;
_STD cout << NEW_LINE;
}
}
const void Display_Matrix(const __int16 const* const* Matrix, const size_t& width, const size_t& height)
{
HANDLE hndl = GetStdHandle(STD_OUTPUT_HANDLE);
for (size_t i = 0; i < height; ++i)
{
for (size_t j = 0; j < width; ++j)
{
if (j % 5 == 0 && j > 0)
{
_STD cout << NEW_LINE;
}
if (Matrix[i][j] == 1)
{
SetConsoleTextAttribute(hndl, 0x003);
_STD cout << "x";
}
else if (Matrix[i][j] == -1)
{
SetConsoleTextAttribute(hndl, 14);
_STD cout << "o";
}
//_STD cout << Matrix[i][j] << ' ';
}
_STD cout << NEW_LINE;
_STD cout << NEW_LINE;
}
SetConsoleTextAttribute(hndl, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
const void Display_Single_Matrix(const __int16 const* Matrix, const size_t& width)
{
HANDLE hndl = GetStdHandle(STD_OUTPUT_HANDLE);
for (size_t i = 0; i < width; ++i)
{
if (i % 5 == 0 && i > 0)
{
_STD cout << NEW_LINE;
}
if (Matrix[i] == 1)
{
SetConsoleTextAttribute(hndl, 0x003);
_STD cout << "x";
}
else if (Matrix[i] == -1)
{
SetConsoleTextAttribute(hndl, 14);
_STD cout << "o";
}
}
_STD cout << NEW_LINE;
SetConsoleTextAttribute(hndl, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
const void Hopfield(__int16** Matrix, const size_t& width)
{
//RANDOM GENERATOR
std::random_device random; //Will be used to obtain a seed for the random number engine
std::mt19937 generator(random()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
float ** weights{};
int16_t * creature{};
weights = new float*[width];
creature = new int16_t[width];
for (size_t i = 0; i < width; ++i)
{
weights[i] = new float[width];
}
auto delta = [](const size_t& i, const size_t& j) -> const __int16 { if (i == j) { return 1; } else { return 0; }; };
int16_t suma{};
bool if_break = true;
for (size_t i = 0; i < width; ++i)
{
for (size_t j = 0; j < width; ++j)
{
for (size_t k = 0; k < 4; ++k)
{
suma += static_cast<int16_t>(Matrix[k][i] * Matrix[k][j]);
}
weights[i][j] = static_cast<float>((1 - delta(i, j)) * suma);
suma = NULL;
}
}
suma = NULL;
for (size_t i = 0; i < width; ++i)
{
//creature[i] = Matrix[0][i]; //A
//creature[i] = -1 * Matrix[1][i]; //C
creature[i] = Matrix[2][i]; //I
//creature[i] = Matrix[3][i]; //X
}
//creature[2] = -1;
//creature[7] = -1;
//creature[12] = -1;
//creature[15] = -1;
//for (size_t i = 0; i < width; ++i)
//{
// //creature[i] = Matrix[0][i]; //A
// creature[i] = 1; //C
// //creature[i] = Matrix[2][i]; //I
// //creature[i] = Matrix[3][i]; //X
//}
//creature[0] = -1;
//creature[34] = -1;
//creature[4] = -1;
//creature[12] = -1;
//creature[1] = -1;
while (if_break)
{
Display_Single_Matrix(creature, width);
float sum{};
for (size_t i = 0; i < width; ++i)
{
for (size_t j = 0; j < width; ++j)
{
sum += creature[j] * weights[i][j];
}
if (sum > 0)
{
creature[i] = 1;
}
else if (sum < 0)
{
creature[i] = -1;
}
sum = NULL;
}
system("pause");
system("cls");
}
for (size_t i = 0; i < width; ++i)
{
delete[] weights[i];
}
delete[] weights;
delete[] creature;
} | true |
6afe8965052be855cc2783d640ecc044c8381122 | C++ | azakhary/cnc-firmware | /CNCProject.ino | UTF-8 | 8,777 | 2.890625 | 3 | [] | no_license | /*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control
For use with the Adafruit Motor Shield v2
----> http://www.adafruit.com/products/1438
*/
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include <Servo.h>
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);
// Connect a stepper motor with 200 steps per revolution (1.8 degree)
// to motor port #2 (M3 and M4)
Adafruit_StepperMotor *myMotorX = AFMS.getStepper(200, 1);
Adafruit_StepperMotor *myMotorY = AFMS.getStepper(200, 2);
Servo servo;
int lineIndex = 0;
#define LINE_BUFFER_LENGTH 256
char line[ LINE_BUFFER_LENGTH ];
int c = 0; // byte received on the serial port
uint8_t mode = INTERLEAVE;
int speedDelay = 0;
float xTail = 0;
float yTail = 0;
void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("START");
Serial.println("IDLE");
AFMS.begin(); // create with the default frequency 1.6KHz
//AFMS.begin(1000); // OR with a different frequency, say 1KHz
myMotorX->release();
myMotorY->release();
servo.attach(9); // 9 or 10
penUp();
}
void loop() {
processSerialInput();
//executeStep();
}
void processSerialInput() {
if (Serial.available() > 0) {
c = Serial.read();
if(( c == '\n') || (c == '\r')) { // command receiving complete
if ( lineIndex > 0 ) { // Line is complete. Then execute!
line[ lineIndex ] = '\0'; // Terminate string
processIncomingLine( line, lineIndex );
lineIndex = 0;
}
else {
// Empty or comment line. Skip block.
}
} else {
//accumulating byte data in line
if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) {
Serial.println("ERROR:1");
lineIndex = 0;
}
else if ( c >= 'a' && c <= 'z' ) { // Upcase lowercase (making this uppercase)
line[ lineIndex++ ] = c-'a'+'A';
}
else {
line[ lineIndex++ ] = c;
}
}
}
}
void processIncomingLine( char* line, int charNB ) {
int currentIndex = 0;
char buffer[ 64 ];
float params[10];
int paramIndex = 0;
int bufferIndex = 0;
char command = '\0';
while( currentIndex < charNB ) {
char c = line[currentIndex++];
if(currentIndex == 1) {
command = c;
} else {
if(c == ':') { // storing prev param, preparing for next param
if(bufferIndex > 0) {
// store buffer
buffer[bufferIndex] = '\0';
params[paramIndex++] = atof(buffer);
}
bufferIndex = 0;
} else { //reading current param
buffer[bufferIndex++] = c;
}
}
}
if(bufferIndex > 0) {
buffer[bufferIndex] = '\0';
params[paramIndex++] = atof(buffer);
}
processCommand(command, params);
}
void processCommand( char command, float* params ) {
switch(command) {
case 'M':
{
float xSteps = params[0];
float ySteps = params[1];
Serial.println("BUSY");
lineBy(xSteps, ySteps);
delay(200);
Serial.println("IDLE");
}
break;
case 'A':
{
float centerX = params[0];
float centerY = params[1];
float endX = params[2];
float endY = params[3];
boolean dirCW = true;
if(params[4] == 0) dirCW = false;
Serial.println("BUSY");
arc(centerX, centerY, endX, endY, dirCW);
delay(200);
Serial.println("IDLE");
}
break;
case 'U':
// servo up
Serial.println("BUSY");
penUp();
delay(200);
Serial.println("IDLE");
//Serial.println("P");
break;
case 'D':
// servo down
Serial.println("BUSY");
penDown();
Serial.println("IDLE");
//Serial.println("P");
break;
case 'R':
myMotorX->release();
myMotorY->release();
delay(200);
break;
default:
Serial.println("ERROR:2");
Serial.println("IDLE");
}
}
void penUp() {
servo.write(90);
delay(200);
speedDelay = 0;
mode = DOUBLE;
}
void penDown() {
servo.write(70);
delay(200);
speedDelay = 7;
mode = DOUBLE;
}
void lineDebug(float x, float y) {
Serial.print("D:");
Serial.print(x);
Serial.print(":");
Serial.println(y);
}
void lineByMicro(float xSteps, float ySteps) {
lineAlgorythm(xSteps*MICROSTEPS, ySteps*MICROSTEPS, MICROSTEP);
}
void lineByDouble(int xSteps, float ySteps) {
lineAlgorythm(xSteps, ySteps, DOUBLE);
}
void lineAlgorythm(float x, float y, uint8_t mode_override) {
int xSteps = round(x);
int ySteps = round(y);
if(xSteps == 0 && ySteps == 0) return;
//lineDebug(x, y);
uint8_t dirX = BACKWARD;
uint8_t dirY = FORWARD;
int dirMulX = 1;
int dirMulY = 1;
if(xSteps < 0) {
xSteps = -xSteps;
dirX = FORWARD;
dirMulX = -1;
}
if(ySteps < 0) {
ySteps = -ySteps;
dirY = BACKWARD;
dirMulY = -1;
}
byte stepCommand = 0;
if(xSteps > ySteps) {
float minStep = (float)ySteps/(float)xSteps;
float dr = 0;
for(int i = 0; i < xSteps; i++) {
dr+=minStep;
if(dr >= 1) {
myMotorY->onestep(dirY, mode_override);
//lineDebug(0, dirMulY);
dr = dr - 1.0;
} else {
}
myMotorX->onestep(dirX, mode_override);
//lineDebug(dirMulX, 0);
if(mode == DOUBLE) {
delay(speedDelay);
}
}
} else {
float minStep = (float)xSteps/(float)ySteps;
float dr = 0;
for(int i = 0; i < ySteps; i++) {
dr+=minStep;
if(dr >= 1) {
myMotorX->onestep(dirX, mode_override);
dr = dr - 1.0;
} else {
}
myMotorY->onestep(dirY, mode_override);
if(mode == DOUBLE) {
delay(speedDelay);
}
}
}
}
void lineByInterleave(float xSteps, float ySteps) {
lineAlgorythm(xSteps * 2.0, ySteps * 2.0, INTERLEAVE);
}
void lineBy(float xSteps, float ySteps) {
int intX = round(xSteps);
int intY = round(ySteps);
float floatX = xSteps-intX;
float floatY = ySteps-intY;
if(xTail >= 1) {
intX++;
xTail = 0;
}
if(xTail <= -1) {
intX--;
xTail = 0;
}
if(yTail >= 1) {
intY++;
yTail = 0;
}
if(yTail <= -1) {
intY--;
yTail = 0;
}
if(intX != 0 || intY != 0) {
lineByInterleave(intX, intY);
}
if(floatX != 0 || floatY != 0) {
xTail += floatX;
yTail += floatY;
}
}
void lineByForArc(float xSteps, float ySteps) {
int oldSpeed = speedDelay;
speedDelay = 0;
lineByMicro(xSteps, ySteps);
speedDelay = oldSpeed;
/*
if(abs(xSteps) < 20 || abs(ySteps) < 20) {
lineByMicro(xSteps, ySteps);
} else if(abs(xSteps) < 50 || abs(ySteps) < 50) {
lineByInterleave(xSteps, ySteps);
} else {
lineByDouble(round(xSteps), round(ySteps));
}*/
}
/**
* centerX and centerY are relative to current position
* endX and endY are relative to current position
*/
void arc(float centerX, float centerY, float endX, float endY, boolean CW) {
float CM_PER_SEGMENT = 10.0;
int oldDelay = speedDelay;
// get radius
float radius=sqrt(centerX*centerX+centerY*centerY);
if(radius < 20) {
CM_PER_SEGMENT = 4.0;
}
// find the sweep of the arc
float angle1 = atan3(-centerX, -centerY);
float angle2 = atan3(endX-centerX, endY-centerY);
float sweep = angle2-angle1;
if(!CW && sweep < 0) sweep = 2*PI + sweep;
if(CW && sweep > 0) sweep = sweep - 2*PI;
speedDelay = 0;
float len = abs(sweep) * radius;
int i, num_segments = floor( len / CM_PER_SEGMENT );
float nx, ny, nz, angle3, fraction;
nx = 0;
ny = 0;
float currX, currY = 0;
for(i=0;i<num_segments;++i) {
// interpolate around the arc
fraction = ((float)i)/((float)num_segments);
angle3 = ( sweep * fraction ) + angle1;
// find the intermediate position
nx = (centerX + cos(angle3) * radius) - currX;
ny = (centerY + sin(angle3) * radius) - currY;
// make a line to that intermediate position
currX=(centerX + cos(angle3) * radius);
currY=(centerY + sin(angle3) * radius);
lineByForArc(nx,ny);
}
// one last line hit the end
lineByForArc(endX-currX,endY-currY);
speedDelay = oldDelay;
}
// returns angle of dy/dx as a value from 0...2PI
float atan3(float dx,float dy) {
float a=atan2(dy,dx);
if(a<0) a=(PI*2.0)+a;
return a;
}
| true |
a4aacb8ba8572789370fffce81fb1740b13f8626 | C++ | NickGhezzi/GameEngineProject | /AltProject/Game/Source/SceneDonkeyKong/ElevatorObject.cpp | UTF-8 | 1,484 | 2.640625 | 3 | [] | no_license | #include "GamePCH.h"
#include "ElevatorObject.h"
#include "Scenes/BaseScene.h"
ElevatorObject::ElevatorObject(BaseScene* pScene, std::string name, vec3 pos, vec3 rot, vec3 scale, Mesh* pMesh, Material* pMaterial)
: GameObject( pScene, name, pos, rot, scale, pMesh, pMaterial )
{
m_Sensor = nullptr;
}
ElevatorObject::~ElevatorObject()
{
delete m_Sensor;
}
void ElevatorObject::Reset()
{
// TODO_DonkeyKong: Turn off the motor on the joint.
m_pBody->EnableMotor(false);
}
void ElevatorObject::Update(float deltaTime)
{
GameObject::Update( deltaTime );
if( m_pBody == nullptr )
return;
}
void ElevatorObject::CreateJointAndSensor()
{
// TODO_DonkeyKong: Create a prismatic joint that extends from (0 to 1 on the y axis).
// Also create a sensor for the elevator.
// When the player enters the sensor, enable a motor on the joint to move the elevator up.
m_Sensor = new GameObject(m_pScene, "ElevatorSensor", m_Position, vec3(0, 0, 0), vec3(1, 1, 1), nullptr, nullptr);
m_Sensor->CreateBody(false);
uint16* mask[] = { new uint16(PhysicsCategory_Player) };
m_Sensor->GetBody()->AddBox(vec2(2, 1.2), 1, true, 1, PhysicsCategory_Environment, mask);
delete mask[0];
m_pBody->AddPrismaticJoint(m_Sensor->GetBody(), 1, 0, 1000, 20);
m_pBody->EnableMotor(false);
}
void ElevatorObject::EnableMotor()
{
// TODO_DonkeyKong: Turn on the motor on the joint.
m_pBody->EnableMotor(true);
}
| true |
c1ee4066abbde7972f9954f60f6a16d9310f72f9 | C++ | kkoon9/algorithm | /Graph/MST/BOJ1197_MST.cpp | UTF-8 | 2,201 | 3.359375 | 3 | [] | no_license | // 크루스칼 알고리즘
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct edge {
int src, dest, weight;
bool operator <(const edge& rhs) const { // 가중치 비교하기 위한
return weight < rhs.weight;
}
};// 간선 정보
const int MAX = 10000 + 1;
vector<edge> vt;
int parent[MAX];
int v, e, k;
int find(int);
bool merge(int, int);
int main() {
scanf("%d %d", &v, &e);
for (int i = 1; i <= v; i++) {
parent[i] = i;
}// 자기 자신을 부모로 초기화
edge tmp;
for (int i = 0; i < e; i++) {
scanf("%d %d %d", &tmp.src, &tmp.dest, &tmp.weight);
vt.push_back(tmp);
}
sort(vt.begin(), vt.end());// 가중치 오름차순 정렬
for (int i = 0; i < e; i++) {
if (merge(vt[i].src, vt[i].dest)) {
k += vt[i].weight;// 최적의 가중치를 더한다
}// 사이클 없이 합칠 수 있으면 합친다
}
printf("%d\n", k);
return 0;
}
int find(int u) {
if (u == parent[u]) return u;
return parent[u] = find(parent[u]);
}
bool merge(int u, int v) {
u = find(u);
v = find(v);
if (u == v) return false;// 사이클 방지
parent[v] = u;
return true;
}
// 프림 알고리즘
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int MAX = 10000 + 1;
vector<vector<pair<int, int>>> edge;
priority_queue < pair<int, int>, vector<pair<int, int>>, greater< >> pq;
bool visited[MAX];
int v, e, c, k;
void prim(int v);
int main() {
scanf("%d %d", &v, &e);
edge.resize(v + 1);
int x, y, z;
for (int i = 0; i < e; i++) {
scanf("%d %d %d", &x, &y, &z);
edge[x].push_back({ z, y });
edge[y].push_back({ z, x });
}
prim(1);// 1번 정점으로 트리를 만들어 시작
printf("%d\n", k);
return 0;
}
void prim(int v) {
visited[v] = true;
for (auto u : edge[v]) {
if (!visited[u.second]) {
pq.push({ u.first, u.second });
}
} // 정점 v와 연결된 간선을 큐에 담는다
while (!pq.empty()) {
auto w = pq.top();
pq.pop();
if (!visited[w.second]) {
k += w.first;
prim(w.second);
return;
} // 정점이 트리와 연결되지 않았으면 연결한다
} // 가중치가 낮은 간선을 차례대로 탐색하면서
} | true |
d431cecc8d8fee0f94872a4e38004ef376e9dcea | C++ | DyllanM/CS370 | /Framework/src/ImRecipe.h | UTF-8 | 1,433 | 2.90625 | 3 | [] | no_license | /*
* ImRecipe.h
*
* Created on:
* Author: wylder
*/
#ifndef IMRECIPE__H
#define IMRECIPE__H
#include "ImStage.h"
#include <vector>
//A recipe is a list of images and fx to apply to them.
class ImRecipe
{
public:
ImRecipe(ImageId source);
virtual ~ImRecipe();
//Excute the recipe
void Execute();
//Clear all stages except the default stage
void ClearStages();
//Inserts a new stage into the recipe
void InsertStage(ImStage *stage, uint position = -1);
//Removes the stage at the specified location
void RemoveStage(uint stage);
//Moves a stage up or down by the delta
void ModifyStage(uint stage, int delta);
//Enable or disable a stage
void EnableStage(uint stage, bool flag);
//Add another result image to the recipe
void AddResult(ImageId result);
//Returns the stages being applied in this recipe
const std::vector<ImStage *> & GetStages();
//Returns the list of results from the recipe
std::vector<ImageId> & GetResults();
//Returns the source image in the pipeline from previous fx
Image2D * GetSource();
//Returns the image to store the main result in
Image2D * GetResult();
//Return the Id of the source image
ImageId GetId();
private:
//Source image
ImageId mSource;
//Sandbox images
Image2D *mSandbox[2];
//Stages of the recipe
std::vector<ImStage *> mStages;
//Results from stages
std::vector<ImageId> mResults;
};
#endif
| true |
502d2e2185abf8f539c7ca8b1c39704a3159b952 | C++ | ddk992001/khang | /Project Euler/Problem 1.cpp | UTF-8 | 593 | 3.765625 | 4 | [] | no_license | // MULTIPLES OF 3 OR 5
#include <iostream>
using namespace std;
long long sumOfThree(long long n) {
long long index = ((n - 1) / 3);
return index * (2 * 3 + (index - 1) * 3) / 2;
}
long long sumOfFive(long long n) {
long long index = ((n - 1) / 5);
return index * (2 * 5 + (index - 1) * 5) / 2;
}
long long sumOfThreeAndFive(long long n) {
long long index = ((n - 1) / 15);
return index * (2 * 15 + (index - 1) * 15) / 2;
}
long long solve(long long n) {
return sumOfThree(n) + sumOfFive(n) - sumOfThreeAndFive(n);
}
int main() {
cout << "Result: " << solve(1000);
return 0;
}
| true |
dbc7050d7bb4a396f15b0ca8751f6125ff7602b0 | C++ | Cecenio/Programmering-1 | /2019-03-28/övning3.cpp | UTF-8 | 365 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
void areacirkel(double &tal);
int main()
{
double diameter;
cout << "Ange diametern på din cirkel: " << endl;
cin >> diameter;
areacirkel(diameter);
return 0;
}
void areacirkel (double &tal)
{
double area = (3.14*(tal*tal))/4;
cout << "Arean på din cirkel är: " << area << "Cm^2" << endl;
}
| true |
c8991ff840e100f0ff31b5fbdc5a82b39e07e0de | C++ | turingcompl33t/cpp-playground | /boost.asio/streambuf.cpp | UTF-8 | 1,058 | 2.828125 | 3 | [] | no_license | // streambuf.cpp
// Basic operations with boost::asio::streambuf.
//
// Build
// cl /EHsc /nologo /std:c++17 /W4 /I %CPP_WORKSPACE%\_Deps\Catch2 /I %CPP_WORKSPACE%\_Deps\Boost streambuf.cpp
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#define BOOST_ALL_NO_LIB
#include <boost/asio.hpp>
namespace net = boost::asio;
TEST_CASE("boost::asio::streambuf with manual consume()")
{
auto buffer = net::streambuf{};
auto ostream = std::ostream{&buffer};
ostream << "hello";
REQUIRE(buffer.size() == 5);
buffer.consume(5);
REQUIRE(buffer.size() == 0);
}
TEST_CASE("boost::asio::streambuf with both input and output streams")
{
auto buffer = net::streambuf{};
auto ostream = std::ostream{&buffer};
auto istream = std::istream{&buffer};
// output stream writes characters to buffer
ostream << "hello";
REQUIRE(buffer.size() == 5);
// input stream reads and consumes characters from the buffer
auto s = std::string{};
istream >> s;
REQUIRE(s == "hello");
REQUIRE(buffer.size() == 0);
} | true |
8244feb3987f236a8a4251e0e3f550dd5bb4b167 | C++ | zhuohengfeng/Algorithm | /selectSort/Student.h | UTF-8 | 721 | 3.375 | 3 | [] | no_license | //
// Created by hengfeng zhuo on 2019-03-27.
//
#ifndef ALGORITHM_STUDENT_H
#define ALGORITHM_STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int score;
public:
// 重载操作符
bool operator>(const Student& otherStudent){
return this->score > otherStudent.score;
}
bool operator<(const Student& otherStudent){
return this->score < otherStudent.score;
}
// 重载输出运算符<<, 类似java中的toString
friend ostream& operator<<(ostream& os, const Student& student) {
os << "Student: " << student.name << " " << student.score << endl;
return os;
}
};
#endif //ALGORITHM_STUDENT_H
| true |
d5c8db888f2a821316a04899a4d44a6aac77d4df | C++ | Viredery/RegexEngine | /src/SyntacticTree.h | UTF-8 | 869 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef SYNTACTIC_TREE_H_
#define SYNTACTIC_TREE_H_
#include <vector>
#include <string>
#include <memory>
#include "Node.h"
namespace Regex {
class SyntacticTree
{
public:
SyntacticTree(std::string pattern);
~SyntacticTree() = default;
void toString();
void scan();
void constructTree();
std::shared_ptr<Node> getTree();
SyntacticTree(SyntacticTree&) = delete;
SyntacticTree &operator=(const SyntacticTree&) = delete;
void printTree(std::shared_ptr<Node> root);
private:
void handleCombiner(bool flag);
std::size_t handleElementArr(std::size_t index);
std::size_t handleQuantifier(std::size_t index);
std::size_t handleLeftBracket(std::size_t index);
std::string pattern;
std::vector<std::shared_ptr<Node>> nodeList;
std::shared_ptr<Node> root = nullptr;
};
} // namespace Regex
#endif // SYNTACTIC_TREE_H_ | true |
a679b704a00606bd81f2fc46a5b531771d46671e | C++ | WShiBin/Notes | /Languages/C++/Code/preprocessor/03Source_file_inclusion.cpp | UTF-8 | 492 | 2.96875 | 3 | [] | no_license | #if __has_include(<optional>)
#include <optional>
#define have_optional 1
#elif __has_include(<experimental/optional>)
#include <experimental/optional>
#define have_optional 1
#define experimental_optional 1
#else
#define have_optional 0
#endif
#include <iostream>
int main()
{
if (have_optional)
std::cout << "<optional> is present.\n";
int x = 42;
#if have_optional == 1
std::optional<int> i = x;
#else
int *i = &x;
#endif
std::cout << "i = " << *i << '\n';
} | true |
e956b31d024da36ff9bd6965e49c393e56747e0e | C++ | RagingRoosevelt/eecs560-Data_Structures_Labs | /Lab06/hash_open.h | UTF-8 | 825 | 2.875 | 3 | [] | no_license | #ifndef HASH_OPEN_H
#define HASH_OPEN_H
#include <iostream>
using namespace std;
class HashTableOpen
{
private:
// entry structure
struct Node
{
long int value;
bool flag;
Node(long int v, bool f):
value(v), flag(f) {}
};
// for calculating load factor
int prime;
int noEntries;
// table
Node** table;
public:
// constructor and destructor
HashTableOpen(int p);
virtual ~HashTableOpen();
// required functions
void insert(long int value);
bool remove(long int value);
void print();
// helper functions
int hash(long int value, int probe);
double getLoadFactor();
int getLoad();
int getPrime();
int getValueAtKey(int key);
};
#endif
| true |
ec78d065e919ea645a0c52590397c7381c3e9eeb | C++ | atgchan/CPP_LAB | /TrainStation/TrainStation/Queue.h | UTF-8 | 511 | 3.265625 | 3 | [] | no_license | #pragma once
template <class T>
class Queue
{
public:
Queue(int maxSize);
~Queue();
void enQueue(T* t);
T* deQueue();
bool isFull();
bool isEmpty();
int size();
int nextPosition(int n);
T* get(int i)
{
if (i >= mCurrentSize)
{
return nullptr;
}
else
{
int tmp = mFirstPosition;
for (int j = 0; j < i; j++)
{
tmp = nextPosition(tmp);
}
return array[tmp];
}
}
private:
T* array[100];
int mFirstPosition;
int mLastPosition;
int mCurrentSize;
int mMaxSize;
};
| true |
05bccfe62ff03f6b1f00b19118810d58bf11c0d0 | C++ | Lali67/Cpp_Snippet | /06-PR1 Prüfungsaufgaben/02-Pizza/Pizzabude/Pizzabude/pizza.h | UTF-8 | 1,921 | 3.375 | 3 | [
"MIT"
] | permissive | #ifndef PIZZA_H
#define PIZZA_H
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include "topping.h"
using namespace std;
class Pizza {
private:
vector<Topping> toppings;
public:
Pizza ()
{
Topping Tomato_sauce{ "Tomato sauce" };
Topping Cheese{ "Cheese", "G" };
toppings.push_back(Tomato_sauce);
toppings.push_back(Cheese);
}
Pizza (vector<Topping> gew)
{
for (const Topping& t : gew)
toppings.push_back(t);
Topping Tomato_sauce{ "Tomato sauce" };
Topping Cheese{ "Cheese", "G" };
bool tomato_found{ false };
bool cheese_found{ false };
for (const Topping& t : toppings)
if (t == Tomato_sauce) { tomato_found = true; break; }
for (const Topping& t : toppings)
if (t == Cheese) { cheese_found = true; break; }
if (!tomato_found) toppings.push_back(Tomato_sauce);
if (!cheese_found) toppings.push_back(Cheese);
if (toppings.size() == 0)
throw runtime_error("runtime");
}
Pizza (vector<Topping> gew, vector<Topping> ungew)
{
Topping Tomato_sauce{ "Tomato sauce" };
Topping Cheese{ "Cheese", "G" };
bool tomato_found{ false };
bool cheese_found{ false };
for(const Topping& t : ungew)
if (t == Tomato_sauce) { tomato_found = true; break; }
for (const Topping& t : ungew)
if (t == Cheese) { cheese_found = true; break; }
if (!tomato_found) toppings.push_back(Tomato_sauce);
if (!cheese_found) toppings.push_back(Cheese);
vector<bool> in{};
for (int i = 0; i < gew.size(); i++)
{
bool gefunden{ false };
for (int j = 0; j < toppings.size(); j++)
if (gew.at(i) == toppings.at(j)) { gefunden = true; }
in.push_back(gefunden);
}
for (int i = 0; i < in.size(); i++)
if (in.at(i) == false) toppings.push_back(gew.at(i));
if (toppings.size() == 0)
throw runtime_error("runtime");
}
double price() const;
friend ostream& operator << (ostream& out, const Pizza& p);
};
#endif | true |
cfec4a24e7711588d994e6202dbc042524a684a8 | C++ | Youosun/CPP | /log4cpp/Log4cpp/Mylog.cc | UTF-8 | 1,440 | 2.625 | 3 | [] | no_license | #include "Mylog.h"
#include <log4cpp/Priority.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/FileAppender.hh>
#include <sstream>
#include <iostream>
#include <string>
Mylog * Mylog::_pInstance = NULL;
Mylog::Mylog()
: _root(log4cpp::Category::getRoot())
{
log4cpp::PatternLayout * ptLyt1 = new log4cpp::PatternLayout();
ptLyt1->setConversionPattern("%d: [%p]: %m %n");
log4cpp::PatternLayout * ptLyt2 = new log4cpp::PatternLayout();
ptLyt2->setConversionPattern("%d: [%p]: %m %n");
log4cpp::OstreamAppender * OsAppender = new log4cpp::OstreamAppender("OsAppender", &cout);
OsAppender->setLayout(ptLyt1);
log4cpp::FileAppender *fAppender = new log4cpp::FileAppender("fAppender", "Mylog");
fAppender->setLayout(ptLyt2);
_root.addAppender(OsAppender);
_root.addAppender(fAppender);
_root.setPriority(log4cpp::Priority::DEBUG);
}
Mylog::~Mylog()
{
log4cpp::Category::shutdown();
}
Mylog * Mylog::getInstance()
{
if(NULL == _pInstance)
{
_pInstance = new Mylog();
}
return _pInstance;
}
void Mylog::destroy()
{
delete _pInstance;
_pInstance = NULL;
}
void Mylog::err(const char * mesg)
{
_root.error(mesg);
}
void Mylog::info(const char * mesg)
{
_root.info(mesg);
}
void Mylog::fatal(const char * mesg)
{
_root.fatal(mesg);
}
void Mylog::debug(const char * mesg)
{
_root.debug(mesg);
}
void Mylog::warn(const char * mesg)
{
_root.warn(mesg);
}
| true |
5799db1a168d871e5914988da2212a63c6d55127 | C++ | oury-fln/gl_test | /test2/main.cpp | GB18030 | 6,760 | 2.953125 | 3 | [] | no_license | #include <windows.h>
#include <gl/gl.h>
#include <gl/glut.h>
#include "plant.h"
#include "values.h"
/*
* ϰ1
* ľ
*/
//ĻȣĻ߶
GLfloat winWidth,winHeight;
//
GLfloat x1 = 100.0f,y1 = 150.0f;
//δС
GLsizei rsize = 10;
//仯
GLfloat xstep,ystep = xstep = 1.0f;
//һȾ
void ghRender(void);
//һߴıص
void ghReshape(int width,int height);
//һʱص
void ghTimerFuc(int value);
//ʼgl
void initGL();
void main()
{
// ˫ģʽ* RGBɫģʽ
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(width, height);
//һWindowsڣgl
glutCreateWindow("Bounce");
//ʾص
glutDisplayFunc(ghRender);
//windowsڳߴıص
glutReshapeFunc(ghReshape);
//һʱص
glutTimerFunc(33,ghTimerFuc,1);
glutMouseFunc(&OnMouse); //ע¼
glEnable(GL_CULL_FACE);
//glPolygonMode(GL_FRONT, GL_LINE);
//ʼ
initGL();
//ѭȴ¼
glutMainLoop();
}
/*
֪ʶ㣺˫弼
κͼӦþ߱һҪܡԭǽҪƵĻĻȾȻͼ˲佻Ļϡ
˫弼Ҫ;
1㲻ûͼȾϸ
2
ҪAPI
1glutInitDisplayMode(unsigned int mode);
ʼGLUT⣬ôʾģʽ
mode ȡֵ
GLUT_SINGLE ģʽ
GLUT_DOUBLE ˫ģʽ
GLUT_RGBA RGBAɫģʽ
GLUT_RGB RGBɫģʽ
GLUT_DEPTH ָһ32λȻ
GLUT_STENCIL ָһֽ
GLUT_ACCUM ָһۼƻ
GLUT_ALPHA ָһȻ
öֵ߸ glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
2glutCreateWindow(const char *title);
һʹopenGLĴ
title ڵı
3glutDisplayFunc(void (*func)(void));
õǰʾĻصڴƶ(ijڵײܵϲ)ߵglutPostRedisplayʱá
func һΪvoidֵΪvoidĺָ()
ע⣺úΪglFlush(),glutSwapBuffers();
4glutReshapeFunc(void (*func)(int width, int height));
õǰڳߴıĻص
fuc һΪint width, int heightֵΪvoidĺwidthheightʾ仯ڵĿȺ߶ȡ
5glutTimerFunc(unsigned int millis, void (*func)(int value), int value);
һʱصʵָһʱһij
millis صļʱ䣬λΪ
func һΪintֵΪvoidĻص
value ԽֵصIJvalue
6glutMainLoop(void);
GLUT߳ѭѭȴû¼̵꣬ȣ
*/
void initGL()
{
//ƱɫΪɫ
glClearColor(0.0f,0.0f,0.0f,1.0f);
}
/*
ҪAPI
1glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
ָɫɫɫֵalphaֵ
GLclampf ʵΪfloat
red ɫɷ
green ɫɷ
blue ɫɷ
alpha
ȡֵΪ[0.0f,1.0f]
*/
//windowsڳߴıʱ
void ghReshape(int width,int height)
{
if (height == 0)
{
height = 1;
}
//ÿɻ
glViewport(0,0,width,height);
//õǰΪͶӰ
glMatrixMode(GL_PROJECTION);
//õǰΪλ
glLoadIdentity();
winHeight = 600.0f;
winWidth = 800.0f;
//Ϊ250߶Ӧ
/*if(width <= height)
{
winHeight = 250.0f * height / width;
winWidth = 250.0f;
}
else
{
winWidth = 250.0f * width / height;
winHeight = 250.0f;
}
*/
//άϵ
glOrtho(0.0f,winWidth,0.0f,winHeight,1.0f,-1.0f);
//趨ǰΪӾ
glMatrixMode(GL_MODELVIEW);
//
glLoadIdentity();
}
/*
ҪAPI
1glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
ôglĻ
GLintʵΪint GLsizeiʵΪint
x λڴߵľ
y λڴڵײľ루ڴ½ΪԭOpenGLԭ꣨½Ϊԭ㣩
width
height ߶
2glMatrixMode (GLenum mode);
õǰ־֮ľԸľΪ
GLenum ʵΪint
modeȡֵ
GL_MODELVIEW Ӿ
GL_PROJECTION ͶӰ
GL_TEXTURE
3glLoadIdentity (void);
õǰΪλ
4glOrtho (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
ûIJüռķΧ3DѿУΪһάϵһηֱʾx,y,zȡСֵ
GLdoubleʵΪdouble
*/
void ghTimerFuc(int value)
{
//Ļͷ
/*if (x1 > winWidth - rsize || x1 < 0)
{
xstep = -xstep;
}
if (y1 > winHeight - rsize || y1 < 0)
{
ystep = -ystep;
}
if (x1 > winWidth - rsize)
{
x1 = winWidth - rsize - 1;
}
if (y1 > winHeight - rsize)
{
y1 = winHeight - rsize - 1;
}
x1 += xstep;
y1 += ystep;*/
//ػ
glutPostRedisplay();
//ʱص
glutTimerFunc(33,ghTimerFuc,1);
}
/*
ҪAPI
1glutPostRedisplay(void);
֪ͨGLUT»ƣµˢδɣεЧģͬһʱεִֻһ
*/
void ghRender()
{
//ɫ
glClear(GL_COLOR_BUFFER_BIT);
printPlant();
//ֵ
glutSwapBuffers();
//ˢ
glFlush();
}
/*
ҪAPI
1glClear (GLbitfield mask);
ָ
:GLbitfield ʵΪunsigned int
mask ȡֵ
GL_DEPTH_BUFFER_BIT Ȼ
GL_ACCUM_BUFFER_BIT ۻ
GL_STENCIL_BUFFER_BIT ģ建
2glColor3f (GLfloat red, GLfloat green, GLfloat blue);
趨ɫкܶ
3glRectf (GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
һƽΣкܶ
x1,y1 Ͻǵ
x2,y2 ½ǵ
4glutSwapBuffers(void);
˫ʱлĽ
5glFlush();
ˢͼglʱıҪ
*/ | true |
b783a5380295899b1fa6de59f8aeabc260e27615 | C++ | Elathorn/Wozek-widlowy | /KCK/KCK/GraphicManager.cpp | UTF-8 | 3,195 | 2.734375 | 3 | [] | no_license | #include "GraphicManager.h"
#include <SFML/System.hpp>
GraphicManager::GraphicManager()
{
TextureManager* TM = new TextureManager(); //stworzenie managera textur
SI = new ScriptInterpreter();
//stworzenie mechaniki i mapy
mechanic->mapCreator(TM);
//stworzenie okna i jego podzialu
createWindow(WINDOW_WIDTH, WINDOW_HEIGHT);
BORDER_VIEWS_Y_AXIS = mechanic->findShelf("south")->getSprite()->getGlobalBounds().top
+ mechanic->findShelf("south")->getSprite()->getGlobalBounds().height;
BORDER_VIEWS_X_AXIS = mechanic->findShelf("east")->getSprite()->getGlobalBounds().left
+ mechanic->findShelf("east")->getSprite()->getGlobalBounds().width;
_frontView = new FrontView(TM, *_window, BORDER_VIEWS_X_AXIS, BORDER_VIEWS_Y_AXIS);
_topView = new TopView(_frontView, TM, *_window, BORDER_VIEWS_X_AXIS, BORDER_VIEWS_Y_AXIS);
_textBase = new TextBase(*_window, BORDER_VIEWS_X_AXIS);
_forklift = new Forklift(*_window, TM);
}
GraphicManager::~GraphicManager()
{
}
void GraphicManager::runGraphic()
{
while (_window->isOpen())
{
Vector2f mouse(Mouse::getPosition(*_window));
Event event;
while (_window->pollEvent(event))
{
if (event.type == sf::Event::TextEntered)
{
if (event.text.unicode == UNICODE_ENTER_CODE)
{
printCommunicate(SI->interpretUserInput(_textBase->getLastLine()));
}
else
{
_textBase->modifyTextByChar(event.text.unicode);
}
}
if (mouse.x < BORDER_VIEWS_X_AXIS)
_topView->executeEvent(mouse, event);
else
_frontView->executeEvent(mouse, event);
if (event.type == Event::Closed)
_window->close();
}
//czyszczenie
_window->clear();
//rysowanie
_topView->drawAllContent();
_frontView->drawAllContent();
_textBase->drawAllContent();
_forklift->drawAllContent();
//wyswietlanie
_window->display();
}
}
void GraphicManager::printCommunicate(string communicat)
{
_textBase->addText(communicat);
_textBase->addText("");
}
string GraphicManager::getStringFromUser()
{
Event event;
while (true)
{
Vector2f mouse(Mouse::getPosition(*_window));
while (_window->pollEvent(event))
{
if (event.type == sf::Event::TextEntered)
{
if (event.text.unicode == UNICODE_ENTER_CODE)
{
return _textBase->getLastLine();
}
else
{
_textBase->modifyTextByChar(event.text.unicode);
}
}
if (mouse.x < BORDER_VIEWS_X_AXIS)
_topView->executeEvent(mouse, event);
else
_frontView->executeEvent(mouse, event);
if (event.type == Event::Closed)
_window->close();
}
//czyszczenie
_window->clear();
//rysowanie
_topView->drawAllContent();
_frontView->drawAllContent();
_textBase->drawAllContent();
//wyswietlanie
_window->display();
}
}
void GraphicManager::stopGraphic(int time)
{
//czyszczenie
_window->clear();
//rysowanie
_topView->drawAllContent();
_frontView->drawAllContent();
_textBase->drawAllContent();
_forklift->drawAllContent();
//wyswietlanie
_window->display();
sleep(seconds(time));
exit(0);
}
void GraphicManager::createWindow(int Xsize, int Ysize)
{
_window = new RenderWindow(VideoMode(Xsize, Ysize), "KCK");
_window->setFramerateLimit(60);
}
| true |
3545664056ce85f752e9266d4933b8ef03430b05 | C++ | exgs/ft_CPP | /cpp6/ex02/Base.cpp | UTF-8 | 1,079 | 3.3125 | 3 | [] | no_license | #include "Base.hpp"
Base *generate(void)
{
timeval time;
int idx;
gettimeofday(&time, NULL);
idx = rand() % 3;
idx = time.tv_usec % 3; // 0,1,2 중 하나
if (idx == 0)
return (new A);
else if (idx == 1)
return (new B);
else if (idx == 2)
return (new C);
return (new C);
}
void identify_from_pointer(Base *p)
{
A *a; B *b; C *c;
if ((a = dynamic_cast<A *>(p)))
std::cout << "A" << std::endl;
else if ((b = dynamic_cast<B *>(p)))
std::cout << "B" << std::endl;
else if ((c = dynamic_cast<C *>(p)))
std::cout << "C" << std::endl;
}
void identify_from_reference(Base &p)
{
int sum = 7;
try
{
A &a = dynamic_cast<A &>(p);
(void)a;
}
catch(const std::exception& e)
{
sum -= 1;
}
try
{
B &b = dynamic_cast<B &>(p);
(void)b;
}
catch(const std::exception& e)
{
sum -= 2;
}
try
{
C &c = dynamic_cast<C &>(p);
(void)c;
}
catch(const std::exception& e)
{
sum -= 4;
}
if (sum == 1)
std::cout << "A" << std::endl;
else if (sum == 2)
std::cout << "B" << std::endl;
else if (sum == 4)
std::cout << "C" << std::endl;
}
| true |
0a3145d4a586981bc2294c447fa28875a7a91ecc | C++ | devanshdalal/CompetitiveProgrammingAlgos | /dddlll/codechef/CHEFINV/CHEFINV-4733034.cpp | UTF-8 | 3,990 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<map>
typedef long long ll;
typedef unsigned long long ul;
typedef double d;
using namespace std;
const ll mod = 1000000007;
int f[200003],n,m;
int read(int idx){
int val=0;
while(idx>0){
val+=f[idx];
idx-=(idx & -idx);
}
return val;
}
int update(int idx,int val){
while(idx<=n){
f[idx]+=val;
idx+=(idx & -idx);
}
}
struct node
{
int val,ind;
};
struct range
{
int l,r,val;
};
bool comp(node i,node j){
return i.val<j.val;
}
inline ll merge(int arr[], int temp[], int left, int mid, int right)
{
int i, j, k;
ll inv_count = 0;
i = left; /* i is index for left subarray*/
j = mid; /* i is index for right subarray*/
k = left; /* i is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)){
if (arr[i] <= arr[j])
temp[k++] = arr[i++];
else{
temp[k++] = arr[j++];
/*this is tricky -- see above explanation/diagram for merge()*/
inv_count += ll(mid - i);
}
}
while (i <= mid - 1)
temp[k++] = arr[i++];
while (j <= right)
temp[k++] = arr[j++];
for (i=left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
inline ll _mergeSort(int arr[], int temp[], int left, int right)
{
ll mid, inv_count = 0;
if (right > left)
{
mid = (right + left)/2;
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid+1, right);
/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid+1, right);
}
return inv_count;
}
ll mergeSort(int arr[], int array_size)
{
int *temp = (int *)malloc(sizeof(int)*array_size);
return _mergeSort(arr, temp, 0, array_size - 1);
}
int main(){
int i,j,k,l,p,q;
scanf("%d %d",&n,&m);
int b[n+1];
node arr[n+1];
for (i = 1; i <=n; ++i)
{
arr[i].ind=i;
scanf("%d",&p);
b[i-1]=arr[i].val=p;
}
sort(arr+1,arr+n+1,comp);
// for ( i = 1; i <=n; ++i)
// {
// cerr << arr[i].val << " ";
// }cerr << endl;
int a[n+1],prev=mod;
for (i =1,j=0; i <=n; ++i)
{
if (arr[i].val==prev)
{
a[arr[i].ind]=j;
}else{
a[arr[i].ind]=++j;
}
prev=arr[i].val;
}
// for ( i = 1; i <=n; ++i)
// {
// cerr << a[i] << " ";
// }cerr << endl;
ll curr=mergeSort(b,n);
range store[m+1];
vector<int> query[n+1];
vector<int>::iterator it;
for (i=0; i<m; i++)
{
scanf("%d%d",&store[i].l,&store[i].r);
store[i].val=0;
query[store[i].l].push_back(i);
query[store[i].r].push_back(i);
}
for (k=1; k<=n;k++ )
{
for (it=query[k].begin();it!=query[k].end(); ++it)
{
q=*it;
i=store[q].l;
j=store[q].r;
if(i>j)swap(i,j);
if (i==k)
{
int ltai=read(a[i]-1);
int ltaj=read(a[j]-1);
int gtai=k-1-read(a[i]);
int gtaj=k-1-read(a[j]);
store[q].val=ltai - gtai + gtaj - ltaj;
// cerr<<"["<< ltai<<" "<<gtai<<" "<<ltaj<<" "<<gtaj<<endl;
}else{
int ltai=read(a[i]-1);
int ltaj=read(a[j]-1);
int gtai=k-1-read(a[i]);
int gtaj=k-1-read(a[j]);
store[q].val+=-ltai + gtai - gtaj + ltaj;
// cerr<<']'<< ltai<<" "<< gtai<<" "<<ltaj<<" "<<gtaj<<endl;
}
}
update(a[k],1);
// cerr <<k << " "<<a[k] << " ?????????????????" << endl;
// for (i = 1; i <=7; ++i)
// {
// cerr<< f[i] << " ";
// }cerr << endl;
// cerr << "------------------" << endl;
}
for (i = 0; i < m; ++i)
{
// cerr << curr<<" "<<ll(store[i].val)<< endl;
printf("%lld\n",curr+ll(store[i].val) );
}
return 0;
} | true |
3b0b5cf1814135692bf5827e6c8465597a1f8fc2 | C++ | L1l1thLY/DataStructure | /ShellsSort.cpp | UTF-8 | 1,117 | 3.71875 | 4 | [] | no_license | #include <iostream>
void swapInt (int* a, int* b) {
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
}
void newSwap (int *a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void shellInsert (int* arrayToSort, int increment, int count) {
for (int i = increment; i < count; i++) {
if (arrayToSort[i] < arrayToSort[i - increment]) {
int j = i - increment;
int temp = arrayToSort[i];
for ( ; j >= 0 && arrayToSort[j] > temp; j -= increment) {
arrayToSort[j + increment] = arrayToSort[j];
}
arrayToSort[j + increment] = temp;
}
}
}
void shellSort (int* arrayToSort, int* incrementQueue, int t, int lengthOfArray) {
for (int i = 0; i < t; ++i) {
shellInsert (arrayToSort, incrementQueue[i], lengthOfArray);
}
}
int main (void) {
int array[10] = {34,-12,23,45,21,77,12,56,89,1};
int incrementQueue[1] = {1};
shellSort (array, incrementQueue, 1, 10);
for (int i = 0; i < 10; ++i) {
std::cout << array[i] << ",";
}
std::cout << std::endl;
return 0;
}
| true |
93329416f09ed3e52b8202f7d23e3be5ab048c7d | C++ | analgorithmaday/analgorithmaday.github.io | /code/cpp/Stack.cpp | UTF-8 | 734 | 3.1875 | 3 | [
"MIT"
] | permissive | const int SIZE=10;
template<class T>
class Stack
{
T arr[SIZE];
int top_idx;
int top() const { return top_idx; }
bool stack_empty() const { return (top_idx == -1); }
bool stack_full() const { return (top_idx+1 > SIZE-1); }
public:
Stack() {
top_idx = -1;
}
bool push(T val) {
if(stack_full())
return false;
else {
arr[++top_idx] = val;
return true;
}
}
bool pop(T& val) {
if(stack_empty())
return false;
else {
val = arr[top_idx];
top_idx -=1;
return true;
}
}
};
void main()
{
Stack<int> sobj;
int pop_val;
| true |
652f9061db7cfc2ffc2aa5a39c1e69f8e48912f8 | C++ | AnneLivia/Competitive-Programming | /Online Judges/URI/1222/main.cpp | UTF-8 | 1,848 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
int main()
{
// Variable respectively: number of words, maximum lines per page, maximum chars per line
// iterator variable, number of lines, numbers of pages, number of chars, number of spaces and number of words.
int n, l, c, i, nl, np, nc, ns, qtdw;
vector<string>v;
string str;
while(cin >> n >> l >> c) {
v.clear();
while(n--) {
cin >> str;
v.push_back(str);
}
i = nl = np = nc = ns = qtdw = 0;
while(i < (int)v.size()) {
qtdw++; // if amount of words is greater than one get space
if(qtdw > 1)
ns = qtdw - 2; // space is qtdw - 2
if(((nc + (int)v[i].size() + ns) < c) || (nc == 0 && (int)v[i].size() == c)) {
// if number of total char with the new word plus the total of space so far is less than the maximum char per line, or
// in case the word is right exactly the amount of char and the number of chars so far is 0, to avoid infinite loop, okay.
nc+=v[i].size(); // add new number of chars.
i++; // go to the next word
if(i == (int)v.size()) // if there's no next word, then add more one page, there are words left that won't be added
np++;
} else {
// if number of chars is greater using the current word, then, increment line
nl++;
if(nl == l) { // if line is equal to the maximum line per page, increment page
np++;
nl = 0; // line is now 0, to check again
}
ns = qtdw = nc = 0; // 0 to all other variables to count again
}
}
cout << np << endl;
}
return 0;
}
| true |
7e235df3911c7dba8b766632f2530c67680b3b9f | C++ | sepulchralraven/memor-koluchkaa | /programming 1.1/LABS 21/LABA 21.7.cpp | UTF-8 | 862 | 3.1875 | 3 | [] | no_license | // LABA 21.7.cpp
// Дана строка-предложение. Зашифровать ее, поместив вначале все символы, расположенные на четных позициях строки,
// а затем, в обратном, все символы, расположенные на нечетных позициях (например, строка «Программа» превратится в «ргамамроП»).
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
char a[500];
cout << "Введите строку: ";
gets_s(a);
int n, i;
n = strlen(a);
for (i = 1; i < n; i++)
{
if (i % 2 == 0)
{
cout << a[i];
}
}
for (i = n; i >= 1; i--)
{
if (i % 2 != 0)
{
cout << a[i];
}
}
return 0;
} | true |
912948b9ecd6bd880e4c81e859d3703d60ab4fe4 | C++ | dtucker21/CS172 | /HW1.cpp | UTF-8 | 4,886 | 3.046875 | 3 | [] | no_license | // HW1.cpp : Defines the entry point for the console application.
//
//EX01_01: /20
//EX01_02: 20/20
//EX01_03: 18/20
//EX01_04: 19/20
//EX01_05: 18/20
//PT -- Why include stdafx? I don't think you need it.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <string>
using namespace std;
void ex02();
void ex03();
void ex04();
void ex05();
int doubleInt(int a);
int add(int a, int b);
void passByReference(int &a);
void arraySize(int a[], int b);
void arraySearch(int a[], int b);
//PT -- careful here. There shouldn't be any need for global variables for this assignment
int refer = 15; //used in passByReference function later
int const SIZE = 5;
int main()
{
ex02();
ex03();
ex04();
ex05();
return 0;
}
void ex02()
{
bool hasPassedTest = 0;
int x, y;
srand(time(NULL));
x = rand() % 101;
y = rand() % 101;
if (x > y)
cout << "X is greater than Y";
else if (x == y)
cout << "X is equal to Y";
else
cout << "X is less than Y" << endl;
cout << "\nEnter a number of shares: ";
int numberOfShares;
cin >> numberOfShares;
if (numberOfShares > 100)
cout << "numberOfShares is greater than 100" << endl;
int box = 0, book = 0;
cout << "Please enter the width of a box: ";
cin >> box;
cout << "Please enter the width of a book: ";
cin >> book;
if (box % book == 0)
cout << "The box width is divisible by the book width." << endl;
else
cout << "The box width is not divisible by the book width." << endl;
int shelfLife;
cout << "The shelf life for a box of chocolates is (in days): ";
cin >> shelfLife;
int outsideTemp;
cout << "\nThe outside temperature is: ";
cin >> outsideTemp;
if (outsideTemp >= 90)
{
shelfLife = shelfLife - 4;
cout << "\nBecause of the temperature outside, your chocolates will last " << shelfLife << " now, instead of " << shelfLife + 4 << endl;
}
}
void ex03()
{
double area, side, diag;
cout << "Think of a square. The area of this square is: ";
cin >> area;
side = sqrt(area);
diag = side * sqrt(2);
cout << "The diagonal for your square is " << diag << endl;
char yn;
cout << "Enter a y for yes or an n for no: ";
int p = 1;
//PT -- why do you need p for this? This could be simply while (true) since you don't break out until you get the right response.
//PT -- it's also weird to use p = 1, rather than p == 1
while (p = 1)
{
cin >> yn;
if (yn == 'y')
{
cout << "yes" << endl;
break;
}
else if (yn == 'n')
{
cout << "no" << endl;
break;
}
}
char tab = '\t';
string mailingAddress;
cout << "Your mailing address is: ";
cin >> mailingAddress;
getline(cin, mailingAddress);
cout << mailingAddress << endl;
//PT -- missing part (e)
//string e = "";
// -2
}
void ex04()
{
int j = 0;
while (j < 1 || j > 10)
{
cout << "Enter a value between 1 and 10. j = ";
cin >> j;
}
int cubeSum = 0, cube = 0;
for (int h = 0; h <= j; h++)
{
cube = h * h * h;
cubeSum = cubeSum + cube;
if (h == j)
{
cout << cubeSum << endl;
break; //PT -- why break, since it'll exit the while loop anyway.
//PT -1
}
}
int k = 0;
do
{
cout << "* ";
k++;
} while (k < j);
for (int e = 0; e <= 40; e = e + 2)
cout << e << " ";
cout << "\n" << doubleInt(j) << endl;
cout << add(rand(), rand()) << endl;
}
int doubleInt(int a)
{
a = a * 2;
return a;
}
int add(int a, int b)
{
int c = 0;
c = a + b;
cout << "The sum of " << a << " and " << b << " is ";
return c;
}
void passByReference(int &a)
{
a++;
cout << "I changed " << a - 1 << " to " << a;
}
void ex05()
{
int k[SIZE];
//PT -- use j < SIZE here, not 4
for (int j = 0; j <= 4; j++)
{
cout << "Enter an integer: ";
cin >> k[j];
if (j == 4) //PT -- SIZE
{
//PT -- loop these, rather than hard-coding 0,1,2,3,4.
//PT -2
int sum = k[0] + k[1] + k[2] + k[3] + k[4];
int product = k[0] * k[1] * k[2] * k[3] * k[4];
cout << "The sum of the integers you entered is " << sum << endl;
cout << "The product of the integers you entered is " << product << endl;
}
}
arraySize(k, SIZE);
arraySearch(k, SIZE);
}
void arraySize(int a[], int b)
{
for (int j = 0; j < b; j++)
{
cout << a[j] << " ";
}
}
void arraySearch(int a[], int b)
{
int search = 0;
cout << "What value do you want to look for in the array? ";
cin >> search;
bool foundValue[1]; //PT -- why is this an array?
foundValue[0] = 1;
for (int j = 0; j < b; j++)
{
if (search == a[j])
{
cout << "The value you searched for was located at k[" << j << "]" << endl;
foundValue[0] = 0;
break;
}
}
if (foundValue[0] == 1)
cout << "The value could not be found in the array." << endl;
}
| true |
a413f804bd1facab29e07b6ece6575a61c665cbf | C++ | GMHDBJD/leetcode_solution | /62.unique-paths.cpp | UTF-8 | 513 | 2.625 | 3 | [] | no_license | /*
* @lc app=leetcode id=62 lang=cpp
*
* [62] Unique Paths
*/
/*
attention to precision
*/
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int uniquePaths(int m, int n)
{
return Cmn(m - 1 + n - 1, n - 1);
}
int Cmn(int m, int n)
{
n = min(n, m - n);
long t = 1;
long r = 1;
while (n)
{
r *= m;
r /= t;
--m;
--n;
++t;
}
return r;
}
};
| true |
2df5031fb6dffa6a4a6007ef7cdaa5ab13b6fea7 | C++ | hd-code/TicTacToe | /src/models/Game.hpp | UTF-8 | 488 | 2.578125 | 3 | [] | no_license | #pragma once
#include "Board.hpp"
// -----------------------------------------------------------------------------
enum EPlayer { ONE, TWO, NUM_OF_PLAYERS };
struct SGame {
SBoard board;
SPlayer players[NUM_OF_PLAYERS];
EPlayer playerOnTurn;
};
// -----------------------------------------------------------------------------
void initGame(SGame &game);
void setNextPlayerOnTurn(SGame &game);
SPlayer* getWinner(const SGame &game);
bool isGameOver(const SGame &game); | true |
faa9d29e4c9d61812e67999db738afdda337850b | C++ | jpoffline/seqcode | /source/simplecheck.cpp | UTF-8 | 4,260 | 2.96875 | 3 | [] | no_license | #include "simplecheck.h"
// Checks the state of the system after every timestep
void SimpleCheck::checkstate (const double data[], const double time, IntParams ¶ms, Output &output, const double status[]){
// We want to check the following conditions:
// Error in Friedmann equation sufficiently small
// Equation of state is not phantom
// Speed of sound is not superluminal
// Speed of sound is not imaginary
// Perturbations are not ghost-like
// Tensor speed is not superluminal
// Tensor speed is not imaginary
// Tensors are not ghost-like
// Energy density is not negative
// Check the error in the Friedmann equation
if (abs(status[16]) > 1e-9) {
std::stringstream message;
message << "Warning: Relative error in Friedmann equation is larger than 1e-9, time t = " << time;
output.printlog(message.str());
friederror = true;
}
// Check for phantom equation of state for DE
if (status[15] < -1) {
std::stringstream message;
message << "Warning: Dark energy EOS is phantom, time t = " << time;
output.printlog(message.str());
phantom = true;
}
// Check for speed of sound
if (params.getmodel().implementsSOS()) {
double speed2 = params.getmodel().speedofsound2(data);
if (speed2 > 1) {
std::stringstream message;
message << "Warning: Speed of sound is superluminal, time t = " << time;
output.printlog(message.str());
superluminal = true;
} else if (speed2 < 0) {
std::stringstream message;
message << "Warning: Speed of sound is imaginary, time t = " << time;
output.printlog(message.str());
laplacian = true;
}
}
// Check for ghosts
if (params.getmodel().implementsghost()) {
if (params.getmodel().isghost(data)) {
std::stringstream message;
message << "Warning: Perturbations are ghostlike, time t = " << time;
output.printlog(message.str());
ghost = true;
}
}
// Check for speed of sound (tensors)
if (params.getmodel().implementsSOT()) {
double speed2 = params.getmodel().speedoftensor2(data);
if (speed2 > 1) {
std::stringstream message;
message << "Warning: Tensor speed is superluminal, time t = " << time;
output.printlog(message.str());
tsuperluminal = true;
} else if (speed2 < 0) {
std::stringstream message;
message << "Warning: Tensor speed is imaginary, time t = " << time;
output.printlog(message.str());
tlaplacian = true;
}
}
// Check for ghosts (tensors)
if (params.getmodel().implementstensorghost()) {
if (params.getmodel().istensorghost(data)) {
std::stringstream message;
message << "Warning: Tensor perturbations are ghostlike, time t = " << time;
output.printlog(message.str());
tghost = true;
}
}
// Check for negative energy density in DE
// Usually we'll crash from a div/0 error before getting here though!
if (status[13] < 0) {
std::stringstream message;
message << "Warning: Dark energy has negative energy density, time t = " << time;
output.printlog(message.str());
negenergy = true;
}
}
void SimpleCheck::checkfinal (const double data[], const double time, IntParams ¶ms, Output &output, const double status[]){
// We want to check the following conditions:
// Equation of state of dark energy is very close to -1
bool finaleos = false;
// Check for EOS of DE (warn if the EOS is greater than -0.9)
if (status[15] > -0.9) {
output.printlog("Warning: final equation of state of dark energy is > -0.9");
finaleos = true;
}
// Report on any errors received throughout evolution
if (finaleos || friederror || phantom || superluminal || laplacian || ghost || tsuperluminal || tlaplacian || tghost || negenergy) {
output.printlog("");
output.printlog("Warning summary:");
if (finaleos) output.printvalue("FinalEOS", 1);
if (friederror) output.printvalue("FriedError", 1);
if (phantom) output.printvalue("Phantom", 1);
if (superluminal) output.printvalue("Superluminal", 1);
if (laplacian) output.printvalue("Laplacian", 1);
if (ghost) output.printvalue("Ghost", 1);
if (tsuperluminal) output.printvalue("TensorSuperluminal", 1);
if (tlaplacian) output.printvalue("TensorLaplacian", 1);
if (tghost) output.printvalue("TensorGhost", 1);
if (negenergy) output.printvalue("NegativeEnergy", 1);
output.printlog("");
}
}
| true |
276709aae483cfbd6f7a8e311100d3b506e967d3 | C++ | zhaomasha/panda_new | /test/server.cpp | UTF-8 | 434 | 2.625 | 3 | [] | no_license | // Hello World server
#include "panda_zmq.hpp"
#include "panda_head.hpp"
using namespace zmq;
int main (void)
{
// Socket to talk to clients
context_t ctx(16);
socket_t s(ctx,ZMQ_REP);
s.bind ("tcp://*:5556");
while (1) {
char buffer [10];
s.recv(buffer,10);
cout<<"Received Hello"<<endl;
sleep (1); // Do some 'work'
s.send ("World", 5);
}
return 0;
}
| true |
0125f3f23eecb2fe7042c4546a1e8c872bc352dd | C++ | Crasader/GLEXP-Team-Chimple-goa | /goa/Classes/util/Speaker.cpp | UTF-8 | 4,818 | 2.5625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | //
// Speaker.cpp
//
//
// Created by Karim Mirazul on 28-08-2017.
//
//
#include "../util/Speaker.h"
#include "editor-support/cocostudio/CocoStudio.h"
#include "SimpleAudioEngine.h"
#include "../lang/LangUtil.h"
#include "../menu/StartMenuScene.h"
#include "../lang/TextGenerator.h"
#include "ui/CocosGUI.h"
#include "../menu/MenuContext.h"
USING_NS_CC;
Speaker::Speaker()
{
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("audio_icon/audio_icon.plist");
}
Speaker::~Speaker() {
}
/*
string word - set the word in speaker to pronounce ....
position - Vec type,to set position of widget ....
selectionMode - select choice option enable if true or default false
*/
Speaker* Speaker::createSpeaker(string word,Vec2 position,bool selectionMode) {
// checkBox enable status , spearkWord which pronounce by speaker ...
_speakerWord = word;
_isCheckBoxEnable = selectionMode;
// create Speaker object ...
_speaker = Sprite::createWithSpriteFrameName("audio_icon/audio.png");
_speaker->setName("speaker");
addChild(_speaker);
this->setPosition(position);
this->setContentSize(Size(_speaker->getContentSize()));
if (_isCheckBoxEnable) {
// create checkBox object ...
_checkBox = Sprite::createWithSpriteFrameName("audio_icon/check_box.png");
_checkBox->setPosition(Vec2(_speaker->getPositionX()+ _speaker->getContentSize().width / 4,
_speaker->getPositionY()+ _speaker->getContentSize().height / 4));
_checkBox->setName("checkbox");
_checkBox->setVisible(false);
addChild(_checkBox);
//create tickMark and set child in checkBox ...
auto tickMark = Sprite::createWithSpriteFrameName("audio_icon/tick.png");
tickMark->setPosition(Vec2(_checkBox->getContentSize().width/2, _checkBox->getContentSize().height/ 2));
tickMark->setName("tick");
tickMark->setVisible(false);
_checkBox->addChild(tickMark);
}
// create Listner and set to speaker and checkBox ...
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(Speaker::onTouchBegan, this);
listener->onTouchEnded = CC_CALLBACK_2(Speaker::onTouchEnded, this);
listener->setSwallowTouches(false);
cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, _speaker);
//if (_isCheckBoxEnable) {
// cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener->clone(), _checkBox);
//}
return this;
}
/*
It return the word which exist in speaker ...
*/
string Speaker::getStringInSpeaker() {
return _speakerWord;
}
/*
Update the existing word in speaker ...
*/
void Speaker::setStringInSpeaker(string newWord) {
_speakerWord = newWord;
}
/*
Freez the checkBox option after select corrcet option ...
*/
void Speaker::setFreezCheckBoxTickStatus(bool freezSelectionOption) {
_freezSelectionOption = freezSelectionOption;
}
/*
get the status of Freezing the checkBox option ...
*/
bool Speaker::getFreezCheckBoxTickStatus() {
return _freezSelectionOption;
}
/*
it check the word is match with audio or not
if correct then return true else false
*/
bool Speaker::checkAnswer(string word) {
if (_speakerWord.compare(word) == 0)
return true;
return false;
}
bool Speaker::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
auto target = event->getCurrentTarget();
Point locationInNode = target->getParent()->convertToNodeSpace(touch->getLocation());
if (target->getBoundingBox().containsPoint(locationInNode)) {
handleClickEffectOnSpeaker(event);
target->setColor(Color3B(211,211,211));
if(_speakerWord.length() > 0){
MenuContext::pronounceWord(_speakerWord);
}
return true;
}
return false;
}
void Speaker::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event) {
auto target = event->getCurrentTarget();
target->setColor(Color3B::WHITE);
}
/*
method use to set the checkBox is selected or not
if selected then return true or else false
*/
void Speaker::setCheckBoxStatus(bool isOptionSelected) {
_isOptionSelected = isOptionSelected;
_checkBox->getChildByName("tick")->setVisible(isOptionSelected);
}
/*
It return status , the checkbox is selected or not
*/
bool Speaker::getCheckBoxStatus() {
return _isOptionSelected;
}
void Speaker::setCheckBoxVisibility(bool visible) {
if (_isCheckBoxEnable) {
_checkBox->setVisible(visible);
setCheckBoxStatus(false);
}
}
bool Speaker::getCheckBoxVisibility() {
return _checkBox->isVisible();
}
/*
Speaker and checkBox button effects and enabel or disable the checkBox status
*/
void Speaker::handleClickEffectOnSpeaker(cocos2d::Event* event)
{
auto target = event->getCurrentTarget();
if (_isCheckBoxEnable) {
if (getCheckBoxVisibility()) {
setCheckBoxStatus(true);
}
else {
setCheckBoxVisibility(true);
setCheckBoxStatus(false);
}
}
}
| true |
27f5d1f8c3d6727311360b24cc5e223ed3c1273a | C++ | martva383/prog1 | /binfa.cpp | UTF-8 | 3,340 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<new>
#include<vector>
#include<math.h>
using namespace std;
struct elem
{
int adat;
elem* bal;
elem* jobb;
};
int input (vector<int> &t)
{
cout<<"input adatok:\n";
int k=0;
if(t.size()<=1000)
{
for (int i=0; i<t.size() ; i++)
{
k++;
cout<<t[i];
if(k%60==0)
cout<<endl;
}
cout<<endl;
}
else
cout<<"beolvasott adatok szama meghaladja az ezret\n";
}
int elemszam (elem * gyoker)
{
if (gyoker==NULL)
return 0;
if(gyoker->adat==-1)
return elemszam(gyoker->bal)+elemszam(gyoker->jobb);
return elemszam(gyoker->bal)+1+elemszam(gyoker->jobb);
}
int levelek(elem * gyoker)
{
if (gyoker==NULL)
return 0;
if (gyoker->bal==gyoker->jobb)
return levelek(gyoker->bal)+levelek(gyoker->jobb)+1;
return levelek(gyoker->bal)+levelek(gyoker->jobb);
}
void kiir( vector<int> &v, int x)
{
for (int i=0; i<x ; i++)
cout<<v[i]<<" ";
cout<<endl;
}
void utak(elem * gyoker, vector<int> &hossz, vector<int> &v)
{
if (gyoker!=0)
{
if(gyoker->adat!=-1)
v.push_back(gyoker->adat);
if(gyoker->bal==gyoker->jobb)
{
kiir(v, v.size());
hossz.push_back(v.size());
}
utak(gyoker->bal, hossz, v);
utak(gyoker->jobb, hossz, v);
v.pop_back();
}
}
int maxh(vector<int> &v)
{
int maxi= 0;
for (int i=0; i<v.size(); i++ )
if(maxi<v[i])
maxi=v[i];
return maxi;
}
double ossz(vector<int> &v)
{
double ossz=0;
for (int i=0; i<v.size(); i++)
ossz+=v[i];
return ossz;
}
double szoras(vector<int> &v, double x)
{
double osszeg=0;
for (int i=0; i<v.size(); i++)
osszeg+=pow(v[i]-x,2);
return sqrt(osszeg/v.size() );
}
int main ()
{
elem gy;
gy.adat=-1;
gy.bal=gy.jobb=0;
elem *fa=NULL;
fa=&gy;
elem * p=fa;
vector<int> t;
int x;
while (cin>>x)
{
if (x==0)
{
if(p->bal==NULL)
{
elem *uj= new elem;
uj->adat=0;
uj->bal=uj->jobb=0;
p->bal=uj;
p=fa;
}
else
p=p->bal;
}
else
{
if(x==1)
{
if(p->jobb==NULL)
{
elem * uj= new elem;
uj->adat=1;
uj->bal=uj->jobb=0;
p->jobb=uj;
p=fa;
}
else
p=p->jobb;
}
else
{
cerr<<"A bemenet nem 0 vagy 1 volt!";
return 0;
}
}
t.push_back(x);
}
input(t);
vector<int> hossz;
vector<int> v;
int elemdb=elemszam(fa);
cout<<"Elemek szama: "<<elemdb<<endl;
double leveldb=levelek(fa);
cout<<"Levelek szama: "<<leveldb<<endl;
cout<<"A fa agai:\n";
utak(fa, hossz, v);
cout<<"Leghosszabb ut: "<<maxh(hossz)<<endl;
double atlag;
atlag=ossz(hossz)/ leveldb;
cout<<"Agak atlag hossza: "<<atlag<<endl;
cout<<"Atlag hossz szoras: "<<szoras(hossz, atlag)<<endl;
| true |
19810209883b7706bc09eb3ae7f890833585c603 | C++ | du-yang/code_repository | /word_sim/word_sim.cc | UTF-8 | 1,951 | 2.984375 | 3 | [] | no_license | /*
* word_sim.cc
* Copyright (C) 2018 app <app@VM_36_54_centos>
*
*/
#include "word_sim.h"
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <map>
#include <math.h>
using namespace std;
WordSim::WordSim(){
if(Init()){
cout<<"初始化完成"<<endl;
}else{
cout<<"初始化未完成"<<endl;
};
}
bool WordSim::Init(){
ifstream in("./data/word2vec.txt");
if(!in.is_open()){
cout<<"open file error"<<endl;
return false;
}
string key_word;
double tmp_float;
string tmp_line;
vector<double> tmp_vec;
stringstream s_stream;
while(!in.eof()){
getline(in,tmp_line);
s_stream.str(tmp_line);
if(s_stream>>key_word){
while(s_stream>>tmp_float){
tmp_vec.push_back(tmp_float);
}
if(tmp_vec.size()==100){
word2vec[key_word] = tmp_vec;
}
}
//cout<<"key word"<<key_word<<"vec:"<<tmp_vec[0]<<' '<<tmp_vec[1]<<endl;
tmp_vec.clear();
s_stream.clear();
}
in.close();
return true;
}
double WordSim::dotProduct(vector<double>& v1,vector<double>& v2){
double result = 0;
size_t len = v1.size();
for(size_t i=0;i<len;i++){
result=result+v1[i]*v2[i];
}
return result;
}
double WordSim::norm2(vector<double>& vec){
double dotp = dotProduct(vec,vec);
return sqrt(dotp);
}
double WordSim::score(string word1,string word2){
//cout<<"input word:"<<word1<<" and "<<word2<<endl;
vector<double> v1,v2;
map<string,vector<double> >::iterator k;
k = word2vec.find(word1);
if(k!=word2vec.end()){
v1 = k->second;
}else{
return 0;
}
k = word2vec.find(word2);
if(k!=word2vec.end()){
v2 = k->second;
}else{
return 0;
}
return dotProduct(v1, v2) / (norm2(v1) * norm2(v2));
}
| true |
88b4111b2a5d257336ce1b710ab2b86c2cd159dc | C++ | blacksea3/leetcode | /cpp/leetcode/462. minimum-moves-to-equal-array-elements-ii.cpp | WINDOWS-1252 | 447 | 3 | 3 | [] | no_license | #include "public.h"
//16ms, 93.81%
//ҵλ
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
int nsize = nums.size();
int res = 0;
int midv = nums[nums.size() / 2];
for (int i = 0; i < nums.size(); ++i)
res += abs(nums[i] - midv);
return res;
}
};
/*
int main()
{
Solution* s = new Solution();
vector<int> nums = { 1,2 };
cout << s->minMoves2(nums);
return 0;
}
*/
| true |
2b08a52ba1fc11f8acd0d8626aea6f588fbc77c9 | C++ | mjoshi3/CS140 | /lab7/BST2.h | UTF-8 | 4,290 | 3.609375 | 4 | [] | no_license | #ifndef BST2_H
#define BST2_H
#include <iomanip>
#include <iostream>
#include <queue>
#include <vector>
/* BST2.h
Author: Marvin Joshi
Date: November 14,2017
This program reads in a text file that contains numbers that
will be inserted into a binary tree. The program inserts each
node and inserts the node to its correct position. While the
program inserts each key, it sets created a particular ID for
each key. After all numbers are inserted into the tree, the
program prints out the node key, its node ID, the parent ID,
and the left and right subtree IDs, they exist.
*/
using namespace std;
template <class TKey>
class bst {
struct node {
node(int num);
void print();
TKey key;
int nodeId;//id that is created every time a new node is made
node *parent;//parent node
node *link[2];
};
public:
class iterator {
public:
iterator()
{
p = NULL;
}
//default constructor (no argument)
//overloaded operators (++, *, ==, !=)
iterator & operator++();
bool operator!=(const iterator & rhs) const
{
return p != rhs.p;
}
bool operator==(const iterator & rhs) const
{
return p == rhs.p;
}
TKey operator*()
{
return p->key;
}
private:
friend class bst<TKey>;
//constructor (with argument)
iterator(node *np)
{
p = np;
}
node *p;
};
iterator begin()
{
node *m = Troot;
while(m->link[0])
m = m->link[0];
return iterator(m);
}
iterator end()
{
return iterator();
}
public:
bst() { Troot=NULL; id = 0; }//sets the id to 0 everytime it is created
~bst() { clear(Troot); }
bool empty() { return Troot==NULL; }
void insert(TKey &);
//iterator lower_bound(const TKey &);
//iterator upper_bound(const TKey &);
void print_bylevel();
private:
void clear(node *);
node *insert(node *, TKey &);
node *minmax_key(node *, int);
int id;//node Id that gets updated each time
node *Troot;
};
template <class TKey>
bst<TKey>::node :: node(int num = 0 )
{
nodeId = num;//sets each id to 0
parent = NULL;//sets the parent to NULL
}
template<class TKey>
class bst<TKey>::iterator & bst<TKey>::iterator::operator++()
{
bst<TKey>::node * m;
if (p->link[1])
{
p = p->link[1];
while (p->link[0])
{
p = p->link[0];
}
}
else
{
m = p->parent;
while ( m != NULL && p == m->link[1] )
{
p = m;
m = m->parent;
}
p = m;
}
return *this;
}
template <class TKey>
class bst<TKey>::node *bst<TKey>::minmax_key(node *T, int dir) {
if (T)
{
while (T->link[dir])
{
T = T->link[dir];
}
}
return T;
}
template <class TKey>
void bst<TKey>::node::print()
{
cout << setw(3) << key<< setw(4) <<nodeId << " :";//prints out the node id of each node
//output node and parent ID information
// change below to output subtree ID information
if (parent == NULL) cout<< setw(3) << " ROOT ";//prints out ROOT if this is the first node entered
else cout << " P=" << setw(3) << parent->nodeId;//prints out the parent id if otherwise
if (link[0]) cout << " L=" << setw(3) << link[0]->nodeId;//prints the left subtree id
else cout << " ";
if (link[1]) cout << " R=" << setw(3) << link[1]->nodeId;//prints the right subtree id
else cout << " ";
cout << "\n";
}
//bst<TKey>::iterator functions not defined above go here
template <class TKey>
void bst<TKey>::clear(node *T)
{
if (T) {
clear(T->link[0]);
clear(T->link[1]);
delete T;
T = NULL;
}
}
template <class TKey>
void bst<TKey>::insert(TKey &key)
{
Troot = insert(Troot, key);
}
template <class TKey>
class bst<TKey>::node *bst<TKey>::insert(node *T, TKey &key)
{
if (T == NULL) {
id++;//update and set node ID
T = new node(id);
T->key = key;
} else if (T->key == key) {
;
} else {
int dir = T->key < key;
T->link[dir] = insert(T->link[dir], key);
T->link[dir]->parent = T;//sets the parent link
}
return T;
}
//bst<TKey>::lower_bound function goes here
//bst<TKey>::upper_bound function goes here
template <class TKey>
void bst<TKey>::print_bylevel()
{
if (Troot == NULL)
return;
queue<node *> Q;
node *T;
Q.push(Troot);
while (!Q.empty()) {
T = Q.front();
Q.pop();
T->print();
if (T->link[0]) Q.push(T->link[0]);
if (T->link[1]) Q.push(T->link[1]);
}
}
#endif
| true |
10fea27d50560810e7875526c0da0d448b8381f7 | C++ | nscooling/pipeandfilter | /src/Buffer.cpp | UTF-8 | 3,173 | 2.5625 | 3 | [] | no_license | // ----------------------------------------------------------------------------------
// Buffer.cpp
//
// DISCLAIMER:
// Feabhas is furnishing this item "as is". Feabhas does not provide any
// warranty
// of the item whatsoever, whether express, implied, or statutory, including,
// but
// not limited to, any warranty of merchantability or fitness for a particular
// purpose or any warranty that the contents of the item will be error-free.
// In no respect shall Feabhas incur any liability for any damages, including,
// but
// limited to, direct, indirect, special, or consequential damages arising out
// of,
// resulting from, or any way connected to the use of the item, whether or not
// based upon warranty, contract, tort, or otherwise; whether or not injury was
// sustained by persons or property or otherwise; and whether or not loss was
// sustained from, or arose out of, the results of, the item, or any services
// that
// may be provided by Feabhas.
// ----------------------------------------------------------------------------------
#include "Buffer.h"
//###################################################################################
#ifdef BUFFER_WITH_DOCTEST
//#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("[int buffer] testing buffer") {
using testType = unsigned;
constexpr unsigned sz = 32;
constexpr unsigned halfSz = sz / 2;
using theBuffer = Buffer<testType, sz>;
theBuffer buffer;
theBuffer::Error err;
// if a REQUIRE() fails - execution of the test stops.
REQUIRE(buffer.isEmpty() == true);
REQUIRE(buffer.size() == size_t(0));
SUBCASE("added element") {
err = buffer.add(10);
// If a CHECK() fails - the test is marked as failed but the execution continues
CHECK(buffer.isEmpty() == false);
CHECK(buffer.size() == size_t(1));
CHECK(err == theBuffer::OK);
}
SUBCASE("test_initial_get") {
testType data;
err = buffer.get(data);
CHECK(err == theBuffer::EMPTY);
}
SUBCASE("test_initial_putget") {
err = buffer.add(1);
testType data;
err = buffer.get(data);
CHECK(err == theBuffer::OK);
CHECK(true == buffer.isEmpty());
CHECK(buffer.size() == size_t(0));
CHECK(1 == data);
}
SUBCASE("test_initial_buffer_full") {
for (testType i = 0; i < sz; ++i) {
err = buffer.add(i);
CHECK(err == theBuffer::OK);
}
CHECK(buffer.size() == size_t(sz));
err = buffer.add(1);
CHECK(err == theBuffer::FULL);
}
SUBCASE("test_initial_buffer_full_to_empty") {
testType data;
for (testType i = 0; i < sz; ++i) {
err = buffer.add(i);
CHECK(err == theBuffer::OK);
}
for (testType i = 0; i < halfSz; ++i) {
err = buffer.get(data);
CHECK(err == theBuffer::OK);
CHECK(i == data);
}
for (testType i = 0; i < halfSz; ++i) {
err = buffer.add(i+sz);
CHECK(err == theBuffer::OK);
}
for (testType i = 0; i < sz; ++i) {
err = buffer.get(data);
CHECK(err == theBuffer::OK);
CHECK((i+halfSz) == data);
}
err = buffer.get(data);
CHECK(err == theBuffer::EMPTY);
}
}
#include "Event.h"
#endif
| true |
5e88dd485ee78cf56e0c986087f9ed7831b7bbd7 | C++ | AristoChen/LeetCode-AC-Solution | /273. Integer to English Words/Solution.cpp | UTF-8 | 4,082 | 3.640625 | 4 | [] | no_license | /*
Submission Detail:{
Difficulty : Hard
Acceptance Rate : 22.84 %
Runtime : 5 ms
Testcase : 601 / 601 passed
Ranking : Your runtime beats 84.01 % of cpp submissions.
}
*/
class Solution {
public:
string numberToWords(int num) {
if(num == 0)
return "Zero";
string answer = "";
int count = 0;
if(num >= 1000000000)
{
while(num >= 1000000000)
{
count++;
num -= 1000000000;
}
answer += numberLowerThanThousand(count);
count = 0;
answer += "Billion ";
}
if(num >= 1000000)
{
while(num >= 1000000)
{
count++;
num -= 1000000;
}
answer += numberLowerThanThousand(count);
count = 0;
answer += "Million ";
}
if(num >= 1000)
{
while(num >= 1000)
{
count++;
num -= 1000;
}
answer += numberLowerThanThousand(count);
count = 0;
answer += "Thousand ";
}
answer += numberLowerThanThousand(num);
return answer.substr(0, answer.size()-1);
}
string numberLowerThanThousand(int num)
{
string answer = "";
int count = 0, digits = 0;
if(num >= 100)
{
while(num >= 100)
{
count++;
num -= 100;
}
answer += digitsToWord(count);
answer += "Hundred ";
count = 0;
}
//cout << num << " ";
if(num >= 20)
{
digits = num % 10;
num = num - digits;
answer += between20and90(num);
num = digits;
}
//cout << num << " ";
if(num >= 10 && num < 20)
answer += tensToWord(num);
if(num >= 1 && num < 10)
answer += digitsToWord(num);
return answer;
}
string between20and90(int num)
{
switch(num)
{
case 20:
return "Twenty ";
case 30:
return "Thirty ";
case 40:
return "Forty ";
case 50:
return "Fifty ";
case 60:
return "Sixty ";
case 70:
return "Seventy ";
case 80:
return "Eighty ";
case 90:
return "Ninety ";
default:
return "";
}
}
string tensToWord(int num)
{
switch(num)
{
case 10:
return "Ten ";
case 11:
return "Eleven ";
case 12:
return "Twelve ";
case 13:
return "Thirteen ";
case 14:
return "Fourteen ";
case 15:
return "Fifteen ";
case 16:
return "Sixteen ";
case 17:
return "Seventeen ";
case 18:
return "Eighteen ";
case 19:
return "Nineteen ";
default:
return "";
}
}
string digitsToWord(int num)
{
switch(num)
{
case 1:
return "One ";
case 2:
return "Two ";
case 3:
return "Three ";
case 4:
return "Four ";
case 5:
return "Five ";
case 6:
return "Six ";
case 7:
return "Seven ";
case 8:
return "Eight ";
case 9:
return "Nine ";
default:
return "";
}
}
}; | true |
c3c0b26579fbe17835b87017aee6eaded817b6cc | C++ | KPO-2020-2021/zad5_2-AdamDomachowski | /src/goraGran.cpp | UTF-8 | 1,950 | 2.75 | 3 | [
"Unlicense"
] | permissive | #include "goraGran.hh"
/*!
\file
\brief metody klasy goraGran
*/
/*!
konstruktor goraGranu
\param [in] srodek - wspolrzedne srodka goraGranu.
\param [in] a - dlugosc
\param [in] b - szerokosc
\param [in] c - wysokosc
\param [in] nazwa_pliku - nazwa pliku do zapisu wierzcholkicholkow
\return przeszkoda z okreslonymi chechami.
*/
goraGran::goraGran(Vector3D srodek, double a, double b, double c, std::string nazwa_pliku)
{
double tab[]={a,b,c};
wymiary = new Vector3D(tab);
this->srodek_bryly=srodek;
this->nazwa_pliku_bryly = nazwa_pliku;
Vector3D punkt;
punkt[0]=srodek[0]-(a/2);
punkt[1]=srodek[1]+(b/2);
punkt[2]=srodek[2]-(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]-(a/2);
punkt[1]=srodek[1]+(b/2);
punkt[2]=srodek[2]-(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]+(a/2);
punkt[1]=srodek[1]+(b/2);
punkt[2]=srodek[2]-(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]+(a/2);
punkt[1]=srodek[1]+(b/2);
punkt[2]=srodek[2]-(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]+(a/2);
punkt[1]=srodek[1]-(b/2);
punkt[2]=srodek[2]+(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]+(a/2);
punkt[1]=srodek[1]-(b/2);
punkt[2]=srodek[2]-(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]-(a/2);
punkt[1]=srodek[1]-(b/2);
punkt[2]=srodek[2]+(c/2);
wierzcholki.push_back(punkt);
punkt[0]=srodek[0]-(a/2);
punkt[1]=srodek[1]-(b/2);
punkt[2]=srodek[2]-(c/2);
wierzcholki.push_back(punkt);
this->srodek_bryly[0]=srodek[0];
this->srodek_bryly[1]=srodek[1];
this->srodek_bryly[2]=srodek[2]-(c/2);
}
| true |
314302374bbbf0907746e1bec95ca24185374bb8 | C++ | Vinayakk83/Competitive-Programming | /LeetCode/1396_Design_Underground_System.cpp | UTF-8 | 976 | 3.1875 | 3 | [] | no_license | class UndergroundSystem {
public:
unordered_map<int, pair<string, int>> idMap;
unordered_map<string, unordered_map<string, pair<int, int>>> stationMap;
UndergroundSystem() {
}
void checkIn(int id, string stationName, int t) {
idMap[id] = {stationName, t};
}
void checkOut(int id, string stationName, int t) {
auto p = idMap[id];
stationMap[p.first][stationName].first += t - p.second;
stationMap[p.first][stationName].second++;
}
double getAverageTime(string startStation, string endStation) {
auto p = stationMap[startStation][endStation];
return (double)p.first / p.second;
}
};
/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem* obj = new UndergroundSystem();
* obj->checkIn(id,stationName,t);
* obj->checkOut(id,stationName,t);
* double param_3 = obj->getAverageTime(startStation,endStation);
*/
| true |
10e4e6e7f663c96a4e45525d565e7f65d5772be6 | C++ | 595624187/c | /算法实验2/main.cpp | WINDOWS-1252 | 787 | 2.859375 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define N 10
int x[N]={-1};
int abs(int i){
if(i<0) i=-i;
return i;
}
int Place(int k)
{
for(int i=0;i<k;i++)
if(x[i]==x[k]||abs(i-k)==abs(x[i]-x[k]))
return 1;
return 0;
}
void Queen(int n)
{
int k=0;
while(k>=0){
x[k]++;
while(x[k]<n&&Place(k)==1)
x[k]++;
if(x[k]<n&&k==n-1){
for(int i=0;i<n;i++)
cout<<x[i]+1<<" ";
cout<<endl;
return ;
}
if(x[k]<n&&k<n-1)
k++;
else
x[k--]=-1;
}
cout<<""<<endl;
}
int main()
{
int n;
cin>>n;
while(n!=-1){
Queen(n);
for(int i=0;i<n;i++) x[i]=-1;
cin>>n;
}
return 0;
}
| true |
0d91d8ce2483c5ba2ad589cbc83c4ebeff7d5b3b | C++ | Wibben/WCIPEG | /dwitesep09p3.cpp | UTF-8 | 1,123 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
class Point
{
public:
double x,y;
void setVal(double x, double y)
{
this->x = x;
this->y = y;
}
double slope(Point p)
{
return (p.y-y)/(p.x-x);
}
Point midpoint(Point p)
{
Point temp;
temp.setVal((p.x+x)/2,(p.y+y)/2);
return temp;
}
double yInt(double slope)
{
return y-slope*x;
}
};
int main()
{
Point p[3];
double x,y;
for(int i=0; i<5; i++) {
for(int j=0; j<3; j++) {
cin >> x >> y;
p[j].setVal(x,y);
}
Point mid1 = p[0].midpoint(p[1]);
Point mid2 = p[0].midpoint(p[2]);
double slope1 = -1/p[0].slope(p[1]);
double slope2 = -1/p[0].slope(p[2]);
if(isinf(slope1)) x = mid1.x;
else if(isinf(slope2)) x = mid2.x;
else if(slope1-slope2==0) x = (mid1.x-mid2.x)/2;
else x = (mid2.yInt(slope2)-mid1.yInt(slope1))/(slope1-slope2);
y = slope1*x+mid1.yInt(slope1);
printf("%.2f %.2f\n",x,y);
}
return 0;
}
| true |
b1a08a0f7c11f96af508639d487b095f623b594b | C++ | rohitnotani4/CP | /InterviewBit/Bit Manipulation/Divide Integers.cpp | UTF-8 | 701 | 3.21875 | 3 | [] | no_license | /*
https://www.interviewbit.com/problems/divide-integers/
*/
int Solution::divide(int A, int B)
{
int dividend = A, divisor = B;
if(!divisor || (dividend==INT_MIN && divisor==-1))
return INT_MAX;
// Check if both are negative/positive using XOR
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;
long long dvd = labs(dividend);
long long dvs = labs(divisor);
int ans = 0;
while(dvd >= dvs)
{
long long temp = dvs, multiple = 1;
while(dvd >= (temp<<1))
{
temp <<= 1;
multiple <<= 1;
}
dvd -= temp;
ans += multiple;
}
return sign == 1 ? ans : -ans;
}
| true |
1ce5ba9808edf05ae74deba9e74b75e7d1fd3b7b | C++ | pabitrapadhy/cpp_11_examples | /cpp_11_examples/auto.h | UTF-8 | 1,461 | 3.625 | 4 | [] | no_license | //
// auto.h
// cpp_11_examples
//
// Created by Padhy, Pabitra on 16/06/18.
// Copyright © 2018 Padhy, Pabitra. All rights reserved.
//
#ifndef auto_h
#define auto_h
#include <iostream>
using namespace std;
/*
Type Inference:
---------------
Use of 'auto' could also be done with return types of a function, which was introduced in C++14.
That would be covered in the 'cpp_14_examples' project.
*/
namespace PP_CPP11 {
// NOTE:
// something like - auto var; // throws a compilation error
// because compiler can't do type inference.
// 1. Type Inference while defining a variable.
auto var = 11; // int
auto fl = 20.3f; // float
auto dl = 120.4; // double
auto cond = (5 > 2); // bool
// 2. Type Inferece with return types
bool doSomething() {
cout << "hello pabitra\n";
return true;
}
auto boolVal = doSomething(); // fp should have a type bool
// 3. Type Inference with Class members
class Foo {
public:
// auto mVar = 10; // Compilation Error : auto not allowed in non-static class members. (also need to make it const)
static const auto mVal = 10; // NOTE: no benefit in using this
void print() { cout << mVal << endl; }
};
// logic execution
bool execute() {
if (boolVal) {
cout << "returning bool correctly\n";
}
Foo f;
f.print();
return true;
}
}
#endif /* auto_h */
| true |