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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
79fe7a5e761c74fcbfdc610889e0710d1884134f | C++ | ihuei801/leetcode | /MyLeetCode/Leetcode/Spiral Matrix.cpp | UTF-8 | 2,562 | 3.375 | 3 | [] | no_license | //O(mn)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> sol;
int rows = matrix.size();
int cols = rows? matrix[0].size() : 0;
int left = 0;
int right = matrix[0].size() - 1;
int up = 0;
int down = matrix.size() - 1;
while(1){
for(int j = left; j <= right; j++){
sol.push_back(matrix[up][j]);
}
up++;
if(up > down) break;
for(int i = up; i <= down; i++){
sol.push_back(matrix[i][right]);
}
right--;
if(left > right) break;
for(int j = right; j >= left; j--){
sol.push_back(matrix[down][j]);
}
down--;
if(up > down) break;
for(int i = down; i >= up; i--){
sol.push_back(matrix[i][left]);
}
left++;
if(left > right) break;
}
return sol;
}
};
//Sean's solution
//for 6x4 matrix: each row access 5 (6-1) elements and each col access 3 (4-1) elements.
//Then the origianl matrix become 4x2 (6-2)x(4-2) matrix
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int row = matrix.size();
if (!row) return res;
int col = matrix[0].size();
int start_row = 0;
int start_col = 0;
while (row > 0 && col > 0)
{
int max_col = start_col + col - 1;
int max_row = start_row + row - 1;
if (row == 1)
{
for (int j = start_col; j < max_col+1; j++)
res.push_back(matrix[start_row][j]);
return res;
}
if (col == 1)
{
for (int i = start_row; i < max_row+1; i++)
res.push_back(matrix[i][start_col]);
return res;
}
for (int j = start_col; j < max_col; j++)
res.push_back(matrix[start_row][j]);
for (int i = start_row; i < max_row; i++)
res.push_back(matrix[i][max_col]);
for (int j = max_col; j > start_col; j--)
res.push_back(matrix[max_row][j]);
for (int i = max_row; i > start_row; i--)
res.push_back(matrix[i][start_col]);
start_row++;
start_col++;
row -= 2;
col -= 2;
}
return res;
}
}; | true |
aefb16bd7ae7b955a356634a323aaa857eb3298d | C++ | JFishLover/Algorithms | /Dynamic_Prog_Optimal_BST/Dynamic_Prog_Optimal_BST/optimal_BST.cpp | UTF-8 | 1,009 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
void optimal_BST(float p[],float q[],int length,float e[][100],float w[][100],int root[][100]){
for(int i=1;i<=length+1;++i){
e[i][i-1]=q[i-1];
w[i][i-1]=q[i-1];
}
//这个三重循环跟矩阵乘法链很像,分别是长度,起点和分割点
for(int l=1;l<=length;++l){
for(int i=1;i<=length-l+1;++i){
int j=i+l-1;
e[i][j]=pow(2.0,31)-1;
w[i][j]=w[i][j-1]+p[j]+q[j];
for(int k=i;k<=j;++k){
float t=e[i][k-1]+e[k+1][j]+w[i][j];
if(t<e[i][j]){
e[i][j]=t;
root[i][j]=k;
}
}
}
}
}
int main(){
float p[6]={0,0.15,0.1,0.05,0.1,0.2};
float q[6]={0.05,0.1,0.05,0.05,0.05,0.1};
int root[100][100];//存储子树的根节点
float w[100][100];//存储子树的概率和
float e[100][100];//存储最优二叉搜索树的最优值
optimal_BST(p,q,5,e,w,root);
cout<<"构造optimal_BST的最小代价为:"<<e[1][5]<<endl;
cout<<"根节点为"<<root[1][5]<<endl;
system("pause");
return 0;
} | true |
373cc96616a1a69bb1d78184d66c91f76e11b092 | C++ | ReiKishida/KishidaStudio_Front_Line | /プロジェクト/マスター版プロジェクト/source.ver.0.1/scene3DBill.h | SHIFT_JIS | 2,742 | 2.609375 | 3 | [] | no_license | //=============================================================================
//
// 3Dr{[hIuWFNg [scene3DBill.h]
// Author : Ishida Takuto
//
//=============================================================================
#ifndef _SCENE3DBILL_H_
#define _SCENE3DBILL_H_
#include "scene.h"
//*****************************************************************************
// NX`
//*****************************************************************************
class CScene3DBill : public CScene
{
public:
CScene3DBill(int nPriority = 3, CScene::OBJTYPE objType = CScene::OBJTYPE_NONE);
~CScene3DBill();
HRESULT Init(void);
void Uninit(void);
void Update(void);
void Draw(void);
static CScene3DBill *Create(void);
D3DXVECTOR3 GetPos(void) { return m_pos; };
void SetPos(D3DXVECTOR3 pos) { m_pos = pos; };
D3DXVECTOR3 GetPosOld(void) { return m_posOld; }
D3DXVECTOR3 GetSize(void) { return D3DXVECTOR3(m_fWidth, m_fHeight, 0.0f); };
void SetSize(D3DXVECTOR3 size);
float GetWidth(void) { return m_fWidth; };
void SetWidth(float fWidth);
float GetHeight(void) { return m_fHeight; };
void SetHeight(float fHeight);
void SetColor(D3DXCOLOR col);
void AddColor(D3DXCOLOR col);
D3DXCOLOR GetColor(void) { return m_col; };
void BindTexture(LPDIRECT3DTEXTURE9 pTexture);
LPDIRECT3DVERTEXBUFFER9 GetVtxBuff(void) { return m_pVtxBuff; };
void SetVtxBuff(LPDIRECT3DVERTEXBUFFER9 vtxBuff) { m_pVtxBuff = vtxBuff; };
void SetParent(D3DXMATRIX *pParent) { m_pMtxParent = pParent; };
void SetZBuffer(bool bZBuff, D3DCMPFUNC cmpFunc = D3DCMP_LESSEQUAL);
void SetLighting(bool bLighting) { m_bLighting = bLighting; };
bool GetDisp(void) { return m_bDisp; }
void SetDisp(bool bDisp) { m_bDisp = bDisp; }
bool GetAddDraw(void) { return m_bAddDraw; }
void SetAddDraw(bool bAddDraw) { m_bAddDraw = bAddDraw; }
bool Collision(D3DXVECTOR3 pos, float fRadius);
protected:
private:
LPDIRECT3DTEXTURE9 m_pTexture; // eNX`ւ̃|C^
LPDIRECT3DVERTEXBUFFER9 m_pVtxBuff; // _obt@ւ̃|C^
D3DXMATRIX m_mtxWorld; // [h}gbNX
D3DXMATRIX *m_pMtxParent; // ẽ}gbNX
D3DXVECTOR3 m_pos; // |S̈ʒu
D3DXVECTOR3 m_posOld; // Öʒu
float m_fWidth; // _X̋
float m_fHeight; // _Y̋
D3DXCOLOR m_col; // F
D3DCMPFUNC m_cmpFunc; // Zobt@̐ݒp
bool m_bZBuffer; // Zobt@̐ݒ邩ǂ
bool m_bLighting; // CgL
bool m_bDisp; // `悷邩ǂ
bool m_bAddDraw; // Z邩ǂ
};
#endif | true |
ac1526cfc6d4159ac940dbb32ba0b6a5919a1db5 | C++ | zerominh/Caro | /src/connect.h | UTF-8 | 2,328 | 2.6875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include "window.h"
#include "text.h"
#include "utils.h"
#include <ctime>
#include <cmath>
enum End{
hoaco, player1, player2
};
enum Checker{
O = -1, _ = 0, X = 1
};
enum Mode {
playerVsPlayerMode, playerVsCompterMode
};
struct Cell{
int row = -1;
int column = -1;
};
class Connect{
public:
static const int NUM_CELL_WIDTH = 18;
static const int NUM_CELL_HEIGHT = 18;
static const int CELL_W = 30;
static const int CELL_H = 30;
static const int WINDOW_WIDTH = CELL_W*NUM_CELL_WIDTH;
static const int WINDOW_HEIGHT = CELL_H*NUM_CELL_HEIGHT;
long FIGHT[8] = {0, 3, 24, 192, 1536, 1288, 98304, 786432};
long DEFENCE[8] = {0, 1, 9, 81, 729, 6561, 59049, 472392};
static const int COLUMN = NUM_CELL_WIDTH;
static const int ROW = NUM_CELL_HEIGHT;
static const int TIME_ELAPSE = 5;
public:
Connect();
~Connect();
inline int** getTable() const { return _table;}
bool isValidCell(const Cell & c) const;
inline void changeChecker() { _checker *= -1;}
void update(const Cell & c);
bool isEndGame();
void showResult(Window & window) const;
void play(Window & window);
void playVsPlayer(Window & window);
void playVsComputer(Window & window);
void showResultPlayerVsPlayerMode(Window & window) const;
void showResultPlayerVsComputerMode(Window & window) const;
private:
void generateCell(Cell &);
long caculateFight(int, int);
long caculateDefence(int, int);
long TCDuyetDoc(int, int);
long TCDuyetNgang(int, int);
long TCDuyetCheoXuoi(int, int);
long TCDuyetCheoNguoc(int, int);
long PNDuyetDoc(int, int);
long PNDuyetNgang(int, int);
long PNDuyetCheoXuoi(int, int);
long PNDuyetCheoNguoc(int, int);
private:
bool init();
bool checkCol(const int & row, const int & column) const;
bool checkRow(const int & row, const int & column) const;
bool checkDia1(const int & row, const int & column) const;
bool checkDia2(const int & row, const int & column) const;
public:
int mode = playerVsPlayerMode;
private:
int ** _table = nullptr;
int _checker = X;
int _endResult = hoaco;
std::vector<Cell> _history;
std::vector<Cell> _historyPlayer1;
std::vector<Cell> _historyPlayer2;
int _checkerOfPlayer = X;
int _checkerOfComputer = O;
};
| true |
f7a8f402639c73a997389b25a9fb6330b43347db | C++ | nznaza/SIM800L | /examples/GPRS_SMSread/GPRS_SMSread.ino | UTF-8 | 1,615 | 2.84375 | 3 | [
"MIT"
] | permissive | /*
GPRS SMS Read
This sketch is used to test seeeduino GPRS_Shield's reading SMS
function.To make it work, you should insert SIM card
to Seeeduino GPRS Shield,enjoy it!
There are two methods to read SMS:
1. GPRS_LoopHandle.ino -> in order to recieve "+CMTI: "SM""
may be you need to send this command to your shield: "AT+CNMI=2,2,0,0,0"
2. GPRS_SMSread.ino -> you have to check if there are any
UNREAD sms, and you don't need to check serial data continuosly
create on 2015/05/14, version: 1.0
by op2op2op2(op2op2op2@hotmail.com)
*/
#include <GPRS_Shield_Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#define PIN_TX 7
#define PIN_RX 8
#define BAUDRATE 9600
#define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;
char phone[16];
char datetime[24];
GPRS gprsTest(PIN_TX,PIN_RX,BAUDRATE);//RX,TX,PWR,BaudRate
void setup() {
Serial.begin(9600);
while(!gprsTest.init()) {
Serial.print("init error\r\n");
delay(1000);
}
delay(3000);
Serial.println("Init Success, please send SMS message to me!");
}
void loop() {
messageIndex = gprsTest.isSMSunread();
if (messageIndex > 0) { //At least, there is one UNREAD SMS
gprsTest.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
//In order not to full SIM Memory, is better to delete it
gprsTest.deleteSMS(messageIndex);
Serial.print("From number: ");
Serial.println(phone);
Serial.print("Datetime: ");
Serial.println(datetime);
Serial.print("Recieved Message: ");
Serial.println(message);
}
}
| true |
29f04f977bf7e5490cb1a0f22cbbbc2882491db5 | C++ | cmbruns/opencmbcv | /cppsrc/include/geom2d.hpp | UTF-8 | 9,202 | 3.40625 | 3 | [] | no_license | #ifndef CMBCV_GEOM2D_HPP_
#define CMBCV_GEOM2D_HPP_
#include <cassert>
#include <iostream>
// These classes are intended to be wrapped using boost.python,
// with an efficient C++ API and a nearly syntactically identical python API
namespace cmbcv {
// "floats" in python are C++ doubles. So use double.
typedef double real_t;
// vec_t<int> class defines indexing, equality, and printing for use
// by other classes.
// But reuse will be by containment, rather than inheritance.
template<unsigned int DIM>
class vec_t
{
public:
typedef real_t value_type;
typedef value_type* iterator;
typedef value_type const * const_iterator;
protected:
value_type data[DIM];
public:
unsigned int size() const {return DIM;}
const value_type& operator[](int ix) const {
assert(ix >= 0);
assert(ix < DIM);
return data[ix];
}
value_type& operator[](int ix) {
assert(ix >= 0);
assert(ix < DIM);
return data[ix];
}
bool operator!=(const vec_t& rhs) const {
const vec_t& lhs = *this;
// There exist tricks to force the compiler to unroll these loops,
// but that's probably overkill at this point.
// (see SimTK Vec.h Impl:: namespace)
for (unsigned int ix(0); ix < size(); ++ix)
if (lhs[ix] != rhs[ix]) return true;
return false;
}
bool operator==(const vec_t& rhs) const {
const vec_t& lhs = *this;
return !(lhs != rhs);
}
std::ostream& print(std::ostream& os) const
{
const vec_t& v = *this;
os << "~[";
for (unsigned int ix(0); ix < size(); ++ix) {
if (ix > 0) os << ", ";
os << v[ix];
}
os << "]";
return os;
}
// begin and end methods help with boost python indexing
const_iterator begin() const {return &data[0];}
iterator begin() {return &data[0];}
const_iterator end() const {return &data[DIM];}
iterator end() {return &data[DIM];}
};
class vec2_t
{
public:
typedef vec_t<2> vector_type;
typedef vector_type::value_type value_type;
typedef vector_type::iterator iterator;
typedef vector_type::const_iterator const_iterator;
// Use union to permit specifying content by members x, y
union {
vector_type vec;
struct { value_type x, y; };
};
vec2_t(value_type x, value_type y) : x(x), y(y) {}
unsigned int size() const {return vec.size();}
value_type& operator[](int ix) {return vec[ix];}
const value_type& operator[](int ix) const {return vec[ix];}
bool operator!=(const vec2_t& rhs) const {
return this->vec != rhs.vec;
}
bool operator==(const vec2_t& rhs) const {
return this->vec == rhs.vec;
}
std::ostream& print(std::ostream& os) const {
return vec.print(os);
}
// begin and end methods help with boost python indexing
const_iterator begin() const {return vec.begin();}
iterator begin() {return vec.begin();}
const_iterator end() const {return vec.end();}
iterator end() {return vec.end();}
};
class vec3_t
{
public:
typedef vec_t<3> vector_type;
typedef vector_type::value_type value_type;
typedef vector_type::iterator iterator;
typedef vector_type::const_iterator const_iterator;
// Use union to permit specifying content by members x, y, z
union {
vector_type vec;
struct { value_type x, y, z; };
};
vec3_t(value_type x, value_type y, value_type z) : x(x), y(y), z(z) {}
unsigned int size() const {return vec.size();}
value_type& operator[](int ix) {return vec[ix];}
const value_type& operator[](int ix) const {return vec[ix];}
bool operator!=(const vec3_t& rhs) const {
return this->vec != rhs.vec;
}
bool operator==(const vec3_t& rhs) const {
return this->vec == rhs.vec;
}
std::ostream& print(std::ostream& os) const {
return vec.print(os);
}
vec3_t cross(const vec3_t& rhs) const {
const vec3_t& lhs = *this;
return vec3_t(
lhs[1]*rhs[2] - lhs[2]*rhs[1],
lhs[2]*rhs[0] - lhs[0]*rhs[2],
lhs[0]*rhs[1] - lhs[1]*rhs[0]);
}
};
// forward declaration
class line2_t;
// define homogeneous_point2_t before point2_t to ease making conversion
// homogeneous_point2_t => point2_t explicit (expensive), but
// point2_t => homogeneous_point2_t implicit (cheap)
class homogeneous_point2_t
{
public:
typedef vec_t<3> vector_type;
typedef vector_type::value_type value_type;
typedef vector_type::iterator iterator;
typedef vector_type::const_iterator const_iterator;
// Use union to permit specifying content by members x, y, w
union {
vector_type vec;
struct { value_type x, y, w; };
};
homogeneous_point2_t(value_type x, value_type y, value_type w = 1.0)
: x(x), y(y), w(w) {}
/// Returns the line joining two points
line2_t line(const homogeneous_point2_t& rhs) const;
unsigned int size() const {return asVec3().size();}
value_type& operator[](int ix) {return asVec3()[ix];}
const value_type& operator[](int ix) const {return asVec3()[ix];}
bool operator!=(const homogeneous_point2_t& rhs) const {
return asVec3() != rhs.asVec3();
}
bool operator==(const homogeneous_point2_t& rhs) const {
return asVec3() == rhs.asVec3();
}
std::ostream& print(std::ostream& os) const {
return asVec3().print(os);
}
// interconversion with vec3 to ease use of cross product for intersection
// Q: Is this constructor more expensive than a reinterpret cast?
// A: Probably not when called as the return value in a method.
explicit homogeneous_point2_t(const vec3_t& vec3)
: x(vec3.x), y(vec3.y), w(vec3.z) {}
protected:
const vec3_t& asVec3() const {
return reinterpret_cast<const vec3_t&>(*this);
}
vec3_t& asVec3() {
return reinterpret_cast<vec3_t&>(*this);
}
};
// point2_t describes pixel coordinates in an image.
// point2_t represents a column vector.
class point2_t : public vec2_t {
public:
point2_t(value_type x, value_type y) : vec2_t(x,y) {}
// point2 => homogeneous_point2 is cheap;
// the reverse is not.
explicit point2_t(const homogeneous_point2_t& hp)
: vec2_t(hp.x/hp.w, hp.y/hp.w) {}
// implicit conversion to homogeneous_point2_t is cheap
operator homogeneous_point2_t() const {
return homogeneous_point2_t(x, y, 1.0);
}
};
class line2_t {
public:
typedef vec_t<3> vector_type;
typedef vector_type::value_type value_type;
typedef vector_type::iterator iterator;
typedef vector_type::const_iterator const_iterator;
union {
vector_type vec;
// equation of the line ax + by + c = 0
struct { value_type a, b, c; };
};
line2_t(value_type a, value_type b, value_type c)
: a(a), b(b), c(c) {}
value_type& operator[](int ix) {return asVec3()[ix];}
const value_type& operator[](int ix) const {return asVec3()[ix];}
/// Compute the point of intersection of two lines
homogeneous_point2_t intersection(const line2_t& rhs) const {
const line2_t& lhs = *this;
// abuse vec3 cross product to get answer
vec3_t v = lhs.asVec3().cross(rhs.asVec3());
return homogeneous_point2_t(v);
}
// interconversion with vec3 to ease use of cross product for intersection
// Q: Is this constructor more expensive than a reinterpret cast?
// A: Probably not when called as the return value in a method.
explicit line2_t(const vec3_t& vec3)
: a(vec3.x), b(vec3.y), c(vec3.z) {}
protected:
const vec3_t& asVec3() const {
return reinterpret_cast<const vec3_t&>(*this);
}
vec3_t& asVec3() {
return reinterpret_cast<vec3_t&>(*this);
}
};
std::ostream& operator<<(std::ostream& os, const cmbcv::point2_t& p);
} // namespace cmbcv
#endif // CMBCV_GEOM2D_HPP_
| true |
8bc628deec77f44cac206b967979354b4e71b8b6 | C++ | logosky/cpp | /mysql/mysql_pool.h | UTF-8 | 2,663 | 2.609375 | 3 | [] | no_license | #ifndef __MYSQL_POOL_H__
#define __MYSQL_POOL_H__
#include "mysql_comm.h"
#include "mysql_interface.h"
#include "mysql_connect.h"
#include <list>
#include <boost/thread.hpp>
#pragma once
namespace demo
{
namespace mysql
{
enum DBType
{
dbt_MySQL,
dbt_MSSQL
};
class MysqlPool
{
public:
MysqlPool(DBType dbt, char* strPath, char* strUser, char* strPwd, int PoolSize);
virtual ~MysqlPool(void);
/** @brief 从池中取出一个数据库连接,需调用CloseConn()释放
*
* demo::mysql::MysqlPool::GetConn
* Access: public
*
* @return : IConnection *
*/
IConnection * GetConn();
/** @brief 从池中取出一个数据库连接,需调用CloseConn()释放
*
* demo::mysql::MysqlPool::GetConn
* Access: public
*
* @param:
* [in] read_timeout 请求MySQL的超时时间,单位为秒
* 在MySQL客户端库代码层的超时时间是 read_timeout * 3
* 即MySQL客户端代码会重试三次,
* 具体参考文档:
* http://dev.mysql.com/doc/refman/5.7/en/mysql-options.html
* 关于MYSQL_OPT_READ_TIMEOUT 说明
*
* @return : IConnection *
*/
IConnection * GetConn(unsigned int read_timeout);
/** @brief 从池中取出一个初始化成功的数据库连接
*
* demo::mysql::MysqlPool::GetConnUseful
* Access: public
*
* @param
* [in]:
*
* [out]:
*
* @return : 成功时返回 IConnection *,否则返回 NULL
*/
IConnection *GetConnUseful();
/** @brief 从池中取出一个初始化成功的数据库连接,并设置读取的超时时间,单位为秒
*
* demo::mysql::MysqlPool::GetConnUseful
* Access: public
*
* @param
* [in]:read_timeout 读取的超时时间
*
* @return : 成功时返回 IConnection *,否则返回 NULL
*/
IConnection *GetConnUseful(unsigned int read_timeout);
/** @brief 将一个数据库连接归还到池中
*
* demo::mysql::MysqlPool::CloseConn
* Access: public
*
* @param IConnection *
* @return : void
*/
void CloseConn(IConnection *);
const int GetTotalCount();
private:
boost::mutex m_Mutex;
typedef std::list<IConnection *> ConnList;
ConnList m_Conns;
// 注释掉,避免编译警告未使用变量
// int m_PoolSize;
// DBType m_DBType;
char* m_Path;
char* m_User;
char* m_Pwd;
volatile int m_TotalCount;
};
}
}
#endif
| true |
17d5515bbc019e639976bf0c01b2e14339e3a83c | C++ | BielskiGrzegorz/GraMUD | /GameManager.cpp | UTF-8 | 1,612 | 2.671875 | 3 | [] | no_license | #include "GameManager.h"
#include <conio.h>
#include <Windows.h>
#include <iostream>
#include "Npc.h"
using namespace std;
void gotoxy(int x, int y)
{
COORD cord;
cord.X = x;
cord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cord);
}
void GameManager::wczytajMape(string s)
{
ifstream wczyt(s);
for (int i = 0; i<1000; i++)
{
for (int j = 0; j<10000; j++)
{
wczyt >> mapa[i][j];
}
}
wczyt.close();
}
void GameManager::wyswietlMape(int x, int y)
{
char s;
s = 219;
for (int i = 0; i < 40; i++)
{
for (int j = 0; j < 40; j++)
{
if (mapa[i][j] == '.')
cout << ' ';
else
cout << s;
}
cout << endl;
}
}
void GameManager::poruszanie(int *x, int *y,Postac *postac)
{
Npc npc;
npc.wczytaj();
string tabnpc[40][40];
for (int i = 0; i < 40; i++)
{
for (int j = 0; j < 40; j++)
{
tabnpc[i][j] = " ";
}
}
tabnpc[1][1] = "Andrzej";
char c='b';
int _x, _y;
for (;;)
{
_x = *x;
_y = *y;
gotoxy(0, 0);
wyswietlMape(*x, *y);
gotoxy(_y, _x);
cout << ' ';
switch (c)
{
case 'a':
{
if (mapa[*x][*y - 1] != 'x')
*y = *y - 1;
}
break;
case 'd':
{
if (mapa[*x][*y + 1] != 'x')
*y = *y + 1;
}
break;
case 'w':
{
if (mapa[*x - 1][*y] != 'x')
*x = *x - 1;
}
break;
case 's':
{
if (mapa[*x + 1][*y] != 'x')
*x = *x + 1;
}
break;
case 'p':
{
postac->x = *x;
postac->y = *y;
postac->zapisz();
}
break;
}
if (tabnpc[*x][*y] != " ")
{
gotoxy(41, 2);
npc.rozmowa(tabnpc[*x][*y]);
}
gotoxy(*y, *x);
cout << 'O';
c = _getch();
}
}
| true |
bd24e0231e2d276116bce5d685261ab8429eea5c | C++ | lyonb96/Noble | /Source/Core/Texture2D.h | UTF-8 | 802 | 2.953125 | 3 | [] | no_license | #pragma once
#include "Asset.h"
#include <bgfx/bgfx.h>
namespace Noble
{
/**
* 2D Texture assets
*/
class Texture2D : public Asset
{
public:
/**
* Default constructor
*/
Texture2D();
/**
* Returns the corresponding asset type for 2D textures
*/
virtual const AssetType GetType() const override { return AssetType::AT_TEXTURE2D; }
/**
* Returns the handle to the loaded texture
*/
bgfx::TextureHandle GetTextureHandle() { return m_TexHandle; }
protected:
/**
* Creates the texture from the given data stream
*/
virtual void CreateFromBuffer(BitStream& data) override;
/**
* Frees memory and releases resources for the texture
*/
virtual void Destroy() override;
private:
// Texture Handle
bgfx::TextureHandle m_TexHandle;
};
} | true |
eeea88d6e3aefe00de4180ccaebe180029197faa | C++ | ugurcan-sonmez-95/HackerRank | /Algorithms/Strings/HackerRank_in_a_String/main.cpp | UTF-8 | 775 | 3.359375 | 3 | [
"MIT"
] | permissive | // HackerRank_in_a_String! - Solution
#include <iostream>
void hackerrankInString(int query_count, std::string &s) {
std::cin >> query_count;
while (query_count) {
std::cin >> s;
const std::string s1 = "hackerrank";
int count{}, temp{};
for (int i{}; i < s1.size(); i++) {
for (int j{temp}; j < s.size(); j++) {
if (s[j] == s1[i]) {
count++;
temp = j+1;
break;
}
}
}
const std::string ans = (count == 10 ? "YES" : "NO");
std::cout << ans << '\n';
query_count--;
}
}
int main() {
int query_count;
std::string s;
hackerrankInString(query_count, s);
return 0;
} | true |
b2e5a783cae81f0890c5097fb0659991ccf3f43d | C++ | chx2502/LeetCode | /LeetCode_1871/main.cpp | UTF-8 | 1,801 | 3.484375 | 3 | [] | no_license | /*
给你一个下标从 0 开始的二进制字符串 s 和两个整数 minJump 和 maxJump 。一开始,你在下标 0 处,且该位置的值一定为 '0' 。当同时满足如下条件时,你可以从下标 i 移动到下标 j 处:
i + minJump <= j <= min(i + maxJump, s.length - 1) 且
s[j] == '0'.
如果你可以到达 s 的下标 s.length - 1 处,请你返回 true ,否则返回 false 。
输入:s = "011010", minJump = 2, maxJump = 3
输出:true
解释:
第一步,从下标 0 移动到下标 3 。
第二步,从下标 3 移动到下标 5 。
输入:s = "01101110", minJump = 2, maxJump = 3
输出:false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-vii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool canReach(string s, int minJump, int maxJump) {
int length = (int)s.length();
vector<int> pre(length, 0);
vector<int> dp(length, 0);
dp[0] = 1;
for (int i = 0; i < minJump; i++) pre[i] = 1;
int left, right, total;
for (int i = minJump; i < length; i++) {
if (s[i] == '0') {
left = i - maxJump;
right = i - minJump;
if (left > 0) total = pre[right] - pre[left-1];
else total = pre[right];
if (total > 0) dp[i] = 1;
}
pre[i] = pre[i-1] + dp[i];
}
return dp[length-1] > 0;
}
};
int main() {
Solution s;
string str = "0000000000";
int minJump = 8;
int maxJump = 8;
bool result = s.canReach(str, minJump, maxJump);
cout << result << endl;
} | true |
98a76eac8684f71e72bd41000e5363144c13e261 | C++ | lajthabalazs/arduino | /projects/rgb_led_stripe/rgb_led_stripe.ino | UTF-8 | 1,418 | 3.234375 | 3 | [] | no_license | int r = 0;
int g = 0;
int b = 0;
int RED_PIN = 11;
int GREEN_PIN = 9;
int BLUE_PIN = 10;
String message;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
readSerial();
analogWrite(RED_PIN, r);
analogWrite(GREEN_PIN, g);
analogWrite(BLUE_PIN, b);
delay(10);
}
void readSerial() {
while (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
message += c; //makes the string readString
delay(5); //slow looping to allow buffer to fill with next character
}
if (message.length() > 0) {
Serial.println(message); //so you can see the captured string
int commaPosition = message.indexOf(',');
if(commaPosition != -1) {
r = (message.substring(0,commaPosition)).toInt();
int secondCommaPosition = commaPosition + 1 + message.substring(commaPosition + 1, message.length()).indexOf(',');
g = (message.substring(commaPosition + 1, secondCommaPosition)).toInt();
b = (message.substring(secondCommaPosition + 1, message.length())).toInt();
Serial.print("Color : R ");
Serial.print(r);
Serial.print(" G ");
Serial.print(g);
Serial.print(" B ");
Serial.println(b);
}
message = "";
}
}
| true |
b5fbcccc5157a02b4b56ea71a94834a48d1f5f49 | C++ | syncopika/learningCpp | /sdl2projects/fishing/headers/Character.hh | UTF-8 | 1,070 | 3.25 | 3 | [] | no_license | #ifndef CHARACTER_H
#define CHARACTER_H
// Character class header file
#include "GameObject.hh"
// Character extends GameObject
class Character : public GameObject{
private:
// keep a vector to hold the textures corresponding to the left and right
// walking sprites of the character
// each step will alternate between left and right walking sprites, but with
// the regular standing sprite (charTexture) in between, i.e.
// left -> stand -> right -> stand -> ....
// this one holds sprites facing the down direction
std::vector<SDL_Texture*> walkingTextures;
public:
// constructor
// @param name = the character's name
// @param file = the file path to the character's .bmp image
//
Character(const std::string name, const std::string file, SDL_Renderer *ren);
// get the walking textures
std::vector<SDL_Texture*> getWalkTextures();
// add the walking textures - by default going in the DOWN DIRECTION
void addWalkTexture(SDL_Texture* texture);
// destroy textures
void destroyTexture();
};
#endif | true |
7986e7fa7756df335ca374f31630fdeb9a7f5add | C++ | brownd1978/FastSim | /TrkEnv/TrkVolumeHandle.hh | UTF-8 | 1,511 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: TrkVolumeHandle.hh 103 2010-01-15 12:12:27Z stroili $
//
// Description: TrkVolumeHandle
// Small class to keep track of TrkVolumes
//
// Environment:
// Software developed for the BaBar Volume at the SLAC B-Factory.
//
// Author List:
// David Brown 10-5-98
//
// Copyright Information:
// Copyright (C) 1998 Lawrence Berkeley Laboratory
//
//------------------------------------------------------------------------
#ifndef TRKVOLUMEHANDLE_HH
#define TRKVOLUMEHANDLE_HH
class TrkVolume;
class TrkVolumeHandle {
public:
// enum to define the track volumes (logically)
enum trkvolumes{none=0,beampipe,svt,dch,drc,emc,ifr};
TrkVolumeHandle();
TrkVolumeHandle(const TrkVolume* vol,trkvolumes volid);
TrkVolumeHandle(const TrkVolumeHandle&);
~TrkVolumeHandle();
TrkVolumeHandle& operator = (const TrkVolumeHandle& other);
const TrkVolume* volume() const { return _volume; }
trkvolumes volumeId() const { return _volid; }
// rw-required functions
int operator == (const TrkVolumeHandle& other) const {
return _volid == other.volumeId(); }
int operator != (const TrkVolumeHandle& other) const {
return _volid != other.volumeId(); }
int operator < (const TrkVolumeHandle& other) const {
return _volid < other.volumeId(); }
private:
const TrkVolume* _volume; // the volume pointed to by this handle
trkvolumes _volid; // whose volume it is
};
#endif
| true |
e0c60463a1deac9c5e4ec6c2862ce1465d6abcca | C++ | helloojj/JustinJohnson-CSCI20-Spr2017 | /lab26/lab26.cpp | UTF-8 | 2,294 | 4.34375 | 4 | [] | no_license | /* Created By: justin johnson
* Created On: 3/9/2017
* This program will convert temputres from kelvin, celcius and Fahrenheit using objects and classS
*/
#include <iostream>
#include <string>
using namespace std;
class TemperatureConverter {
public:
void SetTempFromKelvin(double kelvinTemp);
void SetTempFromCelsius(double celsiusTemp);
void SetTempFromFahrenheit(double fahrTemp);
void PrintTemperatures();
TemperatureConverter(); // default constructor
TemperatureConverter(double kelvinTemp);
double GetTempFromKelvin();
double GetTempAsCelsius();
double GetTempAsFahrenheit();
private:
double kelvin_;
};
TemperatureConverter::TemperatureConverter(){ // default constuctor
kelvin_ = 0.0;
}
TemperatureConverter::TemperatureConverter(double kelvinTemp){
kelvin_ = kelvinTemp;
return;
}
void TemperatureConverter::SetTempFromKelvin(double kelvinTemp){
kelvin_ = kelvinTemp;
}
void TemperatureConverter::SetTempFromCelsius(double celsiusTemp){
kelvin_ = (celsiusTemp + 273.15);
}
void TemperatureConverter::SetTempFromFahrenheit(double fahrTemp){
kelvin_ = (5 * (fahrTemp - 32) / 9) + 273.15;
}
double TemperatureConverter::GetTempFromKelvin() {
return kelvin_;
}
double TemperatureConverter::GetTempAsCelsius(){
return kelvin_;
}
double TemperatureConverter::GetTempAsFahrenheit(){
return kelvin_;
}
void TemperatureConverter::PrintTemperatures(){
cout<<"Kelvin: "
<<GetTempFromKelvin()
<<endl
<<"Celsius: "
<<GetTempAsCelsius()
<<endl
<<"Fahrenheit: "
<<GetTempAsFahrenheit()
<<endl;
}
int main(){
TemperatureConverter temp1; //testing default constructor
TemperatureConverter temp2(274); //testing overloaded constructor
temp1.PrintTemperatures();
temp2.PrintTemperatures();
temp1.SetTempFromKelvin(400.15); //testing mutator function
cout<<temp1.GetTempFromKelvin()<<endl;//testing accessor function
temp1.PrintTemperatures();
temp2.SetTempFromCelsius(32); //testing other functions
cout<<temp2.GetTempAsCelsius()<<endl;
temp2.PrintTemperatures();
temp2.SetTempFromFahrenheit(32);
cout<<temp2.GetTempAsFahrenheit()<<endl;
temp2.PrintTemperatures();
return 0;
} | true |
9129879cdfe7dcce12480b8bd70a7ae2f8ec6a1d | C++ | EnriquePuyol/SAG-Engine | /UI_Performance.cpp | UTF-8 | 1,372 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "UI_Performance.h"
#include "Application.h"
#include "ModuleWindow.h"
UI_Performance::UI_Performance(char* name) : UI(name)
{
active = false;
logMSIterator = 0;
logFPSIterator = 0;
lastFrameTime = SDL_GetTicks();
lastSecondTime = SDL_GetTicks();
fps_log = new float[50];
ms_log = new float[50];
}
UI_Performance::~UI_Performance()
{
}
void UI_Performance::Draw()
{
ImGui::SetNextWindowSize(ImVec2(300, App->window->height - 120), ImGuiCond_Always);
ImGui::Begin(name, &active);
ImGui::Text("App Lifetime = %d seconds", SDL_GetTicks() / 1000);
char* title = new char[50];
UpdateFramerates();
sprintf_s(title, 50, "Framerate %.1f", fps_log[logFPSIterator]);
ImGui::PlotHistogram("", fps_log, 50, 0, title, 0.0f, 100.0f, ImVec2(350, 100));
sprintf_s(title, 50, "Milliseconds %.1f", ms_log[logMSIterator]);
ImGui::PlotHistogram("", ms_log, 50, 0, title, 0.0f, 100.0f, ImVec2(350, 100));
ImGui::End();
}
void UI_Performance::UpdateFramerates()
{
double timeElapsed = SDL_GetTicks() - lastSecondTime;
//fps calculation
lastSecondTime = SDL_GetTicks();
fps_log[logFPSIterator] = 1000 / timeElapsed;
++logFPSIterator;
if (logFPSIterator > 49) logFPSIterator = 0;
//ms calculation
ms_log[logMSIterator] = timeElapsed;
lastFrameTime = SDL_GetTicks();
//iterator increase
++logMSIterator;
if (logMSIterator > 49) logMSIterator = 0;
}
| true |
9e6c75c15e8a63e871d8ed5da8908cab1ba86922 | C++ | KNWolf97/Personal-Work | /Old C++/Week3Homework/Week3Homework/Wolf_3_5.cpp | MacCentralEurope | 14,196 | 3.65625 | 4 | [] | no_license | /**************************************************************************************
* file name: Wolf_3_5
* programmer name: Kyle Wolf
* date created: 2/2/2018
* date of last revision:
* details of the revision:
* short description: User creates sets of ages and can perform operations on those sets
***************************************************************************************/
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include "Set.h"
using namespace std;
using namespace wolf_set;
void getAges(Set&);
// Postcondition: The user has been prompted to enter a range of ages,
// these ages have been entered into the ages set, stopping when the
// set is full or a negative number is entered
void eraseAges(Set&);
// Postcondition: The user has been prompted to enter ages,
// these ages have been erased from the set, stopping when
// the user enters a negative number
void addOn(Set&);
// Postcondition: The user has been prompted to enter ages for a new set,
// the age values in this set have been added on to the existing set
void subtractFrom(Set&);
// Postcondition: The user has been prompted to enter ages for a new set,
// the age values in this set have been subtracted from the existing set,
// new values introduced in the subtractor set are discarded
void addTwo(Set&);
// Postcondition: The user has been prompted to enter ages for two new sets,
// these ages have been added together to form a brand new set
void subtractTwo(Set&);
// Postcondition: The user has been prompted to enter ages for two new sets,
// the values of the first being subtracted by those of the second,
// new values introduced in the second set are discarded
int main( )
{
// Program description
cout << "This program will allow the user to enter" << endl
<< "ages into a set and perform operations on those ages.\n";
// Declaring the variables / objects
Set ageSet;
int selection;
while (1)
{
cout << "\n----------------------------------------------------------------------" << endl
<< setw(35) << ' ' << "MAIN MENU" << endl
<< " 1. Add ages to set" << endl
<< " 2. View ages" << endl
<< " 3. Erase ages from set " << endl
<< " 4. Add contents of a new set to the existing set" << endl
<< " 5. Subtract identical ages of a new set from the existing set" << endl
<< " 6. Obtain a fresh set by adding two sets' values together" << endl
<< " 7. Obtain a fresh set by subtracting one new set's ages from another's" << endl
<< " 8. Quit" << endl
<< "----------------------------------------------------------------------" << endl;
// Variable initialization
cout << "Enter selection: ";
cin >> selection;
// Switch statement for menu selection
switch (selection) {
case 1:
getAges(ageSet);
break;
case 2:
ageSet.displayData();
break;
case 3:
eraseAges(ageSet);
break;
case 4:
addOn(ageSet);
break;
case 5:
subtractFrom(ageSet);
break;
case 6:
addTwo(ageSet);
break;
case 7:
subtractTwo(ageSet);
break;
case 8:
cout << "\nGoodbye!" << endl;
return EXIT_SUCCESS;
default:
cout << "\nInvalid entry." << endl;
}
}
}
void getAges(Set& ages)
{
// Declaring the variables / objects
int user_input;
// Variable initialization
cout << "\nEnter the desired ages." << endl;
cout << "Type a negative number when you are done:" << endl;
cin >> user_input;
// Check that capacity isn't gone over, then check if new value is a duplicate, otherwise, insert value
while (user_input >= 0)
{
if (ages.size() < ages.CAPACITY)
if (!ages.contains(user_input))
ages.insert(user_input);
else
cout << "Duplicate ages cannot be entered." << endl;
else
cout << "I have run out of room and cant add that age." << endl;
cin >> user_input;
}
}
void eraseAges(Set& ages)
{
// Declaring the variables / objects
int user_input = 0;
cout << "\nAt any point, enter a negative number to go back to the Main Menu." << endl;
// Variable initialization, remove from set if present
while (user_input >= 0) {
cout << "Enter age to be deleted: ";
cin >> user_input;
if (ages.erase_one(user_input))
cout << "Age removed." << endl;
else if (user_input < 0)
break;
else
cout << "Age does not occur." << endl;
}
}
void addOn(Set& ages)
{
// Declaring the variables / objects
Set addAges;
cout << "\nADD-ON SET:";
getAges(addAges);
// Overload operator use
ages += addAges;
cout << "\nSet succesfully added on to original set." << endl;
}
void subtractFrom(Set& ages)
{
// Declaring the variables / objects
Set subtAges;
cout << "\nSUBTRACTOR SET:";
getAges(subtAges);
// Overload operator use
ages -= subtAges;
cout << "\nSet succesfully subtracted from original set." << endl;
}
void addTwo(Set& ages)
{
// Declaring the variables / objects
Set ages1, ages2;
cout << "\nFIRST SET:";
getAges(ages1);
cout << "\nSECOND SET:";
getAges(ages2);
// Overload operator use
ages = ages1 + ages2;
cout << "\nNew set succesfully created." << endl;
}
void subtractTwo(Set& ages)
{
// Declaring the variables / objects
Set ages1, ages2;
cout << "\nBASE SET:";
getAges(ages1);
cout << "\nSUBTRACTOR:";
getAges(ages2);
// Overload operator use
ages = ages1 - ages2;
cout << "\nNew set succesfully created." << endl;
}
/*
This program will allow the user to enter
ages into a set and perform operations on those ages.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 10
Invalid entry.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: -9
Invalid entry.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 1
Enter the desired ages.
Type a negative number when you are done:
10
20
30
-1
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 3
At any point, enter a negative number to go back to the Main Menu.
Enter age to be deleted: 10
Age removed.
Enter age to be deleted: 30
Age removed.
Enter age to be deleted: -1
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 2
20
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 4
ADD-ON SET:
Enter the desired ages.
Type a negative number when you are done:
50
60
-1
Set succesfully added on to original set.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 2
20 50 60
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 5
SUBTRACTOR SET:
Enter the desired ages.
Type a negative number when you are done:
50
60
70
-1
Set succesfully subtracted from original set.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 2
20
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 6
FIRST SET:
Enter the desired ages.
Type a negative number when you are done:
10
20
30
40
-1
SECOND SET:
Enter the desired ages.
Type a negative number when you are done:
40
50
60
-1
New set succesfully created.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 2
10 20 30 40 60 50
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 7
BASE SET:
Enter the desired ages.
Type a negative number when you are done:
90
80
70
60
-1
SUBTRACTOR:
Enter the desired ages.
Type a negative number when you are done:
70
60
-1
New set succesfully created.
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 2
90 80
----------------------------------------------------------------------
MAIN MENU
1. Add ages to set
2. View ages
3. Erase ages from set
4. Add contents of a new set to the existing set
5. Subtract identical ages of a new set from the existing set
6. Obtain a fresh set by adding two sets' values together
7. Obtain a fresh set by subtracting one new set's ages from another's
8. Quit
----------------------------------------------------------------------
Enter selection: 8
Goodbye!
Press any key to continue . . .
*/ | true |
23a0283d4a78eb500b8de58e57209e7ea72b8df8 | C++ | WeiMuYang/qtcreator-study-202104 | /03-qt-study-code/82-samp14_2TCP/TCPClient/mainwindow.h | UTF-8 | 1,200 | 2.5625 | 3 | [] | no_license | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTcpSocket>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
// 1. 用于创建tcp的socket套接字
QTcpSocket *tcpClient; //socket
// 2. 状态栏标签
QLabel *LabSocketState; //状态栏显示标签
// 3. 获取本机的以太网IP
QString getLocalIP();//获取本机IP地址
protected:
// 4. 重写关机事件
void closeEvent(QCloseEvent *event);
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
//自定义槽函数
// 5. 建立连接
void onConnected();
// 6. 断开连接
void onDisconnected();
//
void onSocketStateChange(QAbstractSocket::SocketState socketState);
//
void onSocketReadyRead();//读取socket传入的数据
// Socket状态变化的槽函数
void on_actConnect_triggered();
void on_actDisconnect_triggered();
// 清空文本槽函数
void on_actClear_triggered();
// 发送信息槽函数
void on_btnSend_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| true |
03989e10d0fe8b0b378f3556cf087866d5d0aa62 | C++ | ojaster/first_project | /cpp_xcode/FIrst_Project/FIrst_Project/df.cpp | UTF-8 | 829 | 2.96875 | 3 | [] | no_license | ////
//// df.cpp
//// FIrst_Project
////
//// Created by Данил on 18/05/2019.
//// Copyright © 2019 Daniil. All rights reserved.
////
//
//#include <stdio.h>
//#include <iostream>
//using namespace std;
//string funktion(string & c);
//string funktion2();
//int main(){
//
// string c;
//
// string b="ba";
//
// string a="ab";
// string h = "o";
// string r ="r";
// a = r + h;
// for(int i=0; i<b.size(); i++){
// b[i] = a[i];
// }
// cout<<b<<endl;
//
// cout<<funktion(c)<<endl;
// cout<<funktion2()<<endl;
//}
//string funktion2(){
// string b;
// string c;
// funktion(c);
// for(int i=0; i<2; i++){
// b = c;
// }
// return b;
//}
//string funktion(string & c){
// string a = "b";
// string b = "a";
// c = a + b;
// return c;
//}
| true |
ede53749174f7503f6063ee46c72d7fd8aaca42c | C++ | theDude823/Sorting-Visualization | /card.h | UTF-8 | 1,088 | 2.75 | 3 | [] | no_license | #pragma once
#include "screenSize.h"
#include <SFML/Graphics.hpp>
#include <sstream>
using namespace sf;
class Card {
private:
Vector2f m_Position;
Sprite m_Sprite;
Texture m_Texture;
Text m_number;
std::stringstream m_protoNumber;
Font font;
float m_Speed = 1000, m_R = 0, m_Cx, m_Cy;
bool m_moving = 0, m_animating = 0;
Vector2f m_moveCoordinates;
public:
int m_positionNumber;
static Card *m_array;
static bool drawNumber;
Card(int num = 0, float startX = 50, float startY = 50);
void setValue(int num, int positionNumber, float startX, float startY);
int isItMoving();
bool isItAnimating();
void moveNow();
void stopNow();
void update(Time dt);
float getMoveCoordinatex();
float getMoveCoordinatey();
void setPositionx(float newPostn);
float getPositionx();
float getPositiony();
Sprite getSprite();
Text getNumber();
void moveTo(Card &moveToThisCard);
void moveToL(Card &moveToThisCard);
void animateNow();
void stopAnimation();
void clearStream();
};
| true |
1c239cfaafe59c36b790d2c41e4e32a291c168c5 | C++ | Gid32/ProteinFolding | /core/ant.cpp | UTF-8 | 405 | 2.5625 | 3 | [] | no_license | #include "ant.h"
#include <QTime>
Ant::Ant()
{
}
void Ant::setCount(int count)
{
count_ = count;
}
void Ant::run()
{
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
for (int i = 0; i < count_; ++i)
{
Convolution *convolution = ConvolutionFactory::getFactory()->getConvolution();
if(convolution)
emit convolutionCreated(convolution);
}
}
| true |
0c7317c6462b81d7f178852354c69e06de1137ef | C++ | emilybyhuang/Stock-Statement-Generator | /src/updateAct.cpp | UTF-8 | 1,803 | 3.03125 | 3 | [] | no_license | #include <nlohmann/json.hpp>
#include <stock.h>
#include <boost/algorithm/string.hpp>
#include <typeinfo>
#include <updateAct.h>
#include <iomanip>
bool updateAct(std::vector<stock>& mystocks, string action, string ticker, string shares, string price){
//cout << "update size" << mystocks.size();
if(action == "BUY"){
bool present = false;
for (int i = 0; i < mystocks.size(); i++){
if(ticker == mystocks[i].ticker){
present = true;
mystocks[i].shares += stoi(shares);
}
}
if(present == false){
stock newstock(ticker, stoi(shares),stod(price));
mystocks.push_back(newstock);
}
cout <<'\t' << "- You bought " << stoi(shares) << " of " << ticker << " at a price of $" <<
fixed << setprecision(2) << stod(price) << " per share" << endl;
}else if (action == "SELL"){
bool found = false;
for (int i = 0; i < mystocks.size(); i++){
if(ticker == mystocks[i].ticker){
found = true;
double worth = stoi(shares) * stod(price);
string word;
if(worth > (stoi(shares) * (mystocks[i].price))) word = "profit";
else word = "loss";
mystocks[i].shares = mystocks[i].shares - stoi(shares);
cout <<'\t' << "- You sold " << stoi(shares) << " of " << ticker << " at a price of $" <<
fixed << setprecision(2) << stod(price) << " per share for a " << word << " of $" <<
worth - (stoi(shares) * (mystocks[i].price)) << endl;
}
}
if(!found) {
cout << "Error: dont have stocks with this ticker" << endl;
return false;
}
}
return true;
} | true |
2de3b6afa112d9dd6ad05ac75d60f0b0335c0f65 | C++ | Stephhh-Lee/Leetcode | /526-Beautiful_Arrangement.cpp | UTF-8 | 2,618 | 3.015625 | 3 | [] | no_license | class Solution {
public:
int countArrangement(int N) {
int ans = 0;
vector<int> v(N+1, 0);
helper(N, v, 1, ans);
return ans;
}
void helper(int n, vector<int>& v, int pos, int& ans){
if(pos > n){
ans++;
return;
}
for(int i=1; i<=n; i++){
if(v[i]==0 &&(i%pos==0 || pos%i==0)){
v[i]=1;
helper(n,v,pos+1,ans);
v[i]=0;
}
}
}
};
class Solution {
public:
typedef struct {
int cnt;
char* dat;
} entryType;
int dfs(entryType* entries, bool* visit, int n, int N, int cnt) {
if (n > N) return ++cnt;
int c = entries[n].cnt;
for (int i = 1; i <= c; ++i) {
bool* v = visit + entries[n].dat[i];
// Skip for duplicated digits
if (*v) continue;
*v = true;
cnt = dfs(entries, visit, n + 1, N, cnt);
*v = false;
}
return cnt;
}
int countArrangement(int N) {
// Example
// 1 2 3 4 5
// entry 1 1 2 3 4 5 cnt = 5
// entry 2 1 2 0 4 0 cnt = 3
// entry 3 1 0 3 0 0 cnt = 2
// entry 4 1 2 0 4 0 cnt = 3
// entry 5 1 0 0 0 5 cnt = 2
char buf[N + 1][N + 1] = {};
entryType entries[N + 1] = {};
bool visit[N + 1] = {};
for (int i = 1; i <= N; ++i) {
entries[i].dat = buf[i];
}
// Construct candiates
for (int i = 1; i <= N; ++i) {
for (int j = i; j <= N; j += i) {
entries[i].dat[j] = j;
entries[j].dat[i] = i;
}
}
// Pack data
for (int i = 1; i <= N; ++i) {
char* d = entries[i].dat;
int j = 1;
int k = N;
while (j <= k) {
while (j <= N && d[j] != 0) ++j;
while (k > 0 && d[k] == 0) --k;
if (j < k) {
char t = d[j];
d[j] = d[k];
d[k] = t;
}
}
entries[i].cnt = j - 1;
}
// Sort for performance
sort(entries + 1, entries + N + 1,
[](const entryType& a, const entryType& b) -> bool
{
return a.cnt < b.cnt;
});
// DFS
return dfs(entries, visit, 1, N, 0);
}
};
| true |
9d3bf09fafa20477b160953702641c84f6e54226 | C++ | Aapoorva/codeDemos | /CPP/graph_dfs.cpp | UTF-8 | 2,678 | 3.5 | 4 | [] | no_license | #include "iostream"
#include "vector"
#include "stack"
#include "list"
using namespace std;
int findVertex(vector< list<int> > graph, int vertex){
int currIndx = 0;
for (vector<list <int> >::iterator i = graph.begin(); i != graph.end(); ++i, currIndx++)
{
if((*i).front() == vertex){
return currIndx;
}
}
return -1;
}
int addVertex(vector< list<int> > &graph, int vertex){
int vertexIndex = findVertex(graph, vertex);
if (vertexIndex == -1)
{
graph.push_back(list<int>());
graph.back().push_back(vertex);
vertexIndex = graph.size() - 1;
}
return vertexIndex;
}
void addEdge(vector< list<int> > &graph, int startVertex, int endVertex, int isDirected){
// adding vertex to graph
int startVertexIndx = addVertex(graph, startVertex);
int endVertexIndx = addVertex(graph, endVertex);
// adding edge to list
graph[startVertexIndx].push_back(endVertex);
if (isDirected == 0)
{
graph[endVertexIndx].push_back(startVertex);
}
}
void showDfsTraversal(vector< list<int> > &graph){
int startVertex, currVertex, v_pos,curr_v_pos;
int *visitedVertx = new int[graph.size()];
stack<int> waitingVertex;
cout<<"Enter start node : ";
cin>>startVertex;
curr_v_pos = findVertex(graph,startVertex);
if (curr_v_pos == -1){
cout<<"Vertex does not exists";
}
else{
// pushing starting vertex to stack
waitingVertex.push(startVertex);
visitedVertx[curr_v_pos] = 1;
cout<<"***DFS TRAVERSAL***\n";
while(!waitingVertex.empty()){
currVertex = waitingVertex.top();
waitingVertex.pop();
cout<<currVertex<<" ";
curr_v_pos = findVertex(graph, currVertex);
// pushing current vertex's unvisited vertex to stack
for (std::list<int>::iterator i = graph[curr_v_pos].begin(); i != graph[curr_v_pos].end(); ++i)
{
v_pos = findVertex(graph,(*i));
// checking vertex visited or not
if (visitedVertx[v_pos] != 1){
// pushing to stack
waitingVertex.push(*i);
// marking vertex as visited
visitedVertx[v_pos] = 1;
}
}
}
}
}
int main()
{
vector< list<int> > graph;
int n_edge, isDirected;
int startVertex, endVertex;
cout<<"Is your graph directed? yes = 1, no = 0 - ";
cin>>isDirected;
cout<<"Enter no. of edges - ";
cin>>n_edge;
cout<<"Enter edge list\n";
for (int i = 0; i < n_edge; ++i)
{
cin>>startVertex>>endVertex;
addEdge(graph,startVertex,endVertex,isDirected);
}
showDfsTraversal(graph);
cout<<"\n***ADJENCY LIST***\n";
for (std::vector< list<int> >::iterator i = graph.begin(); i != graph.end(); ++i)
{
for (list<int>::iterator i_list = (*i).begin(); i_list != (*i).end(); ++i_list)
{
cout<<*i_list<<" ";
}
cout<<"\n";
}
return 0;
} | true |
0167da092fe719dbc789ce290acc92904e1e9b60 | C++ | astappiev/NURE | /1st-course/AlgSD/lab_2/C/main.cpp | UTF-8 | 627 | 3.515625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <stack>
using namespace std;
int obr(char simb)
{
switch (simb) {
case ')': simb='('; break;
case ']': simb='['; break;
case '}': simb='{'; break;
}
return simb;
}
int main()
{
stack <char> st;
string str;
cin>>str;
int size=str.size();
for(int i=0; i<size; ++i)
{
if(str[i]=='(' || str[i]=='[' || str[i]=='{')
{
st.push(str[i]);
}
else if(!(st.empty()) && st.top()==obr(str[i]))
{
st.pop();
}
else
{
st.push(str[i]);
break;
}
}
if(st.empty()) cout<<"yes"<<endl;
else cout<<"no"<<endl;
return 0;
} | true |
a40c8cfe7920b01df12773ac0d6254e6270a762e | C++ | huangyt/MyProjects | /PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/index_server_data_migration/stdafx.cpp | GB18030 | 1,095 | 2.515625 | 3 | [] | no_license | // stdafx.cpp : ֻļԴļ
// p2pvideo.pch ΪԤͷ
// stdafx.obj ԤϢ
#include "stdafx.h"
// TODO: STDAFX.H
// κĸͷļڴļ
namespace framework
{
string w2b(const wstring& _src)
{
int nBufSize = ::WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, NULL, 0, 0, FALSE);
char *szBuf = new char[nBufSize + 1];
::WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, szBuf, nBufSize, 0, FALSE);
string strRet(szBuf);
delete []szBuf;
szBuf = NULL;
return strRet;
}
wstring b2w(const string& _src)
{
//ַ string ת wchar_t ֮ռõڴֽ
int nBufSize = ::MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,NULL,0);
//Ϊ wsbuf ڴ BufSize ֽ
wchar_t *wsBuf = new wchar_t[nBufSize + 1];
//תΪ unicode WideString
::MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,wsBuf,nBufSize);
wstring wstrRet(wsBuf);
delete []wsBuf;
wsBuf = NULL;
return wstrRet;
}
} | true |
db82c522037e7ff89549d293fc10fa8899ddd76d | C++ | ChengFujia/C-project | /CSP(C++)/201703_3.cpp | GB18030 | 4,101 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
#define MOST_LENGTH 10
//
string handle_heading(string line)
{
int num = 48; //0ascii룬֣棨+=ַ֣+=ַ
int length = line.size();
string result = "<h";
for(int i=0;i<length;i++)
{
if(line[i]=='#') //ͷ#
num++;
else if(line[i]==' ') //ͷĿո
continue;
else if(line[i]!=' ') //ͷ֮
{
// ַ ֺ֧չǰչЧ
result = result + char(num) + '>' + line.substr(i,length-i) + "</h" + char(num) + '>';
// printf("<h %c > %s </h %c >",char(num),line.substr(i,length-i),char(num));
break;
}
}
return result;
}
// б
string handle_list(string line)
{
int length = line.size();
int i;
for(i=1;i<length;i++)
{
if(line[i] != ' ')
break;
}
line = "<li>" + line.substr(i,length-i) + "</li>";
return line;
}
//
string handle_para(string line)
{
string result = "<p>" + line;
return result;
}
// ǿ
string handle_empha(string line)
{
vector<int> loc; //洢_λ
int i = 0;
int length = line.size();
while(i<=length-1 && line.substr(i,length-i).find('_')!=-1)
{
i += line.substr(i,length-i).find('_') +1; //+=ΪfindindexǴиӴʼ
loc.push_back(i-1);
//cout<< i-1 << " " << line[i-1] <<endl;
}
for(int j=0;j<loc.size()/2;j++)
{
string string1 = line.substr(0,loc[2*j] + 7*j); //7jƫӱǩ֮ƫ
string string2 = line.substr(loc[2*j]+1 + 7*j,loc[2*j+1]-1-loc[2*j]);
string string3 = line.substr(loc[2*j+1]+1 + 7*j,length-1-loc[2*j+1]);
line = " ";
line = string1 + "<em>" + string2 + "</em>" + string3;
//cout << line << endl;
}
return line;
}
//
string handle_link(string line)
{
vector<int> loc; //洢ַλ
char cha[4] = {'[',']','(',')'};//洢ַ
int j=0;
int length = line.size();
while(j<=length-1 && line.substr(j,length-j).find('[')!=-1)
{
for(int i=0;i<4;i++)
{
j += line.substr(j,length-j).find(cha[i]) + 1;
loc.push_back(j -1);
// cout << j-1 << " " << line[j-1] << endl;
}
}
for(int p=0;p<loc.size()/4;p++)
{
string string1 = line.substr(0,loc[4*p] + 9*p);
string text = line.substr(loc[4*p]+1 + 9*p,loc[4*p+1]-1-loc[4*p]);
string link = line.substr(loc[4*p+2]+1 + 9*p,loc[4*p+3]-1-loc[4*p+2]);
string string2 = line.substr(loc[4*p+3]+1 + 9*p,length-1-loc[4*p+3]);
line = "";
line = string1 + "<a href=" + link + '>' + text + "</a>" + string2;
//cout << line << endl;
}
return line;
}
int main()
{
vector<string> result;
string line = "";
int num = 1;
bool list_sign = false;
bool para_sign = false;
while(getline(cin,line) && num <= MOST_LENGTH)
{
if(line == "")
{
if(list_sign)
{
result.push_back("</ul>");
list_sign = false;
}
if(para_sign)
{
result[result.size()-1] += "</p>";
para_sign = false;
}
num++;
}
else
{
// Ԥ -- ڵĴ/ڲ
if(line.find('_'))
line = handle_empha(line);
if(line.find('['))
line = handle_link(line);
// ʽ -- 鴦
// heading
if(line[0] == '#')
{
line = handle_heading(line);
result.push_back(line);
}
// list
else if(line[0] == '*')
{
line = handle_list(line);
if(!list_sign)
{
result.push_back("<ul>");
list_sign = true;
}
result.push_back(line);
}
// paragraph
else
{
if(!para_sign)
{
line = handle_para(line);
para_sign = true;
}
else
line = line;
result.push_back(line);
}
// -- һб߶
if(num == MOST_LENGTH)
{
if(list_sign)
result.push_back("</ul>");
if(para_sign)
result[result.size()-1] += "</p>";
}
num ++;
}
}
for(int i=0;i < result.size();i++)
{
cout << result[i] << endl;
}
return 0;
}
| true |
f8c6e196cb517662399044c1b52d14c125870926 | C++ | snowflip/training | /cplusplus/cc.cpp | UTF-8 | 231 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
class A
{
public:
virtual int test();
virtual double test2();
int test3();
protected:
double test4();
private:
int a, b, c;
};
int main()
{
int a = sizeof(A);
printf("a is %d\n", a);
}
| true |
9b9ff174706220ab3047717a6bd2530c346b540a | C++ | edderick/advent-of-code-2019 | /day-02/part-1.cpp | UTF-8 | 924 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(int argc, char* argv[]) {
int value;
vector<int> values;
while (cin >> value) {
values.push_back(value);
cin.ignore();
}
values[1] = 12;
values[2] = 2;
int pc = 0;
while (true) {
for (const auto v: values) {
cout << v << ",";
}
cout << "\nPC = " << pc << " Value = " << values[pc] << "\n";
switch (values[pc]) {
case 1:
values[values[pc + 3]] = values[values[pc + 1]] + values[values[pc + 2]];
pc += 4;
break;
case 2:
values[values[pc + 3]] = values[values[pc + 1]] * values[values[pc + 2]];
pc += 4;
break;
case 99:
cout << "Answer: " << values[0] << "\n";
return 0;
}
}
}
| true |
26072c157ecd8c44d99f4325271b78446485e8bf | C++ | saheel1115/szz | /src/lang_model/generate_entropy_data/code/isolate_lines/ngram.h | UTF-8 | 2,388 | 2.921875 | 3 | [
"MIT"
] | permissive | #ifndef __NGRAM_H__
#define __NGRAM_H__
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#include "utility.h"
using namespace std;
class Word
{
public:
Word()
{
m_prob = 0.0;
}
Word(const string& token, const float prob)
{
m_token = token;
m_prob = prob;
}
bool operator <(const Word &right) const
{
return m_prob < right.m_prob;
}
bool operator >(const Word &right) const
{
return m_prob > right.m_prob;
}
string m_token;
float m_prob;
string m_debug;
};
class Ngram
{
public:
// for prediction task
Ngram(const string& ngramFile, const int order, const int beam_size);
// for calculating the cross entropy
Ngram(const string& ngramFile, const int order);
public:
// for prediction task
/**
* get the candidate tokens when given the prefix
* @param prefix the previous (n-1) grams
* @param use_backoff Using back-off, when there is no candidates given (n-1) grams,
we will search the candidates given the previous (n-2) grams,
...
until candidates are returned
* @param candidates the result candidates
**/
bool GetCandidates(const std::string& prefix, const bool use_backoff, vector<Word>& candidates);
// for calculating the cross entropy
/**
* get the candidate tokens when given the prefix
* @param prefix the previous (n-1) grams
* @param use_backoff Using back-off, when there is no candidates given (n-1) grams,
we will search the candidates given the previous (n-2) grams,
...
until candidates are returned
* @param candidates the result candidates
**/
float GetProbability(const string& prefix, const string& token, const bool use_backoff);
float m_unk_prob;
private:
// for prediction task
// the vector that stores the candidates word given all n-grams (i.e., 1-grams, 2-grams, ..., (n-1)-grams)
vector<map<string, vector<Word> > > m_ngrams_list;
// for calculating the cross entropy
// the map that stores the candidates word given all n-grams (i.e., 1-grams, 2-grams, ..., (n-1)-grams)
vector<map<string, map<string, float> > > m_ngrams_map;
};
#endif
| true |
8384e2de205d4c2e21441548790fd758fa6f9db7 | C++ | c2290445045/Admir | /学生管理系统/Management.h | GB18030 | 663 | 2.5625 | 3 | [] | no_license | #pragma once
#include<vector>
#include<string>
#include"Student.h"
class Management
{
public:
void ADD(Student);//ѧ
void Delete(string);//ɾѧ
void Update(string, int, int);//³ɼ
bool Fuzzy_Serach(string);//ģ
bool Search(string);
void Sort_student();//
double Pass_rate(int);//ϸ
double AVG(int);//ƽɼ
double AVG();//ƽɼܷ
double Standard_deviation(int);//
vector<Student> Return_Data();//
private:
vector<Student>m_students;
bool Fuzzy_search_ID(Student,string);//ѧģ
bool Fuzzy_search_name(Student,string);//ģ
};
| true |
8a5ed698b6c8e054f27e40467ed7263a3643e07c | C++ | gogo40/clever | /modules/std/core/array.cc | UTF-8 | 6,489 | 2.890625 | 3 | [
"MIT"
] | permissive | /**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "core/value.h"
#include "core/vm.h"
#include "modules/std/core/array.h"
#include "modules/std/core/function.h"
namespace clever {
TypeObject* ArrayType::allocData(CLEVER_TYPE_CTOR_ARGS) const
{
ArrayObject* arr = new ArrayObject();
ValueVector& vec = arr->getData();
for (size_t i = 0, j = args->size(); i < j; ++i) {
vec.push_back(args->at(i)->clone());
}
return arr;
}
void ArrayType::dump(TypeObject* value, std::ostream& out) const
{
ArrayObject* arr = static_cast<ArrayObject*>(value);
ValueVector& vec = arr->getData();
out << "[";
for (size_t i = 0, j = vec.size(); i < j; ++i) {
vec.at(i)->dump(out);
if (i < j-1) {
out << ", ";
}
}
out << "]";
}
// Subscript operator
CLEVER_TYPE_AT_OPERATOR(ArrayType::at_op)
{
ValueVector& arr = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
long size = arr.size();
if (!index->isInt()) {
clever_throw("Invalid array index type");
return NULL;
}
if (index->getInt() < 0 || index->getInt() >= size) {
clever_throw("Array index out of bound!");
return NULL;
}
Value* result = arr.at(index->getInt());
// @TODO(Felipe): FIXME
result->setConst(false);
clever_addref(result);
return result;
}
// Array::Array([arg, ...])
CLEVER_METHOD(ArrayType::ctor)
{
result->setObj(this, allocData(&args));
}
// void Array::append([arg, ... ])
CLEVER_METHOD(ArrayType::append)
{
if (!clever_check_args("*")) {
return;
}
if (!args.empty()) {
ValueVector& vec = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
for (size_t i = 0, j = args.size(); i < j; ++i) {
vec.push_back(args[i]->clone());
}
}
result->setNull();
}
// int Array::size()
CLEVER_METHOD(ArrayType::size)
{
if (!clever_check_no_args()) {
return;
}
result->setInt(CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData().size());
}
// mixed Array::at(int position)
CLEVER_METHOD(ArrayType::at)
{
if (!clever_check_args("i")) {
return;
}
ValueVector& arr = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
long num = args[0]->getInt();
if (num < 0 || arr.size() <= size_t(num)) {
result->setNull();
return;
}
result->copy(arr.at(num));
}
// void Array::reserve(Int size)
CLEVER_METHOD(ArrayType::reserve)
{
if (!clever_check_args("i")) {
return;
}
ArrayObject* arr = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS());
result->setNull();
if (args[0]->getInt() < 0) {
return;
}
arr->getData().reserve(args[0]->getInt());
}
// Array Array::reverse()
// Returns the reverse of this array
CLEVER_METHOD(ArrayType::reverse)
{
if (!clever_check_no_args()) {
return;
}
ValueVector& vec = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
ValueVector::reverse_iterator it(vec.rbegin()), end(vec.rend());
ValueVector rev;
while (it != end){
rev.push_back((*it));
++it;
}
result->setObj(this, allocData(&rev));
}
// mixed Array.shift()
// Removes and returns the first element of the array
CLEVER_METHOD(ArrayType::shift)
{
if (!clever_check_no_args()) {
return;
}
ValueVector& vec = (CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS()))->getData();
if (vec.empty()) {
result->setNull();
return;
}
result->copy(vec[0]);
vec[0]->delRef();
vec.erase(vec.begin());
}
// mixed Array.pop()
// Removes and returns the last element of the array
CLEVER_METHOD(ArrayType::pop)
{
if (!clever_check_no_args()) {
return;
}
ValueVector& vec = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
if (vec.empty()) {
result->setNull();
return;
}
result->copy(vec[vec.size()-1]);
vec[vec.size()-1]->delRef();
vec.erase(vec.end()-1);
}
// Array Array.range(Int start, Int end)
// Returns a range as a new array
CLEVER_METHOD(ArrayType::range)
{
if (!clever_check_args("ii")) {
return;
}
ValueVector& vec = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
if (vec.empty()){
result->setNull();
return;
}
ValueVector ran;
ValueVector::size_type start = args[0]->getInt(),
end = args[1]->getInt(),
size = vec.size();
bool reverse = (start > end);
while ((reverse ? (end <= start) : (start <= end))) {
if (start > size || end > size) {
break;
}
ran.push_back(vec[start]);
if (reverse) {
--start;
} else {
++start;
}
}
result->setObj(this, allocData(&ran));
}
// Array Array::each(Function callback)
// Calls function once for each element in the array, passing the element as the only parameter to function
// The return values from function are returned in the same order as the array
CLEVER_METHOD(ArrayType::each)
{
if (!clever_check_args("f")) {
return;
}
Function* func = static_cast<Function*>(args[0]->getObj());
ValueVector& vec = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
ValueVector results;
for (size_t i = 0, j = vec.size(); i < j; ++i) {
ValueVector tmp_args;
tmp_args.push_back(vec[i]);
results.push_back(const_cast<VM*>(vm)->runFunction(func, &tmp_args));
}
result->setObj(this, allocData(&results));
std::for_each(results.begin(), results.end(), clever_delref);
}
// mixed Array.erase(Int position)
// Removes from this array the element at position, returning the value
CLEVER_METHOD(ArrayType::erase)
{
if (!clever_check_args("i")) {
return;
}
ValueVector& vec = CLEVER_GET_OBJECT(ArrayObject*, CLEVER_THIS())->getData();
if (vec.empty()) {
return;
}
long num = args[0]->getInt();
size_t length = vec.size();
if (num >= 0 && size_t(num) < length) {
result->copy(vec[num]);
vec[num]->delRef();
vec.erase(vec.begin() + num);
}
}
// Type initialization
CLEVER_TYPE_INIT(ArrayType::init)
{
setConstructor((MethodPtr)&ArrayType::ctor);
addMethod(new Function("append", (MethodPtr)&ArrayType::append));
addMethod(new Function("size", (MethodPtr)&ArrayType::size));
addMethod(new Function("at", (MethodPtr)&ArrayType::at));
addMethod(new Function("reserve", (MethodPtr)&ArrayType::reserve));
addMethod(new Function("reverse", (MethodPtr)&ArrayType::reverse));
addMethod(new Function("each", (MethodPtr)&ArrayType::each));
addMethod(new Function("shift", (MethodPtr)&ArrayType::shift));
addMethod(new Function("pop", (MethodPtr)&ArrayType::pop));
addMethod(new Function("range", (MethodPtr)&ArrayType::range));
addMethod(new Function("erase", (MethodPtr)&ArrayType::erase));
}
} // clever
| true |
cf6049eda2a400a03cda0e18b3930deb26f4a6f4 | C++ | JuliyaK/labs | /OOP 2/OOP 2/OOP 2.cpp | WINDOWS-1251 | 1,203 | 3.390625 | 3 | [] | no_license | // OOP 2.cpp: .
#include "stdafx.h"
#include "iostream"
using namespace std;
class monstr
{
private:
int health;
int fotce;
public:
monstr()
{
health = 0;
fotce = 0;
}
int getH() const
{
return health;
}
int getF() const
{
return fotce;
}
void setH(int count)
{
int p = count + fotce;
if (p > 150)
{
count -= (p - 150);
}
if (count <= 0)
{
health = 1;
}
else if (count > 100)
{
health = 100;
}
else health = count;
}
void setF( int count)
{
int p = health + count;
if (p > 150)
{
health -= (p - 150);
}
if (count <= 0)
{
fotce = 1;
}
else if (count > 100)
{
fotce = 100;
}
else { fotce = count; }
}
};
int main()
{
setlocale(LC_ALL, "rus");
monstr name1, name2;
name1.setH(52);
name1.setF(120);
cout << " NAME1: " << name1.getH() << endl;
cout << " NAME1: " << name1.getF() << endl;
name2.setH(90);
cout << " NAME2: " << name2.getH() << endl;
name2.setF(0);
cout << " NAME2: " << name2.getF() << endl;
getchar();
getchar();
return 0;
}
| true |
219f5eccf71ee0b736f4e322afd862d533fa01fb | C++ | Saurav-pixel/coding_practice | /decimalTobinary.cpp | UTF-8 | 438 | 3.09375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int decimalNumber;
long placeValue = 1;
long binaryNumber = 0;
cout<<"Enter any decimal number "<<endl;
cin>>decimalNumber;
while(decimalNumber != 0){
int remainder = decimalNumber % 2;
binaryNumber = binaryNumber + placeValue * remainder;
placeValue = placeValue * 10 ;
decimalNumber = decimalNumber / 2;
}
cout<<binaryNumber;
}
| true |
a9bdb7b549c34c6e9f746de9db8adc9146c10d02 | C++ | fancidev/euler | /src/p36.cpp | UTF-8 | 1,567 | 3.359375 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include "euler/digits.hpp"
#include "euler.h"
BEGIN_PROBLEM(36, solve_problem_36)
PROBLEM_TITLE("Find palindromic numbers in both base 10 and base 2")
PROBLEM_ANSWER("872187")
PROBLEM_DIFFICULTY(1)
PROBLEM_FUN_LEVEL(1)
PROBLEM_TIME_COMPLEXITY("sqrt(N) log(N)")
PROBLEM_SPACE_COMPLEXITY("log(N)")
END_PROBLEM()
static void solve_problem_36()
{
int64_t sum = 0;
#if 0
for (int n = 1; n < 1000000; n++)
{
if (is_palindromic(n,10) && is_palindromic(n,2))
{
if (verbose)
std::cout << n << std::endl;
sum += n;
}
}
#else
// Note: the algorithm can be improved by skipping all even numbers.
// However, this is not implemented below.
std::array<int,10> digits;
for (int a = 1; a < 1000; a++)
{
auto p0 = digits.begin();
auto p1 = std::copy(euler::digits(a).begin(), euler::digits(a).end(), p0);
// Mirror abc => abcba
{
auto p2 = std::reverse_copy(p0, p1 - 1, p1);
int n = euler::from_digits<int>(p0, p2);
if (euler::is_palindromic<2>(n))
{
if (verbose())
{
std::cout << n << std::endl;
}
sum += n;
}
}
// Mirror abc => abccba
{
auto p2 = std::reverse_copy(p0, p1, p1);
int n = euler::from_digits<int>(p0, p2);
if (euler::is_palindromic<2>(n))
{
if (verbose())
{
std::cout << n << std::endl;
}
sum += n;
}
}
}
#endif
std::cout << sum << std::endl;
}
| true |
0e6607f0cb54e76c42fba4bd38f28738dcd8cf02 | C++ | imatesiu/Converter | /Progetto1/messaggi/pacchettopresentazione.h | ISO-8859-13 | 1,590 | 2.796875 | 3 | [] | no_license | #pragma once
#include "utility.h"
/*Utilizzo questa classe per rappresentare le informazioni contenute nel pacchetto Presentazione che l'ATS riceve dal ATO
nel messaggio di Presentazione, sono presenti anche i metodi per serializzare e deserializzare il contenuto della classe*/
/*-----------------------------------------------------------------------------------------------
L'ATS riceve dal treno dei messaggi di presentazione dagli ATO
-------------------------------------------------------------------------------------------------*/
ref class pacchettopresentazione
{
unsigned int NID_PACKET;
unsigned int L_PACKET;
unsigned int M_PORT;
public:
pacchettopresentazione(void);
// funzione che restituisce la dimensione (ideale, non quella dovuta agli allineamenti
// fatti dal compilatore) in byte del messaggio tenendo anche in conto l'eventuale padding
// questa funzione sar chiamata da chi vorr serializzare il messaggio, per poter allocare il buffer
int getSize(){return 53;};
// funzioni di interfaccia set e get per ogni campo dati del pacchetto
void setNID_PACKET(int N){NID_PACKET = N;};
int getNID_PACKET(){return NID_PACKET;};
void setL_PACKET(int L){L_PACKET = L;};
int getL_PACKET(){return L_PACKET;};
void setM_PORT(int Q){M_PORT = Q;};
int getM_PORT(){return M_PORT;};
// metodi per la serializzazione e deserializzazione del messaggio
// il buffer di byte deve essere stato precedentemente correttamente allocato.
void serialize(array<Byte>^buff);
void deserialize(array<Byte>^buff);
virtual System::String ^ToString() override;
};
| true |
615dfe729eb9b3c27eda0a12cd53b8eda77e1a1e | C++ | sherief/rapidyaml | /src/c4/yml/std/vector.hpp | UTF-8 | 1,275 | 2.640625 | 3 | [
"MIT"
] | permissive | #ifndef _C4_YML_STD_VECTOR_HPP_
#define _C4_YML_STD_VECTOR_HPP_
#include "../node.hpp"
#include <vector>
namespace std {
template< class V, class Alloc >
void write(c4::yml::NodeRef *n, std::vector< V, Alloc > const& vec)
{
*n |= c4::yml::SEQ;
for(auto const& v : vec)
{
n->append_child() << v;
}
}
template< class V, class Alloc >
bool read(c4::yml::NodeRef const& n, std::vector< V, Alloc > *vec)
{
vec->resize(n.num_children());
size_t pos = 0;
for(auto const& ch : n)
{
ch >> (*vec)[pos++];
}
return true;
}
//-----------------------------------------------------------------------------
template< class Alloc >
c4::yml::span to_span(std::vector< char, Alloc > &vec)
{
return c4::yml::span(vec.data(), vec.size());
}
template< class Alloc >
c4::yml::cspan to_cspan(std::vector< char, Alloc > const& vec)
{
return c4::yml::cspan(vec.data(), vec.size());
}
template< class Alloc >
c4::yml::cspan to_span(std::vector< char, Alloc > const& vec)
{
return c4::yml::cspan(vec.data(), vec.size());
}
template< class Alloc >
c4::yml::cspan to_span(std::vector< const char, Alloc > const& vec)
{
return c4::yml::cspan(vec.data(), vec.size());
}
} // namespace std
#endif // _C4_YML_STD_VECTOR_HPP_
| true |
d2919db4f9e026c63590336b88e8515b5d101d09 | C++ | douglascraigschmidt/CPlusPlus | /expression-tree/commands/User_Command.cpp | UTF-8 | 759 | 2.734375 | 3 | [] | no_license | /* -*- C++ -*- */
#ifndef _USER_COMMAND_CPP
#define _USER_COMMAND_CPP
#include "commands/User_Command.h"
#include "User_Command_Impl.h"
User_Command::User_Command (User_Command_Impl *impl)
: command_impl_ (impl)
{
}
User_Command::User_Command (const User_Command &rhs)
= default;
User_Command &
User_Command::operator= (const User_Command &rhs) {
// Check for self assignment first
if (this != &rhs)
/// We just use the Refcounter functionality here.
command_impl_ = rhs.command_impl_;
return *this;
}
User_Command::~User_Command ()
= default;
bool
User_Command::execute () {
return command_impl_->execute ();
}
void
User_Command::print_valid_commands () {
command_impl_->print_valid_commands ();
}
#endif /* _USER_COMMAND_CPP */
| true |
bd0ae5c3dfec199032ccf89ce3d725b3b1832448 | C++ | akshayaggarwal/DS-Algorithms | /cpp/angrychildren.cpp | UTF-8 | 1,390 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <string.h>
//#include <conio.h>
using namespace std;
void sort(char arr[100])
{
int i,j;
char temp,var;
for(i=0;arr[i]!='\0';i++)
{
var = arr[i];
for(j=i+1;arr[j]!='\0';j++)
{
if(arr[j] < var)
{
var = arr[j];
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
//cout<<"*******************\n";
//cout<<arr<<"\n";
}
int check(char arr[100][100],int n)
{
int flag = 1;
int i,j;
for(j=0;j<n;j++)
{
for(i=1;i<n;i++)
{
if(arr[i][j]<arr[i-1][j])
{
flag = 0;
return 0;
}
}
}
return 1;
}
int main()
{
int k,i,j;
char arr[100][100];
cin>>k;
//const int m = k;
int *n = new int[k];
//getch();
//cout<<"values of n are\n";
//for(i=0;i<k;i++)
// cout<<n[i]<<endl;
int res,ctr = 0,flag;
char ch;
//
cin.getline(arr[0],100);
while(ctr!=k)
{
flag = 0;
cin.get(ch);
n[ctr] = (int)ch-48;
cout<<"value of n[ctr] is"<<n[ctr]<<"\n";
//cout<<"value of ctr is "<<ctr<<"/n";
//cout<<"value of n[ctr] is "<<n[ctr]<<"\n";
for(i=0;i<n[ctr];i++)
{
// cout<<"enter "<<i<<"\n";
cin.getline(arr[i],100);
}
for(i=0;i<n[ctr];i++)
{
sort(arr[i]);
}
res = check(arr,n[ctr]);
if(res == 1)
{
flag = 1;
// break;
}
if(flag == 1)
cout<<"YES\n";
else
cout<<"NO\n";
ctr++;
}
return 0;
}
| true |
edd548205be1fcc0209af68b10d6860a7b11ad26 | C++ | o-o-overflow/dc2021q-rick-public | /service/src/Vector.cpp | UTF-8 | 1,190 | 3 | 3 | [] | no_license | #include "Vector.h"
Vector::Vector() {
}
void Vector::setCoord(float x, float y, float z) {
coord[0]=x;
coord[1]=y;
coord[2]=z;
}
void Vector::setCoord(Vector vector) {
coord[0]=vector.coord[0];
coord[1]=vector.coord[1];
coord[2]=vector.coord[2];
}
Vector Vector::crossProduct(Vector u, Vector v) {
Vector result;
float * cu = u.coord;
float *cv = v.coord;
result.coord[0] = cu[1]*cv[2] - cv[1]*cu[2];
result.coord[1] = -cu[0]*cv[2] + cv[0]*cu[2];
result.coord[2] = cu[0]*cv[1] - cv[0]*cu[1];
return result;
}
Vector Vector::findNormal(Point point1, Point point2, Point point3) {
Vector v1,v2;
v1.coord[0] = point1.coord[0] - point2.coord[0];
v1.coord[1] = point1.coord[1] - point2.coord[1];
v1.coord[2] = point1.coord[2] - point2.coord[2];
v2.coord[0] = point2.coord[0] - point3.coord[0];
v2.coord[1] = point2.coord[1] - point3.coord[1];
v2.coord[2] = point2.coord[2] - point3.coord[2];
return crossProduct(v1, v2);
}
#if DEBUG
string Vector::toString() {
char c[200];
string s;
sprintf(c, "Vector: %.2f %.2f %.2f",coord[0],coord[1],coord[2]);
s = c;
return s;
}
#endif
| true |
d6a0b1bf22eda18ff970e554f015e52892025453 | C++ | jmfb/unit-test | /IFactory.h | UTF-8 | 2,049 | 3.171875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <typeinfo>
#include <functional>
#include <memory>
#include <sstream>
#include "TestException.h"
#include "TypeName.h"
#include "Mock.h"
namespace UnitTest
{
// IFactory interface injection interface. This interface merges the type generic
// virtual functions of DoRegister and DoResolve with template functions that ensure
// compile time type safety.
//
// Example:
// IFactory* factory = GetFactory();
//
// //Resolve an interface via previous calls to Register or RegisterObject.
// std::shared_ptr<IFoo> foo = factory->Resolve<IFoo>();
//
// //Register a mock instance that will be returned on subsequent calls to Resolve.
// MockBar mockBar;
// factory->RegisterObject<IBar>(mockBar);
class IFactory
{
private:
virtual void DoRegister(const std::type_info& type, std::function<void*()> resolver) = 0;
virtual void DoUnregister(const std::type_info& type) = 0;
virtual void* DoResolve(const std::type_info& type) const = 0;
public:
template <typename T>
void Register(std::function<std::shared_ptr<T>()> resolver)
{
DoRegister(typeid(T), [=]() -> void*
{
return new std::shared_ptr<T>(resolver());
});
}
template <typename T>
void Unregister()
{
DoUnregister(typeid(T));
}
template <typename T>
void RegisterObject(T& object)
{
DoRegister(typeid(T), [&]() -> void*
{
return new std::shared_ptr<T>(&object, [](T*){});
});
}
template <typename T>
void RegisterObject(Mock<T>& mockObject)
{
DoRegister(typeid(T), [&]() -> void*
{
return new std::shared_ptr<T>(mockObject.GetObject().get(), [](T*){});
});
}
template <typename T>
std::shared_ptr<T> Resolve() const
{
void* result = DoResolve(typeid(T));
if (result == nullptr)
{
std::ostringstream out;
out << "IFactory::Resolve: Could not resolve type " << TypeName<T>::Get();
throw TestException(out.str());
}
std::shared_ptr<std::shared_ptr<T>> pointer;
pointer.reset(reinterpret_cast<std::shared_ptr<T>*>(result));
return *pointer;
}
};
typedef std::shared_ptr<IFactory> IFactoryPtr;
}
| true |
511995c50fe3e959e79cd73e8b9645db2efd5dae | C++ | ruippeixotog/codeforces | /src/948/D.cpp | UTF-8 | 1,356 | 3.0625 | 3 | [] | no_license | #include <algorithm>
#include <cstdio>
#include <vector>
#define MAXN 300000
#define MAXD 30
using namespace std;
vector<int> toBinDigits(int k, int digits = MAXD) {
vector<int> res;
while(digits--) {
res.push_back(k % 2);
k /= 2;
}
reverse(res.begin(), res.end());
return res;
}
struct Trie {
int count;
Trie* children[2];
Trie(): count(0), children {nullptr, nullptr} {}
void add(vector<int>& arr, int k = 0) {
count++;
if(k == arr.size()) return;
if(!children[arr[k]]) {
children[arr[k]] = new Trie();
}
children[arr[k]]->add(arr, k + 1);
}
int popBest(vector<int>& arr, int k = 0, int acc = 0) {
count--;
if(k == arr.size()) return acc;
int digit = children[arr[k]] ? arr[k] : 1 - arr[k];
int res = children[digit]->popBest(arr, k + 1, (acc << 1) + digit);
if(children[digit]->count == 0) {
delete children[digit];
children[digit] = nullptr;
}
return res;
}
};
int a[MAXN];
Trie p;
int main() {
int n; scanf("%d\n", &n);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
for(int i = 0; i < n; i++) {
int pi; scanf("%d", &pi);
vector<int> pid = toBinDigits(pi);
p.add(pid);
}
for(int i = 0; i < n; i++) {
vector<int> aid = toBinDigits(a[i]);
printf("%d ", a[i] ^ p.popBest(aid));
}
printf("\n");
return 0;
}
| true |
86b4e72a7539cdf6c4ac6ce7b82d98c6536eee14 | C++ | potato179/BOJSolution | /02444/2444.cpp | UTF-8 | 402 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
int main(){
int input, i, j;
scanf("%d", &input);
for(i = 1; i <= input; i++){
for(j = input-i; j > 0; j--) printf(" ");
for(j = 0; j < 2*i-1; j++) printf("*");
printf("\n");
}
for(i = input-1; i > 0; i--){
for(j = input-i; j > 0; j--) printf(" ");
for(j = 0; j < 2*i-1; j++) printf("*");
printf("\n");
}
} | true |
25341769788fad910fd39377c74c282e3c3a37df | C++ | MemoryDealer/Cornea | /Inventory.hpp | UTF-8 | 1,156 | 2.8125 | 3 | [] | no_license | //================================================//
#ifndef __INVENTORY_HPP__
#define __INVENTORY_HPP__
//================================================//
#include "Weapon.hpp"
//================================================//
class Inventory
{
public:
Inventory(void);
~Inventory(void);
enum{
MAGIC_CUBES = 0,
END
};
void setDefaults(void);
// Getter functions
const unsigned getWeapon(unsigned slot) const;
// Setter functions
void setWeapon(unsigned weapon, unsigned slot);
// Modifier functions
void addMagicCube(void);
const unsigned int getCount(int type);
private:
void newXor(unsigned int index);
unsigned int m_xor[10];
// Collectible items
unsigned int m_magicCubes;
// Weapons
int m_weapons[4];
};
//================================================//
// Getter functions
inline const unsigned Inventory::getWeapon(unsigned slot) const
{ return m_weapons[slot]; }
// Setter functions
inline void Inventory::setWeapon(unsigned weapon, unsigned slot)
{ m_weapons[slot] = weapon; }
//================================================//
#endif
//================================================// | true |
5cdbe3a7d423c417fe72b40ecf234c72937f078b | C++ | Yasin-cxh/Algorithm-learning | /面试题65:不用加减乘除做加法/不用加减乘除做加法.cpp | UTF-8 | 624 | 3.734375 | 4 | [] | no_license | //题目
//写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
//思路:使用二进制
//步骤:1.不考虑进位相加(相 或)
//2.计算进位(相与)
//3.相加以上两个结果
//4.重复上述计算,直到进位==0
class Solution {
public:
int add(int a, int b) {
unsigned int num1 =a, num2 = b;
unsigned int sum,carry =0;
do{
sum = num1^num2;
carry = (num1&num2)<<1;
num1 = sum;
num2 = carry;
}while(carry != 0);
return sum;
}
}; | true |
31cb257ceb3e6bf9eec5f343d6532157e1708558 | C++ | iprafols/cross_correlations | /src/astro_object_dataset.cpp | UTF-8 | 3,446 | 2.734375 | 3 | [
"MIT"
] | permissive | /**
astro_object_dataset.cpp
Purpose: This files contains the body for the functions defined in astro_object_dataset.h
@author Ignasi Pérez-Ràfols
@version 1.0 08/08/2014
*/
#include "astro_object_dataset.h"
std::vector<AstroObject> AstroObjectDataset::list(int plate_number) const{
/**
EXPLANATION:
Access function for list_
INPUTS:
plate_number - index of the selected list_ element
OUTPUTS:
NONE
CLASSES USED:
AstroObject
AstroObjectDataset
FUNCITONS USED:
NONE
*/
PlatesMapVector<AstroObject>::map::const_iterator it = list_.find(plate_number);
if (it == list_.end()){
std::vector<AstroObject> v;
return v;
}
else{
return (*it).second;
}
}
AstroObject AstroObjectDataset::list(int plate_number, size_t pos) const {
/**
EXPLANATION:
Access function for list_
INPUTS:
plate_number - index of the selected list_ element
pos - position in the selected list_ element
OUTPUTS:
NONE
CLASSES USED:
AstroObject
AstroObjectDataset
FUNCITONS USED:
NONE
*/
PlatesMapVector<AstroObject>::map::const_iterator it = list_.find(plate_number);
if (it == list_.end()){
AstroObject v(_BAD_DATA_);
return v;
}
else{
if (pos < (*it).second.size()){
return (*it).second[pos];
}
else{
AstroObject v(_BAD_DATA_);
return v;
}
}
}
void AstroObjectDataset::GiveRADEC(std::ostream& out) const{
/**
EXPLANATION:
Adds the objects' RA-DEC values to out
INPUTS:
out - an ostream to add the objects' RA-DEC values to
OUTPUTS:
NONE
CLASSES USED:
AstroObject
AstroObjectDataset
FUNCITONS USED:
NONE
*/
for (PlatesMapVector<AstroObject>::map::const_iterator it = list_.begin(); it != list_.end(); it ++){
for (size_t i = 0; i < (*it).second.size(); i ++){
out << (*it).second[i].angle() << std::endl;
}
}
}
void AstroObjectDataset::GiveZ(std::ostream& out) const{
/**
EXPLANATION:
Adds the objects' redshift values to out
INPUTS:
out - an ostream to add the objects' redshift values to
OUTPUTS:
NONE
CLASSES USED:
AstroObject
AstroObjectDataset
FUNCITONS USED:
NONE
*/
for (PlatesMapVector<AstroObject>::map::const_iterator it = list_.begin(); it != list_.end(); it ++){
for (size_t i = 0; i < (*it).second.size(); i ++){
out << (*it).second[i].z() << std::endl;
}
}
}
void AstroObjectDataset::SetDistances(const ZDistInterpolationMap& redshift_distance_map){
/**
EXPLANATION:
Sets the distance to every object in the dataset
INPUTS:
redshif_distance_map - a InterpolationMap instance with the redshift-distance relation
OUTPUTS:
NONE
CLASSES USED:
AstroObject
AstroObjectDataset
InterpolationMap
FUNCITONS USED:
NONE
*/
for (PlatesMapVector<AstroObject>::map::iterator it = list_.begin(); it != list_.end(); it ++){
for (size_t i = 0; i < (*it).second.size(); i ++){
(*it).second[i].SetDistance(redshift_distance_map);
}
}
}
| true |
4b4a8552347d2659448f9ac302757fcd00c1ac44 | C++ | the6tsense/LED-Cube-Software | /SingleColourEffects/gameoflifeeffect.cpp | UTF-8 | 4,458 | 3.140625 | 3 | [] | no_license | #include "gameoflifeeffect.h"
GameOfLifeEffect::GameOfLifeEffect(QString name)
{
setKey(name);
setTime(300);
}
void GameOfLifeEffect::calc(int status)
{
if(status == 0)
{
clearCube();
for(int i = 0; i < 0.2 * pow(getCubeSize(), 3); i++)
{
int x = rand() % getCubeSize();
int y = rand() % getCubeSize();
int z = rand() % getCubeSize();
cube()(x, y, z) = true;
}
/*cube()(0,0,0) = true;
cube()(0,0,1) = true;
cube()(0,1,0) = true;
cube()(0,1,1) = true;
cube()(1,0,0) = true;
cube()(1,0,1) = true;
cube()(1,1,0) = true;
cube()(1,1,1) = true;*/
}
else
{
Array3d buffer(cube());
bool isStillAlive = false;
for(int x = 0; x < getCubeSize(); x++)
{
for(int y = 0; y < getCubeSize(); y++)
{
for(int z = 0; z < getCubeSize(); z++)
{
int lifeNeighbors = countLivingNeighbors(buffer, x, y, z);
/*if(x == 0)
{
std::cout << "Debug game of Life: y: " << y << " z: "
<< z << " " << lifeNeighbors << std::endl;
}*/
if(cube()(x, y, z))
{
isStillAlive = true;
if(lifeNeighbors < 4 || lifeNeighbors > 6)
{
//cell dies
cube()(x, y, z) = false;
}
}
else
{
if(lifeNeighbors == 5)
{
//a cell is born
cube()(x, y, z) = true;
}
}
}
}
}
//if every cell is already dead, start next animation
if(!isStillAlive)
{
setTime(0);
}
}
}
int GameOfLifeEffect::countLivingNeighbors(Array3d& buf, int x, int y, int z)
{
int lifeNeighbors = 0;
int xPlus = x + 1;
int xMin = x - 1;
int yPlus = y + 1;
int yMin = y - 1;
int zPlus = z + 1;
int zMin = z - 1;
if(xMin < 0)
{
xMin = getCubeSize() - 1;
}
else if(xPlus >= getCubeSize())
{
xPlus = 0;
}
if(yMin < 0)
{
yMin = getCubeSize() - 1;
}
else if(yPlus >= getCubeSize())
{
yPlus = 0;
}
if(zMin < 0)
{
zMin = getCubeSize() - 1;
}
else if(zPlus >= getCubeSize())
{
zPlus = 0;
}
if(buf(x, y, zPlus))
{
lifeNeighbors++;
}
if(buf(x, y, zMin))
{
lifeNeighbors++;
}
if(buf(x, yPlus, z))
{
lifeNeighbors++;
}
if(buf(x, yPlus, zPlus))
{
lifeNeighbors++;
}
if(buf(x, yPlus, zMin))
{
lifeNeighbors++;
}
if(buf(x, yMin, z))
{
lifeNeighbors++;
}
if(buf(x, yMin, zPlus))
{
lifeNeighbors++;
}
if(buf(x, yMin, zMin))
{
lifeNeighbors++;
}
if(buf(xPlus, y, z))
{
lifeNeighbors++;
}
if(buf(xPlus, y, zPlus))
{
lifeNeighbors++;
}
if(buf(xPlus, y, zMin))
{
lifeNeighbors++;
}
if(buf(xPlus, yPlus, z))
{
lifeNeighbors++;
}
if(buf(xPlus, yPlus, zPlus))
{
lifeNeighbors++;
}
if(buf(xPlus, yPlus, zMin))
{
lifeNeighbors++;
}
if(buf(xPlus, yMin, z))
{
lifeNeighbors++;
}
if(buf(xPlus, yMin, zPlus))
{
lifeNeighbors++;
}
if(buf(xPlus, yMin, zMin))
{
lifeNeighbors++;
}
if(buf(xMin, y, z))
{
lifeNeighbors++;
}
if(buf(xMin, y, zPlus))
{
lifeNeighbors++;
}
if(buf(xMin, y, zMin))
{
lifeNeighbors++;
}
if(buf(xMin, yPlus, z))
{
lifeNeighbors++;
}
if(buf(xMin, yPlus, zPlus))
{
lifeNeighbors++;
}
if(buf(xMin, yPlus, zMin))
{
lifeNeighbors++;
}
if(buf(xMin, yMin, z))
{
lifeNeighbors++;
}
if(buf(xMin, yMin, zPlus))
{
lifeNeighbors++;
}
if(buf(xMin, yMin, zMin))
{
lifeNeighbors++;
}
return lifeNeighbors;
}
| true |
4a5cc4fc6d1e4c2e07e46a993f06f4acf6727644 | C++ | amyrhzhao/CooEngine | /Framework/AI/Inc/DecisionModule.h | UTF-8 | 2,488 | 3 | 3 | [
"MIT"
] | permissive | #ifndef INCLUDED_COOENGINE_AI_DECISIONMODULE_H
#define INCLUDED_COOENGINE_AI_DECISIONMODULE_H
#include "Goal.h"
#include "GoalComposite.h"
#include "Strategy.h"
namespace Coo::AI
{
template <typename AgentType>
class DecisionModule
{
public:
typedef Goal<AgentType> GoalType;
typedef Strategy<AgentType> StrategyType;
DecisionModule(AgentType& agent);
~DecisionModule();
void AddStrategy(StrategyType* strategy);
void Purge();
void Update();
private:
void Arbitrate();
AgentType& mAgent;
std::vector<StrategyType*> mStrategies;
StrategyType* mCurrentStrategy;
GoalType* mCurrentGoal;
};
template <typename AgentType>
DecisionModule<AgentType>::DecisionModule(AgentType& agent)
: mAgent(agent)
, mCurrentStrategy(nullptr)
, mCurrentGoal(nullptr)
{
}
template <typename AgentType>
DecisionModule<AgentType>::~DecisionModule()
{
Purge();
}
template <typename AgentType>
void DecisionModule<AgentType>::AddStrategy(StrategyType* strategy)
{
mStrategies.push_back(strategy);
}
template <typename AgentType>
void DecisionModule<AgentType>::Purge()
{
// Remove all strategies
for (auto strategy : mStrategies)
{
SafeDelete(strategy);
}
mStrategies.clear();
// Remove current goal
if (mCurrentGoal != nullptr)
{
mCurrentGoal->Terminate();
SafeDelete(mCurrentGoal);
}
}
template <typename AgentType>
void DecisionModule<AgentType>::Update()
{
// Evaluate our priorities
Arbitrate();
// Update the current action
if (mCurrentGoal != nullptr)
{
mCurrentGoal->Process();
}
}
template <typename AgentType>
void DecisionModule<AgentType>::Arbitrate()
{
float mostDesirable = 0.0f;
StrategyType* bestStrategy = nullptr;
// Find the most desirable strategy
for (auto strategy : mStrategies)
{
float desirability = strategy->CalculateDesirability();
if (desirability > mostDesirable)
{
mostDesirable = desirability;
bestStrategy = strategy;
}
}
// Check if our strategy has changed
if (mCurrentStrategy != bestStrategy)
{
// Set new strategy
mCurrentStrategy = bestStrategy;
// Exit the current goal
if (mCurrentGoal != nullptr)
{
mCurrentGoal->Terminate();
SafeDelete(mCurrentGoal);
}
// Set new goal
if (mCurrentStrategy != nullptr)
{
mCurrentGoal = mCurrentStrategy->CreateGoal();
}
}
}
} // namespace Coo::AI
#endif // !INCLUDED_COOENGINE_AI_DECISIONMODULE_H
| true |
5bd00286e55a1ecd00bfb96ff79c715379d06703 | C++ | amanraj-iit/DSA_Uplift_Project | /Assignments/Solutions/Sonakshi Mishra/Assignment 4/Problem_4.cpp | UTF-8 | 456 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std; //reverse words in a given string
int main()
{
string s1,s2;
int i,j,l1;
getline(cin, s1);
l1=s1.length();
for(i=l1-1;i>0;)
{
for(j=0;j<l1;j++)
{
s2[j]=s1[i];
i--;
}
}
for(j=0;j<l1;j++)
{
cout<<s2[j];
}
return 0;
} | true |
788701f5a514db028345435783552a60437ac0e6 | C++ | guivmc/PokemonTest | /CodeBlocksWithSFMLProjects/State.h | UTF-8 | 839 | 3.125 | 3 | [] | no_license | #ifndef STATE_H_INCLUDED
#define STATE_H_INCLUDED
#include <vector>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
class State
{
public:
virtual void init()=0;
virtual void cleanup()=0;
//Pushing and popping states causes pausing/resuming.
virtual void pause()=0;
virtual void resume()=0;
virtual void getEvents()=0;
virtual void update()=0;
virtual void draw(RenderWindow &gameWindow) = 0;
};
class StateManager
{
private:
vector<State*> states;
public:
void changeState(State* state);
//Pause the current state and go to a new state.
void pushState(State* state);
//Leave current state and go to previous state.
void popState();
void clearStates();
};
#endif // STATE_H_INCLUDED
| true |
06a6807029af1dd0863d17a3960ba5cf6c65cce0 | C++ | Gachiman/parallel_programming_course | /modules/task_3/bederdinov_d_quicksort_batcher_task3_tbb/main.cpp | UTF-8 | 8,367 | 3.0625 | 3 | [] | no_license | // Copyright 2019 Bederdinov Daniil
#define klength 50000000
#include <ctime>
#include <iomanip>
#include <iostream>
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/task.h"
#include "tbb/task_scheduler_init.h"
#include "tbb/tbb.h"
void shuffle(int* array, int size) {
srand((unsigned int)time(NULL));
int i = size, j, temp;
while (--i > 0) {
j = std::rand() % size;
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
void fillArray(int* array, int len) {
for (int i = 0; i < len; i++) {
array[i] = i;
}
}
void quickSort(int* array, int size) {
int i = 0, j = size - 1;
int pivot = array[size / 2];
do {
while (array[i] < pivot)
i++;
while (array[j] > pivot)
j--;
if (i <= j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
i++;
j--;
}
} while (i <= j);
if (j > 0)
quickSort(array, j + 1);
if (i < size)
quickSort(&array[i], size - i);
}
void printArray(int* array, const int size) {
for (int i = 0; i < size; i++) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
}
bool check(int* A, int* B, int size) {
for (int i = 0; i < size; ++i)
if (A[i] != B[i]) {
return false;
}
return true;
}
int compare(const int* i, const int* j) {
return *i - *j;
}
class EvenSelector : public tbb::task {
private:
int* array;
int size1, size2;
public:
EvenSelector(int* _arr, int _size1, int _size2) : array(_arr), size1(_size1), size2(_size2) {
}
task* execute() {
// int* array2 = array + size1;
int numOfEven = (size1 + size2 + 1) / 2; // Число четных элементов
int* evenElements = new int[numOfEven]; // Массив для хранения четных элементов
int firstArrayItterator = 0, secondArrayItterator = 0, i = 0;
while (firstArrayItterator < size1 && secondArrayItterator < size2) {
// if (array[firstArrayItterator] <= array2[secondArrayItterator]) {
if (array[firstArrayItterator] <= array[secondArrayItterator + size1]) {
evenElements[i] = array[firstArrayItterator];
firstArrayItterator += 2;
} else {
// evenElements[i] = array2[secondArrayItterator];
evenElements[i] = array[secondArrayItterator + size1];
secondArrayItterator += 2;
}
i++;
}
if (firstArrayItterator >= size1) {
for (int j = secondArrayItterator; j < size2; j += 2, i++)
// evenElements[i] = array2[j];
evenElements[i] = array[j + size1];
} else {
for (int j = firstArrayItterator; j < size1; j += 2, i++)
evenElements[i] = array[j];
}
// Копирование из временного массива в основной
for (int j = 0; j < numOfEven; j++)
array[j * 2] = evenElements[j];
return NULL;
}
};
class OddSelector : public tbb::task {
private:
int* array;
int size1, size2;
public:
OddSelector(int* _arr, int _size1, int _size2) : array(_arr), size1(_size1), size2(_size2) {
}
task* execute() {
// int* array2 = array + size1;
// int numOfOdd = (size1 + size2) - (size1 + size2 + 1) / 2; // Число нечетных элементов
int numOfOdd = (size1 + size2) / 2; // Число нечетных элементов
int* oddElements = new int[numOfOdd]; // Массив для хранения нечетных элементов
int firstArrayItterator = 1, secondArrayItterator = 1, i = 0;
while (firstArrayItterator < size1 && secondArrayItterator < size2) {
// if (array[firstArrayItterator] <= array2[secondArrayItterator]) {
if (array[firstArrayItterator] <= array[secondArrayItterator + size1]) {
oddElements[i] = array[firstArrayItterator];
firstArrayItterator += 2;
} else {
// oddElements[i] = array2[secondArrayItterator];
oddElements[i] = array[secondArrayItterator + size1];
secondArrayItterator += 2;
}
i++;
}
if (firstArrayItterator >= size1) {
for (int j = secondArrayItterator; j < size2; j += 2, i++)
// oddElements[i] = array2[j];
oddElements[i] = array[j + size1];
} else {
for (int j = firstArrayItterator; j < size1; j += 2, i++)
oddElements[i] = array[j];
}
// Копирование из временного массива в основной
for (int j = 0; j < numOfOdd; j++)
array[j * 2 + 1] = oddElements[j];
return NULL;
}
};
class Comparator {
private:
int* array;
public:
explicit Comparator(int* _arr) : array(_arr) {}
void operator()(const tbb::blocked_range<int>& r) const {
for (int i = r.begin(); i < r.end(); i++)
if (array[i - 1] > array[i]) {
int tmp = array[i - 1];
array[i - 1] = array[i];
array[i] = tmp;
}
}
};
class Sorter : public tbb::task {
private:
int* array;
int size;
int portion;
public:
Sorter(int* _arr, int _size, int _portion) : array(_arr), size(_size), portion(_portion) {}
task* execute() {
if (size <= portion) {
quickSort(array, size);
} else {
int halfSize = size / 2 + (size / 2) % 2;
Sorter& sorter1 = *new (allocate_child()) Sorter(array, halfSize, portion);
Sorter& sorter2 = *new (allocate_child()) Sorter(array + halfSize, size - halfSize, portion);
set_ref_count(3);
spawn(sorter1);
spawn_and_wait_for_all(sorter2);
EvenSelector& evenSelector = *new (allocate_child()) EvenSelector(array, halfSize, size - halfSize);
OddSelector& oddSelector = *new (allocate_child()) OddSelector(array, halfSize, size - halfSize);
set_ref_count(3);
spawn(evenSelector);
spawn_and_wait_for_all(oddSelector);
tbb::parallel_for(tbb::blocked_range<int>(1, size), Comparator(array));
}
return NULL;
}
};
void TBB_QS(int* array, int size, int threads) {
int portion = size / threads;
Sorter& sorter = *new (tbb::task::allocate_root())Sorter(array, size, portion);
tbb::task::spawn_root_and_wait(sorter);
}
int main(int argc, char* argv[]) {
int threads = 4;
int size = klength;
if (argc == 2) {
threads = atoi(argv[1]);
} else if (argc == 3) {
threads = atoi(argv[1]);
size = atoi(argv[2]);
}
int* array = new int[size];
int* copy1 = new int[size];
int* copy2 = new int[size];
fillArray(array, size);
shuffle(array, size);
for (int i = 0; i < size; i++) {
copy1[i] = array[i];
copy2[i] = array[i];
}
if (size <= 100) {
std::cout << "Unsorted array:" << std::endl;
printArray(array, size);
std::cout << std::endl;
}
tbb::tick_count startTime = tbb::tick_count::now(), endTime;
TBB_QS(array, size, threads);
endTime = tbb::tick_count::now();
auto parallelTime = (endTime - startTime).seconds();
if (size <= 100) {
printArray(array, size);
}
qsort(copy1, size, sizeof(int), (int (*)(const void*, const void*))compare);
std::cout << "TBB time: " << parallelTime << std::endl;
startTime = tbb::tick_count::now();
quickSort(copy2, size);
endTime = tbb::tick_count::now();
auto serialTime = (endTime - startTime).seconds();
std::cout << "Serial time time: " << std::fixed << std::setprecision(6) << serialTime << std::endl;
std::cout << "Boost: " << serialTime / parallelTime << std::endl;
if (check(copy1, array, size))
std::cout << "Arrays are equal" << std::endl;
else
std::cout << "Arrays are NOT equal" << std::endl;
delete[] copy1;
delete[] copy2;
delete[] array;
return 0;
}
| true |
2e84d1cda6659a2f11b28b70dcb7dbd98f35c201 | C++ | CraftingGamerTom/Programming-with-Data-Structures | /Homework01 - object/testTwoDArray.h | UTF-8 | 2,866 | 2.953125 | 3 | [] | no_license | /*
* File: %<%NAME%>%.%<%EXTENSION%>%
* Author: %<%USER%>%
*
* Created on %<%DATE%>%, %<%TIME%>%
*
* This file uses the CxxTest library <TestSuite> to create test cases
* for a students project. For full cxxtest documentation see the userguide
* located in your C:\MinGW\cxxtest\doc or visit:
* http://cxxtest.com/guide.html
*
*/
#ifndef TESTTWODARRAY_H
#define TESTTWODARRAY_H
#include <cxxtest/TestSuite.h>
#include "TwoDArray.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <strings.h>
//Include your classes header file(s) below and uncomment.
//#include "myClass.h"
class testTwoDArray: public CxxTest::TestSuite {
public:
TwoDArray *theArray = NULL;
double masterArray[5][5];
void setUp() {
theArray = new TwoDArray();
}
void tearDown() {
delete theArray;
}
//All tests should start with the word 'test' followed by
//the name of the function being tested.
void testRow() {
double arrayOfDoubles[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
theArray->set_row(&masterArray[0][0], 0, 5, &arrayOfDoubles[0]);
double* rowLocation = theArray->get_row(&masterArray[0][0], 0, 5);
double* expLocation = &arrayOfDoubles[0];
TS_ASSERT_SAME_DATA(rowLocation, expLocation, 5 * sizeof(double));
//Use TS_ASSERT_EQUALS(Result, ExpResult) to test your functions.
}
void testElement() {
// Sets the array elements
double arrayOfDoubles[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
theArray->set_row(&masterArray[0][0], 0, 5, &arrayOfDoubles[0]);
double expVal = 10;
theArray->set_element(&masterArray[0][0], 0, 5, 0, expVal);
double val = theArray->get_element(&masterArray[0][0], 0, 5, 0);
TS_ASSERT_EQUALS(val, expVal);
}
void testSum() {
// Sets the array elements
double arrayOfDoubles[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
theArray->set_row(&masterArray[0][0], 0, 5, &arrayOfDoubles[0]);
double expSum = 15;
double sum = theArray->sum(&masterArray[0][0], 1, 5);
TS_ASSERT_EQUALS(sum, expSum);
}
void testFindMax() {
// Sets the array elements
double arrayOfDoubles[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
theArray->set_row(&masterArray[0][0], 0, 5, &arrayOfDoubles[0]);
double expVal = 5;
double val = theArray->find_max(&masterArray[0][0], 1, 5);
TS_ASSERT_EQUALS(val, expVal);
}
void testFindMin() {
double arrayOfDoubles[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
theArray->set_row(&masterArray[0][0], 0, 5, &arrayOfDoubles[0]);
double expVal = 1;
double val = theArray->find_min(&masterArray[0][0], 1, 5);
TS_ASSERT_EQUALS(val, expVal);
}
void testToString() {
double arrayOfDoubles[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };
theArray->set_row(&masterArray[0][0], 0, 5, &arrayOfDoubles[0]);
string expVal = "[1.0, 2.0, 3.0, 4.0, 5.0]";
string val = theArray->to_string(&masterArray[0][0], 1, 5);
TS_ASSERT_EQUALS(expVal, val);
}
};
#endif /* TESTTWODARRAY_H */
| true |
eb7b4708082d86042c12cfa6e7b144cace7c1fd6 | C++ | emreharman/Cpp | /Proje1/b191210049_odev_1/b191210049_odev_1.cpp | ISO-8859-9 | 2,386 | 2.953125 | 3 | [] | no_license | /****************************************************************************
**
** RENC ADI.......: Emre Harman
** RENC NUMARASI..: b191210049
** DERS GRUBU........: B1
****************************************************************************/
#include<iostream>
#include<Windows.h>
#include<iomanip>
using namespace std;
int main() {
int satir = 0;
int sutun = 0;
int bosluk1 = 0;
int bosluk2 = 0;
do {
//satir sayisi 5-15 arasinda olana kadar satir sayisi giriliyor.
do {
cout << "Satir Sayisi...: ";
cin >> satir;
if (satir < 5 || satir > 15) {
cout << "Satir numarasi hatali... Tekrar deneyin..." << endl;
continue;
}
else {
break;
}
} while (1);
//sutun sayisi 5-40 arasinda olana kadar sutun sayisi giriliyor.
do {
cout << "Sutun Sayisi...: ";
cin >> sutun;
if (sutun < 5 || sutun > 40) {
cout << "Sutun numarasi hatali... Tekrar deneyin..." << endl;
continue;
}
else {
break;
}
} while (1);
//sutun sayisi satir sayisinin 2 kati degilse donguye bastan basliyor
//2 katiysa donguden cikiyor.
if (sutun / 2 != satir) {
cout << "Sutun sayisi satir sayisinin iki kati olmalidir... Tekrar deneyin..." << endl;
continue;
}
else {
break;
}
} while (1);
bosluk1 = (sutun / 2)-2;
bosluk2 = 3;
//satir sayisi kadar seklin ust kismina islem yapiyoruz.
for (int i = 0; i < satir; i++) {
//seklin ilk ve son satirina sutun sayisi kadar '*' koyuyoruz.
if (i == 0 || i == satir - 1) {
for (int j = 0; j < sutun; j++) {
cout << "*";
}
}
//ilk ve son satir disindaki satirlara kenardaki '*'lari ve seklin ortasindaki
//ucgen seklindeki '*'lari koyuyoruz.
else {
cout << "*" << setw(bosluk1) << "*" << setw(bosluk2) << "*" << setw(bosluk1) << "*";
bosluk1--;
bosluk2 += 2;
}
Sleep(100);
cout << endl;
}
bosluk1 = 1;
bosluk2 = sutun - 3;
//seklin ust kisminda yaptigimiz islemleri tersten uygulayarak alt kisimdaki sekli ciziyoruz.
for (int i = 0; i < satir; i++) {
if (i == 0 || i == satir - 1) {
for (int j = 0; j < sutun; j++) {
cout << "*";
}
}
else {
cout << "*" << setw(bosluk1) << "*" << setw(bosluk2) << "*" << setw(bosluk1) << "*";
bosluk1++;
bosluk2 -= 2;
}
Sleep(100);
cout << endl;
}
system("pause");
return 0;
}
| true |
a0f0ba3747a5e068f3b9a2744fcf0f8027f695b0 | C++ | guangkuan/C--Primer-5th | /Chapter17/test17.05/Sales_data.h | UTF-8 | 2,017 | 3.375 | 3 | [] | no_license | #ifndef SALES_DATA_H_INCLUDED
#define SALES_DATA_H_INCLUDED
#include <string>
#include <iostream>
class Sales_data
{
friend Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs);
friend std::ostream& operator<<(std::ostream& os, const Sales_data& s);
friend std::istream& operator>>(std::istream& is, Sales_data& s);
friend Sales_data add(const Sales_data&, const Sales_data&);
friend std::ostream& print(std::ostream&, const Sales_data&);
friend std::istream& read(std::istream&, Sales_data&);
public:
Sales_data() = default;
Sales_data(const std::string &s): bookNo(s) { }
Sales_data(const std::string &s, unsigned n, double p): bookNo(s), units_sold(n), revenue(p * n) { }
Sales_data(const Sales_data &s ): bookNo(s.bookNo), units_sold(s.units_sold), revenue(s.revenue) { }
Sales_data(Sales_data&& s): bookNo(s.bookNo), units_sold(s.units_sold), revenue(s.revenue) { }
~Sales_data(){ }
Sales_data(std::istream&);
std::string isbn() const { return bookNo; }
Sales_data& combine(const Sales_data&);
Sales_data& operator=(const Sales_data& rhs);
Sales_data& operator=(const std::string& rhs);
Sales_data& operator+=(const Sales_data& rhs);
explicit operator std::string () const { return bookNo; }
explicit operator double () const { return revenue; }
double avg_price() const;
private:
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
inline Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs)
{
Sales_data sum = lhs;
sum += rhs;
return sum;
}
std::ostream& operator<<(std::ostream& os, const Sales_data& item);
std::istream& operator>>(std::istream& is, Sales_data& s);
Sales_data add(const Sales_data&, const Sales_data&);
std::ostream &print(std::ostream&, const Sales_data&);
std::istream &read(std::istream&, Sales_data&);
inline bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs)
{
return lhs.isbn() < rhs.isbn();
}
#endif // SALES_DATA_H_INCLUDED
| true |
d4a353132bf0f6cde517c9bf99c81b4917f12fb1 | C++ | Memotech-Bill/CamTest | /PictWnd.cpp | UTF-8 | 2,766 | 2.65625 | 3 | [
"BSD-2-Clause"
] | permissive | // PictWnd.cpp - A window for displaying the video picture.
#include <stdio.h>
#include <wx/dc.h>
#include "PictWnd.h"
BEGIN_EVENT_TABLE(PictWnd, wxPanel)
EVT_SIZE(PictWnd::OnSize)
END_EVENT_TABLE()
/*** PictWnd ***************************************************
Constructor.
Inputs:
parent = Parent window.
Coding history:
WJB 20/ 5/10 First draft.
WJB 26/ 3/11 PictWnd now takes ownership of the image.
*/
PictWnd::PictWnd (wxWindow *parent)
: wxScrolledWindow (parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxHSCROLL | wxVSCROLL | wxALWAYS_SHOW_SB)
{
// printf ("PictWnd constructor.\n");
m_image = NULL;
m_bitmap = NULL;
}
/*** ~PictWnd **************************************************
Destructor. Free resources.
Coding history:
WJB 25/ 5/10 First draft.
WJB 26/ 3/11 PictWnd now takes ownership of the image.
WJB 17/ 7/11 Close log files.
*/
PictWnd::~PictWnd (void)
{
// printf ("PictWnd destructor.\n");
if ( m_image != NULL ) delete m_image;
if ( m_bitmap != NULL ) delete m_bitmap;
}
/*** SetImage **************************************************
Sets an image to be displayed in the window.
Inputs:
img = Image to display.
Coding history:
WJB 24/ 5/10 First draft.
WJB 26/ 3/11 PictWnd now takes ownership of the image.
*/
void PictWnd::SetImage (wxImage *pimg)
{
// Copy image.
if ( m_image != NULL ) delete m_image;
m_image = pimg;
if ( m_bitmap != NULL ) delete m_bitmap;
m_bitmap = new wxBitmap (*pimg);
SetVirtualSize (m_bitmap->GetWidth (), m_bitmap->GetHeight ());
// printf ("Loaded bitmap: %d x %d\n", m_bitmap->GetWidth (), m_bitmap->GetHeight ());
// Redraw screen.
Refresh (false);
// printf ("Called Refresh.\n");
}
/*** OnDraw *****************************************************
Display the current image (if any) in the window.
Inputs:
dc = Device context to draw to.
Coding history:
WJB 24/ 5/10 First draft.
*/
void PictWnd::OnDraw (wxDC &dc)
{
// printf ("Entered OnDraw.\n");
if ( m_bitmap != NULL )
{
// printf ("Draw bitmap.\n");
dc.DrawBitmap (*m_bitmap, 0, 0, false);
}
}
/*** OnSize *************************************************************************************
*/
void PictWnd::OnSize (wxSizeEvent &e)
{
wxSize sz = e.GetSize ();
// printf ("PictWnd size: %d x %d\n", sz.GetWidth (), sz.GetHeight ());
int iWidth, iHeight;
GetClientSize (&iWidth, &iHeight);
iWidth /= 10;
iHeight /= 10;
SetScrollRate (iWidth, iHeight);
}
| true |
ccfdac68c550808ce7d21d5875b2e4a930735ede | C++ | LongerZrLong/cs107-FinalProject | /OffPiste/core/tests/src/test_integration.cpp | UTF-8 | 10,175 | 2.984375 | 3 | [
"MIT"
] | permissive | /* googletest header files */
#include "gtest/gtest.h"
/* source / header files */
#include "BinaryOperator.hpp"
#include "Function.cpp"
#include "Function.hpp"
#include "Node.cpp"
#include "Node.hpp"
#include "UnaryOperator.hpp"
#include "Variable.hpp"
#include "test_vars.h"
// add an AD shortcut for brevity
using namespace OP;
/**
This file tests that the backwards and forwards mode generate the same results.
*/
//--------------------------- Test Operators ----------------------------------
//-----------------------------------------------------------------------------
void check_jacobians_equal(Mat a, Mat b) {
ASSERT_EQ(a.size(), b.size()); // check same number of rows
for (int i = 0; i < a.size(); i++) {
ASSERT_EQ(a.at(i).size(), b.at(i).size()); // check same number of columns
for (int j = 0; j < a.at(i).size(); j++) {
// check element i,j is same for each matrix
EXPECT_NEAR(a.at(i).at(j), b.at(i).at(j), 1E-2);
}
}
}
//--------------------------- Binary Functions --------------------------------
TEST(Operators, Add) {
// Init
Variable a(2.0, 1.5);
Variable b(3.0, 2.0);
// Add
Expression u = a + b;
Function f({a, b}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Subtract) {
// Init
Variable a(2.0, 1.5);
Variable b(3.0, 2.0);
// Subtract
Expression u = a - b;
Function f({a, b}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
Mat correct_answer = {{1.5, -2.0}};
ASSERT_EQ(jacob_f, correct_answer);
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Multiply) {
// Init
Variable a(2.0, 1.5);
Variable b(3.0, 2.0);
// Multiply
Expression u = a * b;
Function f({a, b}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Divide) {
// Init
Variable a(2.0, 1.5);
Variable b(3.0, 2.0);
// Divide
Expression u = a / b;
Function f({a, b}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Power) {
// Init
Variable a(2.0, 1.5);
Variable b(3.0, 2.0);
// Power
Expression u = pow(a, b);
Function f({a, b}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Comparison) {
// Init
Node a(2.0);
Node b(3.0);
Node c(3.0);
// Validate
ASSERT_EQ(a > b, false);
ASSERT_EQ(a < b, true);
ASSERT_EQ(a == b, false);
ASSERT_EQ(c == b, true);
ASSERT_EQ(a != b, true);
ASSERT_EQ(a >= b, false);
ASSERT_EQ(a <= b, true);
ASSERT_EQ(b <= c, true);
}
//--------------------- Negate, Sqrt, Exponent, Log ---------------------------
TEST(Operators, Negate) {
// Init
Variable a(2.0, 1.5);
// Negate
Expression u = -a;
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Sqrt) {
// Init
Variable a(2.0, 1.5);
// Sqrt
Expression u = sqrt(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Exponent) {
// Init
Variable a(2.0, 1.5);
// Exponent
Expression u = exp(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Logarithm) {
// Init
Variable a(2.0, 1.5);
// Logarithm
Expression u = log(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
//--------------------------- Trigonometric Functions -------------------------
TEST(Operators, Sine) {
// Init
Variable a(0.9, 0.2);
// Sine
Expression u = sin(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
ASSERT_EQ(jacob_f, jacob_b);
}
TEST(Operators, Cosine) {
// Init
Variable a(0.9, 0.2);
// Cosine
Expression u = cos(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Tangent) {
// Init
Variable a(0.9, 0.2);
// Tangent
Expression u = tan(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Asin) {
// Init
Variable a(0.9, 0.2);
// Asin
Expression u = asin(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Acos) {
// Init
Variable a(0.9, 0.2);
// Acos
Expression u = acos(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Atan) {
// Init
Variable a(0.9, 0.2);
// Atan
Expression u = atan(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Sinh) {
// Init
Variable a(0.9, 0.2);
// Sinh
Expression u = sinh(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Cosh) {
// Init
Variable a(0.9, 0.2);
// Cosh
Expression u = cosh(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
TEST(Operators, Tanh) {
// Init
Variable a(0.9, 0.2);
// Tanh
Expression u = tanh(a);
Function f({a}, {u});
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
check_jacobians_equal(jacob_f, jacob_b);
}
//--------------------------- Test Functions ----------------------------------
//-----------------------------------------------------------------------------
TEST(Functions, ForwardDerivative) {
// Init
Variable a(0.9, 0.2);
// Sine
Expression u = sin(a);
Function f({a}, {u});
Vec seeds = {1};
f.set_seed(seeds);
float der = f.forward_derivative(u, a);
EXPECT_NEAR(der, 0.6216, 1E-4);
}
//--------------------------- Test Complex Function ---------------------------
//-----------------------------------------------------------------------------
TEST(Operators, ComplexFunction) {
// Init
Variable a(0.9, 0.2);
Variable b(1.2, 0.02);
Variable c(10.0, 2.3);
// Sine
Expression u = sin(a) + b * exp(c) + pow(b, 2);
Function f({a, b, c}, {u});
Vec seeds = {1, 2, 3, 4};
// should throw an error because there are 4 seeds but only 3 inputs
EXPECT_THROW(f.set_seed(seeds), std::runtime_error);
// try again with correct seed length
seeds = {1, 2, 3};
f.set_seed(seeds);
// Evaluate Forward Jacobian
Vec result_f_mode = f.evaluate();
Mat jacob_f = f.forward_jacobian();
// Evaluate Backward Jacobian
// f.zero_grad();
// u.backward();
Mat jacob_b = f.backward_jacobian();
// Validate
Mat correct_answer = {{0.62160998582839966, 44057.73046875, 79295.2734375}};
check_jacobians_equal(jacob_f, jacob_b);
check_jacobians_equal(jacob_f, correct_answer);
} | true |
d441dde7b230d284c40ee4e2b920fb382380c834 | C++ | WangYang-wy/LeetCode | /C++/455. Assign Cookies.cpp | UTF-8 | 669 | 2.59375 | 3 | [
"MIT"
] | permissive | //
// Created by 王阳 on 2018/5/13.
//
#include "header.h"
class Solution {
public:
int findContentChildren(vector<int> &g, vector<int> &s) {
// 先排序。
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int g_index = 0;
int s_index = 0;
int g_length = int(g.size());
int s_length = int(s.size());
while (g_index < g_length && s_index < s_length) {
if (g[g_index] <= s[s_index]) {
g_index++;
}
s_index++;
}
return g_index;
}
};
int main() {
Solution *solution = new Solution();
delete solution;
return 0;
} | true |
ac7289d5fc97334bb72c74831e1b6df65332ba4d | C++ | abeflood/ColorBasedBallSorter | /CCamera.cpp | UTF-8 | 2,468 | 2.828125 | 3 | [] | no_license | //#include "stdafx.h"
#include "CCamera.h"
#include <vector>
#define PASS_AREA 10000
//intialize camera
CCamera::CCamera()
{
cam.open(0);
}
//check if there is blue ball waiting to be sorted
bool CCamera::blue_check()
{
bool test = false;
cam >> intial;
//convert image to HSV then convert to binary image based on blue
cv::cvtColor(intial, hsv, CV_BGR2HSV);
cv::inRange(hsv, cv::Scalar(106, 30, 70), cv::Scalar(109, 255, 255), bluesel);
//clean up binary image
cv::erode(bluesel, erode, cv::Mat());
cv::dilate(erode, dilate, cv::Mat());
bounded = intial;
//find shapes in binary image
findContours(dilate, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (unsigned int i = 0; i < contours.size(); i++)
{
cv::Rect r = boundingRect(contours.at(i));
drawContours(bounded, contours, i, cv::Scalar(255, 255, 255), -1, 8, hierarchy);
//if the shape is larger then threshold..return true
if (r.area() > PASS_AREA)
{
cv::rectangle(bounded, r, cv::Scalar(255, 255, 255));
test = true;
cv::putText(bounded, "PASSED", cv::Point(50, 50), 1, 2, cv::Scalar(255, 255, 255));
}
}
if (!test)
{
cv::putText(bounded, "REJECTED", cv::Point(50, 50), 1, 2, cv::Scalar(255, 255, 255));
}
//cv::imshow("bounded", bounded);
return test;
}
//check if there is a ball waiting to be sorted
bool CCamera::ball_check()
{
bool test = false;
cam >> intial;
//convert to greyscale then convert to binary based on a threshold value
cv::cvtColor(intial, grey, CV_BGR2GRAY);
cv::threshold(grey, threshold, 200, 255, 0);
//clean up binary image
cv::erode(threshold, between, cv::Mat());
cv::dilate(between, between2, cv::Mat());
ballcheck = between2;
//find shapes in binary image
findContours(between2, contours2, hierarchy2, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
for (unsigned int i = 0; i < contours2.size(); i++)
{
cv::Rect r = boundingRect(contours2.at(i));
drawContours(ballcheck, contours2, i, cv::Scalar(255, 255, 255), -1, 8, hierarchy2);
//if shapes are is greater than threshold...then return true
if (r.area() > (PASS_AREA +PASS_AREA))
{
cv::rectangle(ballcheck, r, cv::Scalar(255, 255, 255));
test = true;
}
}
if (!test)
{
bounded = intial;
cv::putText(bounded, "NO BALL", cv::Point(50, 50), 1, 2, cv::Scalar(255, 255, 255));
}
return test;
}
//returns one image from camera
cv::Mat CCamera::return_frame()
{
cv::Mat ret;
cam >> ret;
return ret;
}
| true |
9d932140a98a7443941e6f95f1e254db7577a716 | C++ | realmelan/leetcode | /solutions/leetcode/canTransform.cpp | UTF-8 | 2,094 | 3.046875 | 3 | [] | no_license | // canTransform.cpp
// leetcode
//
// Created by Song Ding on 9/5/18.
// Copyright © 2018 Song Ding. All rights reserved.
//
#include "common.h"
using namespace std;
namespace canTransform {
class Solution {
public:
/**
* Relative order of L/R will not change. Also, 'R' can only move
* rightward, and 'L' can only move leftward.
*
* Two conditions must be met:
* 1, after stripping 'X', the leftover strings should be equal
* 2, 'X' on left side of 'L' should only decrease, and 'X' on left
* side of 'R' should only increase.
*/
bool canTransform(string start, string end) {
if (start.size() != end.size()) {
return false;
}
string sstrip;
string estrip;
int xcount = 0;
vector<int> xstart;
for (char c : start) {
if (c != 'X') {
xstart.push_back(xcount);
sstrip.push_back(c);
} else {
++xcount;
}
}
xstart.push_back(xcount);
xcount = 0;
vector<int> xend;
for (char c : end) {
if (c != 'X') {
xend.push_back(xcount);
estrip.push_back(c);
} else {
++xcount;
}
}
xend.push_back(xcount);
if (estrip != sstrip) {
return false;
}
for (int i = 0; i < estrip.size(); ++i) {
if (estrip[i] == 'L' && xstart[i] < xend[i]) {
return false;
} else if (estrip[i] == 'R' && xstart[i] > xend[i]) {
return false;
}
}
return true;
}
private:
};
}
/*/
int main() {
// TODO: prepare parameters here
string start = "XXRXXLXXXX";
string end = "XXXXRXXLXX";
// TODO: add return type and paramters.
clock_t start_clock = clock();
auto res = canTransform::Solution().canTransform(start, end);
cout << clock() - start_clock << endl;
cout << res << endl;
return 0;
}
//*/
| true |
7359ecd31cf713eecb1174d6f821c643dc7da379 | C++ | AloysiusParedes/CS-341-Project-2 | /Review.h | UTF-8 | 520 | 2.9375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
using namespace std;
class Review {
private:
//private members
int MovieID, UserID, Rating, numRating;
string ReviewDate;
public:
//constructor prototype
Review(int mid, int uid, int rating);
//accessor prototypes
int getMovieID();
int getUserID();
int getRating();
int getNumRating();
string getReviewDate();
//mutator prototypes
void setNumRating(int num);
//function
void incrementNumReviews();
};//end Review class
| true |
69a07d27c72b4eff1dcf169bc7fb1f73fe1c6e7c | C++ | bobby-mohanty/CodeForces | /800/1220A.cpp | UTF-8 | 304 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
char a[n];
cin>>a;
int b[2] = {0};
for(int i=0; i<n; i++)
{
if(a[i] == 'z')
b[0]++;
if(a[i] == 'n')
b[1]++;
}
while(b[1]>0)
{
cout<<1<<" ";
b[1]--;
}
while(b[0]>0)
{
cout<<0<<" ";
b[0]--;
}
return 0;
} | true |
5321c5e3225a201f002b1f20c7f179299f232236 | C++ | dagong996/Coding | /leetcode/179largest-number.cc | UTF-8 | 1,683 | 3.140625 | 3 | [] | no_license | #include <limits.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
static bool compare(int a, int b) {
if (a == b) return false;
string nums1 = to_string(a) + to_string(b);
string nums2 = to_string(b) + to_string(a);
int i = 0;
// while (i < nums1.size()) {
// if (nums1[i] != nums2[i]) {
// return nums1[i] > nums2[i];
// break;
// }
// i++;
// }
// return false;
return nums1 > nums2; // 直接对两个字符串进行比较
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), compare);//为compare(a,b)为true则a在b前面
string rtn;
for (int i = 0; i < nums.size(); i++) {
rtn += to_string(nums[i]);
}
if (rtn[0] == '0') return to_string(0);
return rtn;
}
private:
};
void cout_vector(vector<int>& nums) {
for (auto i : nums) {
cout << i << ' ';
}
cout << endl;
}
void debug() {
Solution sol;
// cout << sol.compare(7, 32) << endl;
//一维数组的输入
// vector<int> nums1 = {1, 2, 3, 0, 0, 0};
vector<int> nums2;
int i;
while (cin >> i) {
nums2.push_back(i);
}
cout << sol.largestNumber(nums2) << endl;
cout_vector(nums2);
//二维数组的输入
// while (cin >> m >> n) {
// vector<vector<char>> grid(m, vector<char>(n));
// for (int i = 0; i < m; i++) {
// for (int j = 0; j < n; j++ ) {
// cin >> grid[i][j];
// }
// }
// int ans = sol.solution(grid);
// cout << ans << endl;
// }
return;
}
int main(int argc, char const *argv[]) {
/* code */
ios::sync_with_stdio(false);
debug();
system("pause");
return 0;
} | true |
b064797830d747d43b9ff481efea4c33adf285ad | C++ | Auburn-University-COMP-3000/assignment-1-kje0011 | /Assignment_1/q5.cpp | UTF-8 | 446 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
// constants and variables
int celsius = 100;
int fahrenheit;
int count;
// calculations
while (celsius != fahrenheit)
{
fahrenheit = 32 + 9.0/5.0 * celsius;
celsius--;
}
// output
cout << "Celsius = " << celsius << endl;
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
} | true |
29e705657ab0925c1179587d889563df6af87512 | C++ | scipianus/Algorithm-contests | /CodeForces/CodeForces Round #264 Div 2/A/A.cpp | UTF-8 | 322 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int n, S, sol = -1;
int main()
{
int i, x, y;
std::ios_base::sync_with_stdio(false);
cin >> n >> S;
for(i = 1; i <= n; ++i)
{
cin >> x >> y;
if(y > 0 && x < S)
sol = max(sol, 100 - y);
if(y == 0 && x <= S)
sol = max(sol, 0);
}
cout << sol << "\n";
return 0;
}
| true |
5bc346571975284703fd2d18475f1161704f7d3c | C++ | SopoSh/Company-Employees | /Ass4.cpp | UTF-8 | 2,148 | 3.890625 | 4 | [] | no_license | // Ass4.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
/*--------------------------------------------------------------------------
Driver program to process a list of pointers to employee objects.
-------------------------------------------------------------------------*/
#include <iostream>
#include <list> //STL library for implemented list
#include <string>
using namespace std;
#include "Employee.h"
#include "waiter.h"
#include "Owner.h"
#include "Chef.h"
int main()
{
cout << "Enter this month's profit and tips for three waiters: " << endl;
int empProfit, empTips1, empTips2, empTips3;
cin >> empProfit;
cin >> empTips1;
cin >> empTips2;
cin >> empTips3;
Employee* ptr; //create pointer to the object of type employee, linked list
list<Employee*> empList;
ptr = new Owner("Heath Ledger", 7754368, 'O', 15000, 15, empProfit, empTips1);
ptr->calculateSalary(empProfit, empTips1);
empList.push_back(ptr); //pushback adds node to a list
ptr = new Chef("Cesar Romero", 79143891, 'C', 10000, "Italian", empProfit, empTips1);
ptr->calculateSalary(empProfit, empTips1);
empList.push_back(ptr);
ptr = new Chef("Mark Hamill", 82736451, 'C', 10000, "French", empProfit, empTips1);
ptr->calculateSalary(empProfit, empTips1);
empList.push_back(ptr);
ptr = new waiter("Jared Leto", 17362549, 'W', 3000, 3, empProfit, empTips1);
ptr->calculateSalary(empProfit, empTips1);
empList.push_back(ptr);
ptr = new waiter("Jack Nicholson", 73635284, 'W', 3000, 5, empProfit, empTips2);
ptr->calculateSalary(empProfit, empTips2);
empList.push_back(ptr);
ptr = new waiter("Joaquin Phoenix", 28364522, 'W', 3000, 7, empProfit, empTips3);
ptr->calculateSalary(empProfit, empTips3);
empList.push_back(ptr);
for (list<Employee*>::iterator it = empList.begin(); //iterator acts like a sticker and helps with iteration
it != empList.end(); it++)
{
ptr = *it;
cout << *ptr << endl; //here can be used **it
}
}
| true |
90865289e1168d8342b2f2df1914371ea363b8c9 | C++ | mehr-licht/codepile | /stack/infix-to-postfix.cpp | UTF-8 | 1,496 | 4.15625 | 4 | [] | no_license | /* Convert the given expression from infix to postfix */
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
using namespace std;
string infixToPostfix(string exp);
bool isOperand(char ch);
int precedence(char ch);
int main(void) {
string exp("((a+b-c)*d/e)+f*(g+h)");
cout << infixToPostfix(exp) << endl;
return 0;
}
string infixToPostfix(string exp) {
stack<char> Stack;
string postfixExp;
for(string::iterator iter = exp.begin(); iter != exp.end(); ++iter) {
if(isOperand(*iter))
postfixExp.push_back(*iter);
else if(*iter == '(')
Stack.push(*iter);
else if(*iter == ')') {
while(!Stack.empty() && Stack.top() != '(') {
postfixExp.push_back(Stack.top());
Stack.pop();
}
Stack.pop();
} else {
while(!Stack.empty() && precedence(Stack.top()) >= precedence(*iter)) {
postfixExp.push_back(Stack.top());
Stack.pop();
}
Stack.push(*iter);
}
}
while(!Stack.empty()) {
postfixExp.push_back(Stack.top());
Stack.pop();
}
return postfixExp;
}
bool isOperand(char ch) {
return isalpha(ch);
}
int precedence(char ch) {
switch(ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
| true |
e122e637fc1c257f44471558cade662bcc49b10e | C++ | manet-sih/manet_gzrp | /RoutingTable.cc | UTF-8 | 8,138 | 2.765625 | 3 | [] | no_license | #include "RoutingTable.h"
RoutingTable::RoutingTable(){}
void RoutingTable::addEvent(ns3::Ipv4Address addr,ns3::EventId id){
auto itr = eventTable.find(addr);
if(itr==eventTable.end()){
eventTable[addr] = id;
}else{
itr->second = id;
}
}
void RoutingTable::addRouteEntry(RoutingTableEntry& entry){
rTable[entry.getDsptIp()] = entry;
}
bool RoutingTable::search(ns3::Ipv4Address addr,RoutingTableEntry& entry){
if(rTable.empty()) return false;
auto itr = rTable.find(addr);
if(itr==rTable.end()) return false;
entry = itr->second;
return true;
}
ns3::Time RoutingTable::getHoldTime() const{
return holdTime;
}
void RoutingTable::setHoldTime(ns3::Time time){
holdTime = time;
}
uint32_t RoutingTable::size() const{
return rTable.size();
}
bool RoutingTable::updateRoute(RoutingTableEntry& route){
auto itr = rTable.find(route.getDsptIp());
if(itr==rTable.end()){
return false;
}
route = itr->second;
return true;
}
void RoutingTable::deleteRouteEntries(ns3::Ipv4InterfaceAddress interface){
for(auto itr = rTable.begin(); itr!=rTable.end();itr++){
if(itr->second.getLink() == interface){
auto tmpIterator = itr;
itr++;
rTable.erase(tmpIterator);
}else{
itr++;
}
}
}
bool RoutingTable::deleteRouteEntry(ns3::Ipv4Address ip){
auto itr = rTable.find(ip);
if(itr==rTable.end()) return false;
rTable.erase(itr);
return true;
}
bool RoutingTable::deleteEvent(ns3::Ipv4Address addr){
auto itr = eventTable.find(addr);
if(eventTable.empty()) return false;
else if(itr == eventTable.end()) return false;
else if(itr->second.IsRunning()) return false;
else if(itr->second.IsExpired()) {
itr->second.Cancel();
eventTable.erase(itr);
return true;
}
else{
eventTable.erase(itr);
return true;
}
}
bool RoutingTable::forceDeleteEvent(ns3::Ipv4Address addr){
auto itr = eventTable.find(addr);
if(itr == eventTable.end()) return false;
ns3::Simulator::Cancel(itr->second);
eventTable.erase(itr);
return true;
}
void RoutingTable::deleteRoutesWithInterface(ns3::Ipv4InterfaceAddress addr){
for(auto itr = rTable.begin();itr!=rTable.end();){
if(itr->second.getLink() == addr) {
auto tmp = itr;
itr++;
rTable.erase(tmp);
}else{
itr++;
}
}
}
void RoutingTable::getAllRoutes(std::map<ns3::Ipv4Address,RoutingTableEntry>& table){
for(auto itr = rTable.begin();itr!=rTable.end();itr++){
if(itr->first != ns3::Ipv4Address("127.0.0.1") && itr->second.getEntryState()!=EntryState::INVALID){
table[itr->first] = itr->second;
}
}
}
void RoutingTable::deleteAllInvalidRoutes(){
for(auto itr = rTable.begin();itr!=rTable.end();){
if(itr->second.getEntryState() == EntryState::INVALID) {
auto tmp = itr;
itr++;
rTable.erase(tmp);
}else if(itr->second.getLifeTime()>holdTime){
auto tmp = itr;
itr++;
rTable.erase(tmp);
}
else itr++;
}
}
bool RoutingTable::getKnownZones(std::set<ns3::Ipv4Address>& knownZones,uint32_t zone)
{
auto itr = knownZonesTable.find(zone);
if(itr == knownZonesTable.end())
return false;
else{
knownZones = itr->second;
return true;
}
}
void RoutingTable::addZoneIp(ns3::Ipv4Address ip,uint32_t zone){
auto findItr = knownZonesTable.find(zone);
if(findItr == knownZonesTable.end()){
knownZonesTable[zone] = std::set<ns3::Ipv4Address>();
}
knownZonesTable[zone].insert(ip);
}
bool RoutingTable::deleteZoneIp(ns3::Ipv4Address ip,uint32_t zone){
auto findItr = knownZonesTable.find(zone);
if(findItr == knownZonesTable.end()){
return false;
}
std::set<ns3::Ipv4Address>& ipSet = findItr->second;
auto findIp = ipSet.find(ip);
if(findIp == ipSet.end()) return false;
ipSet.erase(findIp);
if(ipSet.size() == 0) knownZonesTable.erase(findItr);
return true;
}
bool RoutingTable::deleteZoneIp(ns3::Ipv4Address ip,std::map<uint32_t,std::set<ns3::Ipv4Address>>::iterator findItr){
std::set<ns3::Ipv4Address>& ipSet = findItr->second;
auto findIp = ipSet.find(ip);
if(findIp == ipSet.end()) return false;
ipSet.erase(findIp);
if(ipSet.size() == 0) knownZonesTable.erase(findItr);
std::set<uint32_t> zoneSet;
getZonesForIp(zoneSet,ip);
if(zoneSet.size()==0){
auto findItr = zoneLifeMap.find(ip);
if(findItr != zoneLifeMap.end()){
zoneLifeMap.erase(findItr);
}
}
return true;
}
bool RoutingTable::deleteIpFromZoneMap(ns3::Ipv4Address addr){
bool result = false;
for(auto itr = knownZonesTable.begin();itr!=knownZonesTable.end();itr++){
result = result||(deleteZoneIp(addr,itr));
}
auto findItr = zoneLifeMap.find(addr);
if(findItr != zoneLifeMap.end()){
zoneLifeMap.erase(findItr);
}
return result;
}
bool RoutingTable::anyRunningEvent(ns3::Ipv4Address addr){
auto itr = eventTable.find(addr);
if(eventTable.empty()) return false;
if(itr== eventTable.end()) return false;
if(itr->second.IsRunning()) return true;
return false;
}
void RoutingTable::purge(std::map<ns3::Ipv4Address,RoutingTableEntry>& removedAddresses){
if(rTable.empty()) return;
for(auto i = rTable.begin();i!=rTable.end();i++){
auto iTmp = i;
if((i->second.getLifeTime()>holdTime && (i->second.getMetric().getMagnitude()>0))||i->second.getEntryState() == EntryState::INVALID){
for(auto j = rTable.begin();j!=rTable.end();j++){
if((j->second.getNextHop() == i->second.getDsptIp())&&(i->second.getMetric().getMagnitude() != j->second.getMetric().getMagnitude())){
auto jTmp = j;
removedAddresses.insert(std::make_pair(j->first,j->second));
j++;
rTable.erase(jTmp);
}else{
j++;
}
}
removedAddresses.insert(std::make_pair(i->first,i->second));
i++;
rTable.erase(iTmp);
}else{
i++;
}
}
return;
}
void RoutingTable::getListOfAddressWithNextHop(ns3::Ipv4Address addr,std::map<ns3::Ipv4Address,RoutingTableEntry> map){
map.clear();
for(auto i= rTable.begin();i!=rTable.end();i++){
if(i->second.getNextHop() == addr)
map.insert(std::make_pair(i->first,i->second));
}
}
void RoutingTable::print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const{
*stream->GetStream()<<"\nRouting Table\n"<<"Destination\tGateway\tInterface\t\tMetric\t\tSeqNum\t\tLifeTime\t\tSettlingTime\n";
for(auto i = rTable.begin();i!=rTable.end();i++){
i->second.print(stream);
}
*stream->GetStream()<<"\n";
}
bool RoutingTable::getZonesForIp(std::set<uint32_t> zones,ns3::Ipv4Address addr){
zones.clear();
bool inserted = false;
for(auto itr = knownZonesTable.begin();itr!=knownZonesTable.end();itr++){
std::set<ns3::Ipv4Address> set = itr->second;
auto findItr = set.find(addr);
if(findItr==set.end()) continue;
zones.insert(itr->first);
inserted = true;
}
return inserted;
}
bool RoutingTable::getAllIpforZone(uint32_t zone,std::set<ns3::Ipv4Address> set){
auto itr= knownZonesTable.find(zone);
if(itr==knownZonesTable.end()) return false;
set = itr->second;
return true;
}
bool RoutingTable::getZoneList(std::set<uint32_t> zones){
bool entryAdded = false;
for(auto itr = knownZonesTable.begin();itr!=knownZonesTable.end();itr++){
if(itr->second.size() != 0){
zones.insert(itr->first);
entryAdded = true;
}
}
return entryAdded;
}
bool RoutingTable::addIpLife(ns3::Ipv4Address addr,ns3::Time time){
auto findItr = zoneLifeMap.find(addr);
if(findItr != zoneLifeMap.end()){
return false;
}
zoneLifeMap[addr] = time;
return true;
}
bool RoutingTable::searchIpLife(ns3::Ipv4Address addr,ns3::Time& time){
auto findItr = zoneLifeMap.find(addr);
if(findItr == zoneLifeMap.end()) return false;
time = findItr->second;
return true;
}
bool RoutingTable::deleteIpLife(ns3::Ipv4Address addr){
auto findItr = zoneLifeMap.find(addr);
if(findItr == zoneLifeMap.end()) return false;
zoneLifeMap.erase(findItr);
return true;
}
bool RoutingTable::updateIpLife(ns3::Ipv4Address addr, ns3::Time time){
auto findItr = zoneLifeMap.find(addr);
if(findItr == zoneLifeMap.end()) return false;
findItr->second = time;
return true;
}
bool RoutingTable::deleteExpiredZoneIP(){
bool deleted = false;
for(auto itr = zoneLifeMap.begin();itr!= zoneLifeMap.end();){
if(itr->second<holdTime) {
auto temp = itr;
deleteIpFromZoneMap(itr->first);
deleted = true;
itr++;
zoneLifeMap.erase(temp);
}
}
return deleted;
}
| true |
a6a301b20a2093a28bbb58958cc5a00494ad9820 | C++ | imclab/EveMiner | /EVETest/EVETest.cpp | UTF-8 | 17,183 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
#include "IO.h"
#include "OpenCV.h"
#include "Timer.h"
#include "Util.h"
BOOL CALLBACK FindEveWindowProc(HWND hwnd, LPARAM lParam);
bool selectRightClickMenu(string firstAction);
bool selectRightClickMenu(string firstAction, string secondAction);
bool undock();
void depositOre();
bool approachAndFireMiningLasers();
bool selectAsteroid();
bool jumpToSystem(string systemName);
void openOverviewMine();
void openOverviewGates();
void openOverviewStations();
bool openOreHold();
bool openInv();
bool isAsteroidLocked();
bool isInWarp();
bool isDocked();
bool isInvOpen();
bool isInvFull();
bool isStopped();
bool isInSystem(string systemName);
bool waitToStop();
bool waitForSystem(string systemName);
bool waitForMinerDone();
bool waitForWarp();
bool waitUntilDocked();
void getNumber();
void setOverviewLocation();
void moveMouseAway();
void clickOnShip();
Timer t(1); // The run timer.
Point overviewLoc; // Location of the first entry in the overview, set when undocked.
bool overviewLocSet = false;// Flag specifying whether the overview location has been set or not.
HWND eveWindow; // Our global handle to the eve window
int width; // Client window resolution
int height;
#define NUM_MINING_SITES 3 // Set to 3 because the 4th one requires double warp, whoops.
string miningSites[] = {
"rmenu_mining1.bmp",
"rmenu_mining2.bmp",
"rmenu_mining3.bmp",
"rmenu_mining4.bmp"
};
int curSiteIdx = 0;
#define VELD_PRICE 17.15
#define VELD_CAPACITY 231000
#define NUM_LASERS 2
bool runOnce = true;// Flag for runOnce events that have to happen when undocked.
int main() {
// TODO: Implement reconnecting and connection drop. The image name is "connlist.bmp"
EnumWindows(FindEveWindowProc, NULL);
if(eveWindow == NULL)
fatalExit("Could not find EVE window, closing. Make sure EVE is open before running!");
SetForegroundWindow(eveWindow);
Sleep(500);
// Set the client window's width and height.
RECT rect;
GetClientRect(eveWindow, &rect);
width = rect.right;
height = rect.bottom;
// Figure out where we are, and hopefully where we need to go.
if(isDocked()) {
depositOre();
}
else if(isInSystem("rens")) {
cout << "Looks like you're in rens, go home ship, you're drunk." << endl;
goto in_rens;
}
else if(isInSystem("frarn")) {
if(isInvFull()) { // Check if we have a full inventory in frarn, if so, go home.
cout << "You've got your hands full in frarn, going home." << endl;
jumpToSystem("rens");
goto in_rens;
}
else { // I'm just going to assume your ass is in the minefield.
openOverviewMine(); // Open the mining tab and check for rocks.
if(isImageOnScreen("nav_veld.bmp", 0.95)) { //|| isImageOnScreen("nav_scord.bmp", 0.95)) {
cout << "Found rocks, go mine!" << endl;
goto at_minefield;
}
else {
cout << "So you're somewhere in frarn, go get somewhere we can recognize." << endl;
Sleep(10000);
return 0;
}
}
}
else {
fatalExit("We have no idea where you are, are you okay? Exiting.");
}
while(1) {
t.start();
undock();
if(!isDocked() && runOnce) { // Reset the overview by scrolling up on it so the closest objects appear on the screen.
setOverviewLocation(); // Find and set overviewLoc to the location of the first entry in the overview.
// TODO: This is going to cause a problem, need to have a better way to initialize.
// Or to stop using the GOTO's, because they will fail for miners.
runOnce = false;
}
cout << "Heading to Frarn to mine" << endl;
jumpToSystem("frarn");
selectRightClickMenu(miningSites[curSiteIdx], "rmenu_warpto.bmp");// Warp to mining waypoint.
waitForWarp(); // Warp through.
at_minefield:
do {
if(!selectAsteroid()) { // Target and select an asteroid.
curSiteIdx++; // Update which mining site we go to.
curSiteIdx %= NUM_MINING_SITES;
cout << "Failed to select an asteroid for some reason, next mine site will be: " << miningSites[curSiteIdx] << endl;
break; // And break.
}
approachAndFireMiningLasers(); // Start firing teh lazerzzz.
} while(!waitForMinerDone()); // Wait till we fill up the hangar or for the rock to disappear.
cout << "Heading back Home" << endl;
jumpToSystem("rens");
in_rens:
selectRightClickMenu("rmenu_home.bmp", "rmenu_dock.bmp");
waitForWarp(); // Warp through.
waitUntilDocked(); // Dock.
depositOre(); // Deposit.
unsigned long runTime = t.elapsed(); // Grab the elapsed time.
cout << "Time for current run: " << formatTime(runTime) << endl;
cout << "Approx money for current run: " << VELD_PRICE * VELD_CAPACITY << " ISK" << endl;
double mIskPerHour = (double)VELD_PRICE * VELD_CAPACITY / runTime * 1000*60*60 / 1000000;
cout << "Hourly income based on current run: " << mIskPerHour << "Mil Isk" << endl;
// R-r-r-r-r-r-repeat!
}
return 0;
}
bool isStopped() {
return isImageOnScreen("stopped.bmp", 0.98);
}
bool isInWarp() {
return isImageOnScreen("warpdrive.bmp", 0.91);
}
bool isInvOpen() {
return isImageOnScreen("inv_cargoopen.bmp", 0.95);
}
bool isDocked() {
return isImageOnScreen("undock.bmp", 0.85);
}
bool isInvFull() {
if(!openInv()) {
cout << "Failed to open inventory!" << endl;
return false;
}
return isImageOnScreen("cargofull.bmp", 0.999);
}
// Returns whether or not the ship is currently located in the particular system.
bool isInSystem(string systemName) {
cout << "Checking if you are in: " << systemName << endl;
Sleep(1000); // VM is really slow, maybe this will help?
openOverviewStations();
string imgStr = "nav_" + systemName + ".bmp"; // Build the search string for the overview.
return isImageOnScreen(imgStr, 0.99); // If the system name is shown in the stations overview, we are in this system.
}
bool isAsteroidLocked() {
return isImageOnScreen("veld_lock.bmp", 0.98);
}
bool waitForWarp() {
Timer t(15000); // We'll set a timeout on how long it takes for a ship to get into warp to prevent blocking.
while(!isInWarp()) {
if(t.isDone()) {
cout << "Couldn't detect warp." << endl;
return false;
}
}
cout << "Warp detected!" << endl;
t.setInterval(80000); // Another timeout for how long you're in warp. I think time dilation would screw this up, oh well, it's not perfect.
t.start();
while(isInWarp()) {
if(t.isDone()) {
cout << "Warping took to long. Exiting." << endl;
return false;
}
Sleep(500);
}
cout << "Warp completed." << endl;
return true;
}
bool waitToStop() {
Timer t(40000); // Seems like a reasonable time to stop.
while(!isStopped()) {
if(t.isDone()) {
cout << "Something went wrong when trying to stop!" << endl;
return false;
}
}
cout << "Detected that you've stopped." << endl;
return true;
}
bool selectAsteroid() {
Point p;
openOverviewMine(); // Open the mining navigation tab.
moveMouseAway(); // Move away the mouse to make sure we don't mess with image recognition.
if(!findAsteroidOnScreen(p)) {
cout << "Couldn't find an asteroid to select!" << endl;
return false;
}
double asteroidDistance = getDistance(p.x, p.y);
cout << "Our asteroid distance is: " << asteroidDistance << " m" << endl;
// Find how far away the asteroid is.
if(asteroidDistance > 14 * 1000) { // If it's over 14km then we say screw it.
cout << "The selected asteroid is further than 14km away." << endl;
return false;
}
moveMouse(p.x, p.y, 1); // Click on it.
pressKey(VK_LCONTROL); // Target.
Sleep(5000); // Wait for target lock.
// Check for lock symbol here!!!
return true;
}
void fireMiningLasers() {
for(int x = 0; x < NUM_LASERS; x++) {
pressKey(VK_F1 + x); // Vkeys for the f's are 0x70..0x7x starting with F1
}
}
bool approachAndFireMiningLasers() {
pressKey((unsigned short)0x51); // Press Q to approach the thing
Timer t(180000); // Setup a timeout timer to avoid getting hung up
do {
if(t.isDone()) {
cout << "Timeout during approach and firing of lasers!" << endl;
return false;
}
Sleep(4000); // Give it some time to approach.
fireMiningLasers();
cout << "Fired lasers." << endl;
Sleep(500); // Don't poll so agressively, plus give the messages time to display.
} while(isImageOnScreen("rocktoofar.bmp", 0.9));
cout << "Approached and successfully firing the lasers." << endl;
return true;
}
void resetMiningLasers() {
fireMiningLasers(); // Since we're not actually mining anything, and at least one laser is erroneously on,
// turn them all off, without a target, this will cause the rest of them to blink.
moveMouse(width - 20, height - 20, 2); // Right click on the bottom corner of the screen to open the right click menu.
Sleep(200);
clickOnShip(); // Then click away to reset the mining lasers to off position.
}
bool waitForMinerDone() {
Timer t(600000); // 10 minutes to fill up hull, will almost certainly have to change this later.
cout << "Waiting to get miner full message." << endl;
while(!isInvFull()) { // Repeat while the inventory is not full.
if(t.isDone()) {
cout << "Something went wrong, timeout for miner full exceeded." << endl;
return false;
}
// Check if we still hold an active lock on an asteroid. If we don't, that means that the rock is gone.
if(!isAsteroidLocked()) {
cout << "Rock disappeared." << endl;
resetMiningLasers(); // This is a bug, once a rock disappears, the mining lasers are supposed to stop. In this case, only one does.
return false;
}
}
cout << "Miner is full." << endl;
return true;
}
// Right click menu integration
#define RMENU_WIDTH 210 // Width of the menu when right clicking in space
#define RMENU_HEIGHT 15 // Height of each item
#define RMENU_NUMITEMS 11 // Number of items in right click menu
bool selectRightClickMenu(string firstAction) {
clickOnShip(); // Click in the center to ensure no menus are open
moveMouse(width - RMENU_WIDTH / 5, height - 30, 2); // Right click on the bottom right corner of the screen to bring up the menu.
moveMouse(width - RMENU_WIDTH / 5, height - 5, 0); // Move to the bottom of the menu to not obcure any options.
if(!clickImageOnScreen(firstAction, 0.95)) {
cout << "Failed to find/select option in first menu" << endl;
fatalExit("See previous message");
return false;
}
return true;
}
bool selectRightClickMenu(string firstAction, string secondAction) {
selectRightClickMenu(firstAction); // Let's open the first menu
POINT ptMouse; // Get the mouse position
GetCursorPos(&ptMouse);
ScreenToClient(eveWindow, &ptMouse);
int x = ptMouse.x - RMENU_WIDTH / 2 - 20;
int y = ptMouse.y; // Move the mouse to the left, just past the menu.
moveMouse(x, y, 0);
y = height - 10;
moveMouse(x, y, 0); // Move the mouse again to the bottom of second menu.
if(!clickImageOnScreen(secondAction, 0.95)) {
cout << "Failed to find/select option in second menu" << endl;
fatalExit("See previous message");
return false;
}
return true;
}
bool openInv() {
if(!isInvOpen()) {
keyDown(VK_MENU); // Send alt.
pressKey('C'); // Press C. The shortcut "ALT-C" should open up the inventory.
keyUp(VK_MENU); // Release alt.
}
Sleep(300); // Give it a little bit of time to actually open the inventory.
return isInvOpen();
}
bool openOreHold() {
if(!openInv()) // Need to open the inventory first.
return false;
// Click the ship select icon to reset
clickImageOnScreen("inv_shipselect.bmp", 0.95);
// Then click the orehold.
bool result = clickImageOnScreen("inv_orehold.bmp", 0.95);
if(!result) {
cout << "Failed to open orehold!" << endl;
}
return result;
}
void _openOverview(string name) {
moveMouseAway(); // Move the mouse out of the way to not get in the way of image recognition.
clickImageOnScreen(name, 0.95);
Sleep(200); // Give it some time to open the tab.
}
void openOverviewGates() {
return _openOverview("overview_gates.bmp");
}
void openOverviewMine() {
return _openOverview("overview_mining.bmp");
}
void openOverviewStations() {
return _openOverview("overview_stations.bmp");
}
void _depositOreHelper(Point itemHangarPos, string oreName) {
double corr;
while(1) {
Point orePos;
findOnScreen(oreName, orePos, corr);
if(corr > 0.95) { // Looks like we've found the ore
cout << "Ore found, moving to item hangar" << endl;
dragMouse(orePos.x, orePos.y, itemHangarPos.x, itemHangarPos.y);
Sleep(300); // Wait for a minute for the UI to update.
}
else
break;
}
}
void depositOre() {
openOreHold(); // Open the ore hold
Point itemHangarPos;
double corr;
// Grab the position of the item hangar thing.
findOnScreen("inv_itemhangar.bmp", itemHangarPos, corr);
if(corr < 0.90) {
cout << "Item hangar image was not found!" << endl;
return;
}
_depositOreHelper(itemHangarPos, "inv_veld.bmp");
//_depositOreHelper(itemHangarPos, "inv_scord.bmp");
}
bool undock() {
Point loc;
cout << "Attempting Undock." << endl;
if(isDocked()) {
cout << "It looks like you're docked." << endl;
clickImageOnScreen("undock.bmp", 0.85);
cout << "Clicked undock." << endl;
Timer t(20000); // Give the operation a 20 second timeout.
while(isDocked()) {
Sleep(2000);
if(t.isDone()) {
cout << "Error on undock!" << endl;
return false;
}
}
Sleep(3000); // Let's give it three seconds to load it's stuff before continuing.
cout << "Looks like you're out! Have fun!" << endl;
return true;
}
else {
cout << "Couldn't find undock symbol, are you undocked already?" << endl;
return false;
}
}
bool waitUntilDocked() {
Timer t(60000); // We'll give it 60 seconds of timeout to wait, to make sure we don't block forever.
cout << "Waiting 60 seconds to dock..." << endl;
while(!isDocked()) {
if(t.isDone()) {
cout << "Timer ran out, something's wrong." << endl;
return false;
}
Sleep(2000); // Calm down speedy gonzales, we gotta chilllll.
}
Sleep(1000);
cout << "Docked!" << endl;
return true;
}
bool waitForSystem(string systemName) {
Timer t(60000); // Timeout to wait until you are in a system is 60s.
while(!isInSystem(systemName)) {
if(t.isDone()) {
cout << "Error waiting for current location: " << systemName << endl;
fatalExit("");
return false;
}
Sleep(500);
}
Sleep(3000);
cout << "Awesome, you are now in: " << systemName << endl;
return true;
}
bool jumpToSystem(string systemName) {
openOverviewGates();
string navImg = "nav_" + systemName + ".bmp";
bool result = false;
if(isImageOnScreen(navImg, 0.98)) // Check if the system we want to go to exists.
result = clickImageOnScreen(navImg, 0.98);
else { // Also check if it's highlighted.
navImg = "nav_" + systemName + "_s.bmp";
if(isImageOnScreen(navImg, 0.98))
result = clickImageOnScreen(navImg, 0.98);
}
if(result) { // Check if we've successfully found and clicked on the system we want to go to.
pressKey((unsigned short)'D'); // Send the jump command
waitForWarp(); // Need to do something about this, assuming we are far enough to warp to jumpgate
waitForSystem(systemName); // Wait until the call tells us we are in the system.
}
else {
cout << "Unsuccessful in clicking on proper system for warp." << endl;
}
return result;
}
// Use caching and lazy evaluation for things like this.
Point getOverviewLocation() {
if(overviewLocSet) {
return overviewLoc;
}
if(isDocked()) {
fatalExit("Error, tried to access overview location, but was reported as being docked!");
}
// TODO: Probably need more checks here..
setOverviewLocation();
return overviewLoc;
}
void setOverviewLocation() {
openOverviewMine(); // Open the mining portion of the overview.
clickOnShip(); // Click on the ship to deselect anything you hopefully have in the overview.
Point p;
double corr;
// Find the position of the first element in the overview.
findOnScreen("nav_overviewloc.bmp", p, corr);
if(corr < 0.99)
fatalExit("Failed to find overview location!");
Mat templ = safeImageRead("nav_overviewloc.bmp");
p.x += templ.cols / 2; // Next we update the location to the bottom right of the template
p.y += templ.rows / 2; // since findOnScreen() gives the location of the center of the template.
overviewLoc = p;
overviewLocSet = true; // Update the flag so it's just cached.
cout << "Found overview start at: " << p.x << ", " << p.y << endl;
}
void clickOnShip() {
moveMouse(width / 2, height / 2, 1);
}
void moveMouseAway() {
moveMouse(width - 20, height - 20, 0);
}
BOOL CALLBACK FindEveWindowProc(HWND hwnd, LPARAM lParam) {
char className[80];
char title[80];
GetClassNameA(hwnd, className, sizeof(className));
GetWindowTextA(hwnd, title, sizeof(title));
if(!strncmp(title, "EVE -", 5)) {
cout << "Window title: " << title << endl;
cout << "Class name: " << className << endl;
eveWindow = hwnd;
}
return TRUE;
} | true |
650bb3902b9def788682d93287a4be47d4c1a7d0 | C++ | JinRLuo/vjudge_Summertraining | /最小生成树/b.cpp | GB18030 | 1,800 | 3.1875 | 3 | [] | no_license | /*
ʡ̡ͨĿʹȫʡκׯ䶼ʵֹ·ͨһֱӵĹ·ֻҪܼͨ·ɴTɣֵõ·ͳƱг·ķãԼõ·ǷѾͨ״̬дȫʡͨҪͳɱ
Input
ɲÿĵ1иׯĿN ( 1< N < 100 ) N(N-1)/2 жӦׯ·ijɱ״̬ÿи4ֱׯıţ1ŵNׯ·ijɱԼ״̬1ʾѽ0ʾδ
NΪ0ʱ
Output
ÿռһУȫʡͨҪͳɱ
Sample Input
3
1 2 1 0
1 3 2 0
2 3 4 0
3
1 2 1 0
1 3 2 0
2 3 4 1
3
1 2 1 0
1 3 2 1
2 3 4 1
0
Sample Output
3
1
0
*/
#include <bits/stdc++.h>
using namespace std;
struct edge{
int a,b;
int cost;
}e[5000];
int f[105];
bool cmp(edge e1,edge e2){
return e1.cost<e2.cost;
}
void init(int n){
for(int i=1;i<=n;i++){
f[i]=i;
}
}
int find(int a){
if(f[a]!=a){
f[a]=find(f[a]);
return f[a];
}
return a;
}
void merge(int a,int b){
int x1,x2;
x1=find(a);
x2=find(b);
if(x1!=x2){
f[x1]=x2;
}
}
int main(){
ios::sync_with_stdio(false);
int n,d,x1,x2;
while(cin>>n){
int res=0;
if(n==0)
break;
init(n);
for(int i=0;i<n*(n-1)/2;i++){
cin >> e[i].a >> e[i].b >> e[i].cost >> d;
if(d==1){
merge(e[i].a,e[i].b);
}
}
sort(e,e+n*(n-1)/2,cmp);
for(int i=0;i<n*(n-1)/2;i++){
x1=find(e[i].a);
x2=find(e[i].b);
if(x1!=x2){
merge(x1,x2);
res+=e[i].cost;
}
}
cout << res << endl;
}
}
| true |
80da5457a9ae89a525e871e7ec6c9caca2fab837 | C++ | ahmetserefoglu/Stirngstructorneklercpp | /struct4.cpp | UTF-8 | 695 | 2.734375 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct ogrenci
{
char ad[20],soyad[20];
int vize,final;
};
int main()
{
int ort;
ogrenci x[]={"muhammet","mastar",60,80,"ali","akil",90,80,"arif","serat",40,50};
for(int i=0;i<3;i++)
{
ort=x[i].vize*0.3+x[i].final*0.7;
if(ort>60)
{
cout<<"\nogrencinin adi:"<<x[i].ad<<endl;
cout<<"ogrencinin soyadi:"<<x[i].soyad<<endl;
cout<<"sinifi gecmistir:"<<endl;
}
else
{
cout<<"\nogrencinin adi:"<<x[i].ad<<endl;
cout<<"ogrencinin soyadi:"<<x[i].soyad<<endl;
cout<<"sinifta kalmistir:"<<endl;
}
}
}
| true |
efff77c970e2c6a5cd14840cdf6977cf86147aad | C++ | xiaoqiang0/leetcode | /minimum-path-sum.cc | UTF-8 | 1,610 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int m = grid.size();
int n;
if (m == 0) return 0;
n = grid[0].size();
if (n == 0) return 0;
vector<vector<int> > d(m, vector<int>(n));
d[0][0] = grid[0][0];
for (int i = 0; i < m; i ++){
for (int j = 0; j < n; j ++){
int top = -1, left = -1;
if (i - 1 >= 0) top = d[i-1][j];
if (j - 1 >= 0) left = d[i][j-1];
if (top == -1 && left == -1)
d[i][j] = grid[i][j];
else if (top == -1)
d[i][j] = grid[i][j] + left;
else if (left == -1)
d[i][j] = grid[i][j] + top;
else
d[i][j] =grid[i][j] + (top > left ? left: top);
// cout <<d[i][j] << " ";
}
// cout <<endl;
}
return d[m-1][n-1];
}
};
int main()
{
//int a[] = {1,1,2,3};
//int a[] = {9,9,9,9};
//int a[] = {9,9,9,8};
int a[] = {};
vector<vector<int> > g(4, vector<int>(3));
g[0][0] = 1;g[0][1] = 1;g[0][2] = 1;
g[1][0] = 3;g[1][1] = 2;g[1][2] = 1;
g[2][0] = 4;g[2][1] = 6;g[2][2] = 1;
g[3][0] = 5;g[3][1] = 1;g[3][2] = 1;
Solution S;
cout <<S.minPathSum(g) <<endl;
return 0;
}
| true |
9d48e002edd784f688c0c29eba5aa598d7232d6f | C++ | rolandhartanto/Competitive-Programming | /TLX_Toki_Learning/kelas_pembelajaran_pemrograman/pemrograman_dasar/ch14_Rekursi/kasur_rusak.cpp | UTF-8 | 531 | 3.234375 | 3 | [] | no_license | //Kasur Rusak
//Author : Roland Hartanto
#include<bits/stdc++.h>
using namespace std;
bool cekPalindrom(string X){
if(X.length()==1){
return true;
}else if(X.length()==2){
if(X[0] == X[1]){
return true;
}else{
return false;
}
}
else if(X.length()>2){
if(X[0] == X[X.length()-1]){
X.erase(0,1);
X.erase(X.length()-1,1);
return (cekPalindrom(X));
}else{
return false;
}
}
}
int main(){
string A;
cin>>A;
if(cekPalindrom(A)==true){
cout<<"YA"<<endl;
}else{
cout<<"BUKAN"<<endl;
}
return 0;
}
| true |
865b5638710c78d55088c2f9526e56ab0cedbc18 | C++ | hakkelt/paszuj_beadando | /tamas.cpp | UTF-8 | 16,254 | 2.59375 | 3 | [] | no_license | #include "paszuj.h"
#include <set>
#include <cmath>
using namespace std;
/*
Azért használok iterátorokat és nem magukat a konténereket, mert így módosítani tudom őket (ok, erre még
egy pointer is jó lenne), és ki tudom törölni abból a listából, amiben vannak (na, ehhez kell az iterátor!).
Eltárolom, hogy melyik hajóra nézve kb mennyivel jutna közelebb a céljához
(alsó becslést végzek Dijkstra algoritmussal).
*/
struct MennyireEriMegSzallitani {
list<Kontener>::iterator kontener;
vector<InduloHajo>::iterator melyikHajon;
int mennyivelLeszKozelebb;
};
/*
Két MennyireEriMegSzallitani típusú változót hasonlít össze, az lesz a nagyobb, amelyiknek nagyobb a
mennyivelLeszKozelebb típusú mezője, vagyis ha a konténer átkerülne egy másik helyre, akkor
onnan kb hány nappal kevesebb idő alatt ér át a rendeltetési helyére (ezt Dijkstra algoritmussal fogom
alulról becsülni). Ez lesz az elem prioritása. Ha egyenlő a két elem prioritása, akkor a bónuszidő dönt.
A prioritás ebben az esetben azt írja le, ezért az lesz a nagyobb prioritású, amelyiknek kisebb az
így kapott úthossza, ezért van fordítva a relációs jel.
Ezt a funktort a parancsol függvényben deklarált prioritásos sorhoz hoztam létre.
*/
bool CompareMennyireEriMegSzallitani (const MennyireEriMegSzallitani &v1, const MennyireEriMegSzallitani &v2) {
if (v1.mennyivelLeszKozelebb == v2.mennyivelLeszKozelebb)
return v1.kontener->bonuszIdo > v2.kontener->bonuszIdo;
else
return v1.mennyivelLeszKozelebb < v2.mennyivelLeszKozelebb;
}
/*
Ez a függvény prioritásos sorokat hasonlít össze prioritásos sorok legnagyobb eleme szerint.
(Pontosabban a legkisebb eleme szerint, de az előző összehasonlító függvény és ezt úgy írtam meg, hogy
megfordítsa a sorrendet, vagyis a kisebbet tüntesse föl nagyobbnak).
A feladatra nézve ez azt jelenti, hogy melyik az az a konténer, ami a legtöbbet halad, ha felkerül
az "álom hajóra", ami az összes közül neki a legjobb.
*/
bool ComparePriorityQueue (const vector<MennyireEriMegSzallitani> v1, const vector<MennyireEriMegSzallitani> v2) {
return CompareMennyireEriMegSzallitani(v1[0], v2[0]);
}
/*
Egy adott napra nézve minden egyes aznap induló hajót végignézi, és felállít egy prioritásos listát
a konténerek közt aszerint, hogy az induló hajóra felkerülne, akkor mennyivel jutna közelebb a céljához
(persze ez csak egy durva becslés lesz, mert nem a gráfot statikusnak veszem, vagyis nem veszem
figyelembe, hogy az egyes hajójáratok nem indulnak minden nap. A felállított prioritásos sor
első n elemét elszállítom, ahol n a vizsgált hajó kapacitása - a parancsok structba beleírom az
utasításokat, és kitörlöm annak a városnak a megfelelő gráf-csúcsból, ahonnan elszállítom, és a
hajó célhelyéhez meg hozzáadom, ha az nem a konténer célhelye. Így csak olyan konténereim lesznek a
gráfban amiket szállítani kell. Amikor elfogytak a szállítandó konténerek, akkor a függvény hamissal tér
vissza.
*/
void Paszuj::parancsol() {
cout << "\tNap: " << graf.nap << " \tKontenerek szama: " << kontenerekSzama << endl;
/*A belső prioritásos sorba (vectort használok praktikus okokból, de úgy rendezem, hogy prioritásos sor legyen)
az fog kerülni, hogy az adott konténert ha felrakom a tartózkodási helye szerini
városból induló hajókra, akkor az egyes hajók mennyivel viszik közelebb a konténert a végcéljához.
Ez a map csoportosítja a kapott priotásos sorokat aszerint, hogy melyik konténerre vonatkoznak.
Kulcsként iterátort használok, mert az (remélem) minden konténerre különböző*/
map< int, vector<MennyireEriMegSzallitani> > gyujto;
// Végigmegyek azokon a városokon, ahonnan az adott nap indul hajó...
for (unordered_map<string, vector<InduloHajo>>::iterator v = graf.induloHajok.begin(); v != graf.induloHajok.end(); v++) {
// ...végigmegyek a városban található konténereken... (Azért használok iterátoros ciklus és nem rage-based-et, mert szükségem lesz az iterátorra magára)
for (list<Kontener>::iterator k = graf.csucsok[v->first].kontenerek->begin();
k != graf.csucsok[v->first].kontenerek->end(); k++) {
// ... és végigmegyek az adott városból induló összes hajón minden egyes konténer esetében vizsgálva azt, hogy mennyivel jutna közelebb az adott konténer, ha felkerül az adott hajóra
for(vector<InduloHajo>::iterator h = v->second.begin(); h != v->second.end(); h++) {
// Ennyivel javulna a konténer aktuális tartózkodási helye a célhelyhez képest, ha felkerülne az adott hajóra
int kulonbseg = Dijkstra(v->first, k->celHely) - Dijkstra(h->hova, k->celHely);/// - h->menetido;
if (0 < kulonbseg) {
MennyireEriMegSzallitani uj;
uj.kontener = k;
uj.melyikHajon = h;
uj.mennyivelLeszKozelebb = kulonbseg;
gyujto[k->ID].push_back(uj);
}
}
}
}
/* Ez egy konténereket tároló lista itarátoraiból álló prioritásos sorok prioritásos sora. ...huh...
A belső prioritásos sorba (itt BelsoPriorityQueue-ként van rövidítve egy korábbi #define-nak
köszönhetően) az fog kerülni, hogy az adott konténert ha felrakom a tartózkodási helye szerini
városból induló hajókra, akkor az egyes hajók mennyivel viszik közelebb a konténert a végcéljához.
A külső prioritásos sor pedig aszerint rendezi sorba a konténereket, hogy melyik halad a legnagyobbat,
ha felkerül az "álom hajóra", vagyis arra a hajóra,ami leginkább rövidít az útján.*/
vector< vector<MennyireEriMegSzallitani> > kivansagok;
for (auto k : gyujto) {
make_heap(k.second.begin(), k.second.end(), CompareMennyireEriMegSzallitani);
kivansagok.push_back(k.second);
}
make_heap(kivansagok.begin(), kivansagok.end(), ComparePriorityQueue);
while (not kivansagok.empty()) {
// A prioritásos sorból a top() függvénnyel tudom lekérdezni a legkisebb elemet
// Bevezetek két rövidítést (actKontener és az actHajo), mert átláthatóbb, ha ezeken nem írom le ezerszer.
list<Kontener>::iterator actKontener = kivansagok[0][0].kontener; // Ez az a konténer lesz, aminek a legszebb a kívánsága: az összes közül ez ígér a legtöbbet, hogy mennyivel fog közelebb kerülni, ha feltesszük arra a hajóra, amire kéri
vector<InduloHajo>::iterator actHajo = kivansagok[0][0].melyikHajon; // Ez pedig a legszebb kívánságban szereplő hajó
// Ha teljesíthető a kívánság, mert a hajón van még hely...
if (0 < actHajo->kapacitas) {
Parancs uj;
uj.bonuszIdo = // Ha már lejárt a bónuszidő, akkor ne negatív legyen ez az érték, amit fájlba majd kiírok, hanem nulla (ez benne volt a feladatleírásban)
(actKontener->bonuszIdo - graf.nap < 0 ? 0 : actKontener->bonuszIdo - graf.nap);
uj.jaratKod = actHajo->jaratKod;
uj.mikorErkezik = graf.nap + actHajo->menetido;
uj.rakomanyNev = actKontener->rakomanyNev;
// Ha konténerek mind beleférnek az adott hajóba
if (actKontener->mennyiseg <= actHajo->kapacitas) {
uj.mennyiseg = actKontener->mennyiseg; // Felrakom az összes konténert
actHajo->kapacitas -= uj.mennyiseg; // Kiszámolom, hogy mennyi hely maradt a hajón
// Ha a konténerek még nem érkeztek meg a célhelyükre, akkor hozzáadom az épp vizen levő konténerek listájába (pontosabban prioritásos sorába)
if (actHajo->hova != actKontener->celHely) {
HajonKontener k;
k.hova = actHajo->hova;
k.kontener = *actKontener;
k.mikor = graf.nap + actHajo->menetido;
graf.hajonKontenerek.push(k);
}
// Ha nem akkor "véletlenül" elfelejtem hozzáadni a listához, nem érkezik meg, úgyhogy eltűnik a gráfból, de nem is baj, hiszen nincs több dolgunk vele
else {
// Ezek csak azért számlálom, hogy legyen mit kiírni a konzolra.
kontenerekSzama -= actKontener->mennyiseg;
if (0 < uj.bonuszIdo - actHajo->menetido) bonuszIdore += actKontener->mennyiseg;
}
graf.csucsok[actHajo->honnan].kontenerek->erase(actKontener); // törlöm a gráfból ezeket a konténereket az adott helyről, mert már nincsenek ott
pop_heap(kivansagok.begin(), kivansagok.end(), ComparePriorityQueue);
kivansagok.pop_back();
}
// Ha nem fér be az összes konténer, akkor felrakok annyi konténert a hajóra, amennyit csak tudok
else {
uj.mennyiseg = actHajo->kapacitas; // Felrakok a hajóra annyit, amennyit csak tudok
actHajo->kapacitas = 0; // Jelzem, hogy betelt a hajó
int temp = actKontener->mennyiseg; // Ketté fogom osztani a konténereket (egy rész meg a hajóval, többi marad), ezért elmentem, hogy mennyi volt
actKontener->mennyiseg = uj.mennyiseg; // Ez utazik
if (actHajo->hova != actKontener->celHely) { // Fel is teszem a hajóra, hacsak nem megy a hajó a konténerek célállomása felé, mert akkor nem tartom őket számon a továbbiakban, mert tudom, hogy sínen vannak
HajonKontener k;
k.hova = actHajo->hova;
k.kontener = *actKontener; // Itt másolat készül a konténerről (csökkentett mennyiseg mezővel), így a továbbiakban, ha megváltoztathatom az actKontener értékeit, a kikötőben maradó konténer fog változni
k.mikor = graf.nap + actHajo->menetido;
graf.hajonKontenerek.push(k);
}
else { // Ha odaérnek a helyhez, akkor
kontenerekSzama -= uj.mennyiseg;
if (0 < uj.bonuszIdo - actHajo->menetido) bonuszIdore += uj.mennyiseg;
}
actKontener->ID = MAX_ID++;
actKontener->mennyiseg = temp - uj.mennyiseg; // Ennyi marad a kikötőben
}
parancsok.push_back(uj);
}
// Ha nem teljesíthető a kívánsága, akkor törlöm a kívánságot, és újrarendezem a kívánságlistát úgy, hogy törlöm az adott elemet, és újra beszúrom (így nem kell az egész rendszert megbolygatni, hanem pár cserével megúszom)
else {
pop_heap(kivansagok[0].begin(), kivansagok[0].end(), CompareMennyireEriMegSzallitani);
kivansagok[0].pop_back();
if (kivansagok[0].size() != 0) {
pop_heap(kivansagok.begin(), kivansagok.end(), ComparePriorityQueue);
push_heap(kivansagok.begin(), kivansagok.end(), ComparePriorityQueue);
}
else {
pop_heap(kivansagok.begin(), kivansagok.end(), ComparePriorityQueue);
kivansagok.pop_back();
}
}
}
}
/// ---------------------------------------------------------------------------------------------------
/*
Megkeresi a legrövidebb utat a gráfban a "honnan" változóban tárolt városból a "hova" változóban tárolt
városig. A keresés során a gráfot statikusnak tekinti, vagyis eltekint attól, hogy ha mondjuk 3 napot
utazik, akkor az eltelt három nap alatt meg kéne, hogy változzanak a gráfban az élek súlyai.
*/
int Paszuj::Dijkstra(string honnan, string hova) {
int min_weight = graf.csucsok[honnan].min_dist[hova]; // Betöltöm a korábban elvégzett számolás eredményét. Ha eddig még nem végeztem volna el a számolást, akkor az előző sor 0-ra állítja a min_weight-et (mivel új elemet hozott létre a map-ben)
if (min_weight != 0) return min_weight; // Ha már egyszer elvégeztem a számítást, akkor nem kell még egyszer kiszámolni.
string min_name = honnan;
set<string> unvisited; // Azokat a csúcsokat tárolom benne, amikről nem tudom, hogy milyen hosszú a belé vezető legrövidebb út.
const int INF = INT_MAX;
for (auto i : graf.csucsok) { // Kezdetben felteszem, hogy minden csúcsba végtelen hosszú út vezet, és a későbbiekben ezen fogok javítani
graf.csucsok[i.first].dist = INF;
unvisited.insert(i.first);
}
/* Ez a ciklus azt csinálja, hogy mindig kiválasztja a legkisebb értékkel rendelkező csúcsot
(vagyis azt a csúcsot, ahova a legrövidebb út vezet, és még nem vizsgáltam),
és onnan kiindulva megnézem, hogy a többi csúcs értékét tudom-e javítani.
A ciklus addig tart, míg el nem érek odáig, hogy azt mondhatom, a cél hely jelenleg kiszámolt értékén
(a legrövidebb útvonal hosszán) már nem tudok javítani, ezért onnan kiindulva készülnék
javítani a többi csúcs értékén >> erre viszont már nincs szükség, az nem érdekel. */
while (min_name != hova) {
unvisited.erase(min_name);
int min_search = INF; // Ezt arra fogom használni, hogy megkeressem, hogy a javított értékű csúcsok közül megkeressem a legkisebbet, ahonnan a következő körben ki fogok indulni.
Csucs * actual = &(graf.csucsok[min_name]); // Ez a ciklusmag előző futása során talált legkisebb értékű csúcs, ebből fogok kiindulni
for (auto i : unvisited) {
int old_dist = graf.csucsok[i].dist; // A csúcs eddigi (talán javításra váró értéke)
if (actual->elek.count(i)) { // Ha vezet egyáltalán út a vizsgált csúcsból a javítandó csúcsba
// A ciklusmag ezen része javít az élek értékén, ha tud
int new_dist = min_weight + actual->elek[i];// Ennyi lenne az út hossza, ha abból a csúcsból indulnék, amit az előző körben a legkisebb értékűnek találtam
if (new_dist < old_dist) // Ha javít, akkor átírom a csúcs értékét
graf.csucsok[i].dist = new_dist;
// Ez a rész pedig a minimális, eddig még meg nem látogatott csúcsot keresi, ahonnan a következő körben kiindulva próbálok javítani
if (min_name == hova ? new_dist < min_search : new_dist <= min_search) { // Ezt azért írtam ilyen bonyolultan, hogy a legkisebb élű csúccsal sok egyenlő értékű csúcs van, akkor, ha köztük van a célhely, akkor ezt válassza ki legkisebbnek, mert akkor véget érhet a ciklus (a célhely értékén pedig akkor már úgyse tudok javítani)
min_search = new_dist;
min_name = i;
}
} // Ez a rész is a legkisebb értékű csúcsot keresi azok közt az elemek közt, ahova nem vezet él az előző körben minimálisnak talált csúcsból
else if (old_dist < min_search) {
min_search = old_dist;
min_name = i;
}
}
min_weight = min_search; // Ha a belső ciklus véget ért, akkor tudhatjuk, hogy megtaláltuk a minimális értékű csúcsot, aminek eltárolom az értékét a következő kör számára
}
graf.csucsok[honnan].min_dist[hova] = min_weight; // Elmentem a számítás értékét, vagyis, ha legközelebb pontosan e két csúcs közti legrövidebb utat keresem, akkor simán le tudom kérdezni a függvény elején, és nem kell újraszámolnom
return min_weight;
}
| true |
c7181d771648c3be1fb1744b68374ebbe036b42c | C++ | arunjain9988/CP | /spoj_main74/main.cpp | UTF-8 | 3,029 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h> // This will work only for g++ compiler.
#define loop(i, l, r) for (int i = (int)(l); i < (int)(r); ++i)
#define floop(i, l, r) for (int i = (int)(l); i <= (int)(r); ++i)
#define rloop(i, l, r) for (int i = (int)(l); i >= (int)(r); --i)
//short hand for usual tokens
#define pb push_back
#define mp make_pair
// to be used with algorithms that processes a container Eg: find(all(c),42)
#define all(x) (x).begin(), (x).end() //Forward traversal
#define rall(x) (x).rbegin, (x).rend() //reverse traversal
// traversal function to avoid long template definition. Now with C++11 auto alleviates the pain.
#define tr(c,i) for(__typeof__((c)).begin() i = (c).begin(); i != (c).end(); i++)
// trace program
#define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace1(x) cerr<<#x<<": "<<x<<endl
#define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl
// useful constants
#define MOD 1000000007
using namespace std;
// Shorthand for commonly used types
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef long long ll;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef double ld;
ll** matrixMul(ll** A,ll** B) {
ll** res = new ll*[2];
loop(i,0,2) res[i] = new ll[2];
for (ll i=0; i<2;i++) {
for (ll j=0; j<2; j++) {
res[i][j] = 0;
for (ll k=0; k<2; k++) {
res[i][j] += (A[i][k] * B[k][j])%MOD;
}
}
}
return res;
}
ll** matrixExp(ll** M,ll n) {
ll **res = new ll*[2];
res[0] = new ll[2];
res[1] = new ll[2];
res[0][0]=1,res[0][1]=0,res[1][0]=0,res[1][1]=1;
while(n) {
if (n&1) res = matrixMul(res,M);
M = matrixMul(M,M);
n>>=1;
}
return res;
}
int gcd1(int a,int b) {
if (b==0) return 0;
return (gcd1(b,a%b)+1);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.precision(10);
cout << fixed;
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
int t;
cin>>t;
ll n;
while(t--) {
cin>>n;
if (n==0){
cout<<1<<'\n';
continue;
}
ll **M = new ll*[2];
loop(i,0,2) {
M[i] = new ll[2];
}
M[0][0]=0,M[0][1]=1,M[1][0]=1,M[1][1]=1;
ll** mtopown = matrixExp(M,n);
ll ans = (mtopown[0][1] + mtopown[1][1])%MOD;
cout<<ans<<'\n';
// cout<<gcd1(mtopown[0][1],mtopown[1][1])<<'\n';
}
return 0;
}
| true |
669d681399f97959f8f704d220ae0c734727bcd9 | C++ | m5stack/M5Stack | /examples/Advanced/WIFI/WiFiTCP/WiFiTCP.ino | UTF-8 | 3,819 | 2.703125 | 3 | [
"MIT"
] | permissive | /*
*******************************************************************************
* Copyright (c) 2023 by M5Stack
* Equipped with M5Core sample source code
* 配套 M5Core 示例源代码
* Visit for more information: https://docs.m5stack.com/en/core/gray
* 获取更多资料请访问: https://docs.m5stack.com/zh_CN/core/gray
*
* Describe: WIFI TCP.
* Date: 2021/7/29
*******************************************************************************
M5Core will sends a message to a TCP server
M5Core 将向TCP服务器发送一条数据
*/
#include <M5Stack.h>
#include <WiFi.h>
#include <WiFiMulti.h>
// Set the name and password of the wifi to be connected.
// 配置所连接wifi的名称和密码
const char *ssid = "cam";
const char *password = "12345678";
WiFiMulti WiFiMulti;
void setup() {
int sum = 0;
M5.begin(); // Init M5Core. 初始化M5Core
M5.Power.begin(); // Init power 初始化电源模块
WiFiMulti.addAP(
ssid,
password); // Add wifi configuration information. 添加wifi配置信息
M5.lcd.printf(
"Waiting connect to WiFi: %s ...",
ssid); // Serial port output format string. 串口输出格式化字符串
while (WiFiMulti.run() !=
WL_CONNECTED) { // If the connection to wifi is not established
// successfully. 如果没有与wifi成功建立连接
M5.lcd.print(".");
delay(1000);
sum += 1;
if (sum == 8) M5.lcd.print("Conncet failed!");
}
M5.lcd.println("\nWiFi connected");
M5.lcd.print("IP address: ");
M5.lcd.println(WiFi.localIP()); // The serial port outputs the IP address
// of the M5Core. 串口输出M5Core的IP地址
delay(500);
}
void loop() {
M5.lcd.setCursor(0, 40);
const char *host = "www.baidu.com"; // Set the IP address or DNS of the TCP
// server. 设置TCP服务器的ip或dns
const uint16_t port =
80; // The port of the TCP server is specified. 设置TCP服务器的端口
M5.lcd.printf("Connecting to: %s\n", host);
WiFiClient client;
if (!client.connect(
host,
port)) { // Connect to the server. 0 is returned if the
// connection fails. 连接服务器,若连接失败返回0
M5.lcd.print(
"Connection failed.\nWaiting 5 seconds before retrying...\n");
delay(5000);
return;
}
// send an arbitrary string to the server. 发送一个字符串到上边连接的服务器
client.print("Send this data to the server");
// send a basic document request to the server.
// 向服务器发送一个基本的文档请求.
client.print("GET /index.html HTTP/1.1\n\n");
int maxloops = 0;
// wait for the server's reply to become available
//等待服务器的回复
while (!client.available() && maxloops < 1000) {
maxloops++;
delay(1); // delay 1 msec
}
if (client.available() >
0) { // Detects whether data is received. 检测是否接收到数据
String line = client.readStringUntil(
'\r'); // Read information from data received by the device until
// \r is read. 从设备接收到的数据中读取信息,直至读取到\r时
M5.lcd.println(line); // String received by serial port output.
// 串口输出接收到的字符串
} else {
M5.lcd.println("client.available() timed out ");
}
M5.lcd.println("Closing connection.");
client.stop();
M5.lcd.println("Waiting 5 seconds before restarting...");
delay(5000);
M5.lcd.fillRect(0, 40, 320, 220, BLACK);
}
| true |
de378b3a9669df45cca1b29454a37b921623e0ad | C++ | mikebessuille/Simulation | /SFMLGame/Unit.h | UTF-8 | 2,872 | 3 | 3 | [] | no_license | #pragma once
#include <SFML/Graphics.hpp>
#include <memory>
#include "PlayerUnit.h"
// Keep this outside the class, so that the ShapeList class (factory) can refer to it.
struct UnitDefaults
{
const float default_size;
const sf::Color default_colour;
const unsigned int default_healthGain; // how much health is gained when this unit is eaten
const unsigned int default_points; // how many points are gained when this unit is shot.
const unsigned int default_damage;
const unsigned int maxDestroyFrames;
};
class Unit
{
public:
Unit() = delete;
Unit(sf::Shape* ps, sf::Vector2f vel);
Unit(sf::Vector2f pos, sf::Vector2f vel, const UnitDefaults *pdef );
virtual ~Unit();
// These don't work with KW yet...
Unit& operator=(Unit rhs) = delete; // Disallow assignment operator, to prevent leaking of pshape
Unit(const Unit& other) = delete; // Disallow copy constructor, to prevent leaking of pshape
// These don't work because the base constructor will always call the base implementation of these functions
//virtual const float def_size() const { return default_size; }; /* returns Unit::default_size */
//virtual sf::Color def_colour() const { return default_colour; }; /* returns Unit::default_colour */
sf::Shape * getShape() { return(pshape); };
void move( const float speedFactor );
void setVelocity(const sf::Vector2f vel) { velocity = vel; }
sf::Vector2f getVelocity() { return velocity; }
virtual bool HandleCollision(PlayerUnit &player); // Player collided with the unit
virtual bool HandleShot(PlayerUnit &player); // Player shot the unit
void Render(shared_ptr<sf::RenderWindow> pwindow); // non-virtual
void RenderDestroy( shared_ptr<sf::RenderWindow> pwindow ); // non-virtual
virtual bool FinishedDestroying() { return(destroyFrames >= pdefaults->maxDestroyFrames); };
// Static functions:
static const UnitDefaults *GetDefaults() { return &defaults; }; // returns the Unit:: version of defaults.
private:
// Make these (copy ctor, assignment operator) private, simply because KW doesn't properly detect the C++11 "delete" functionality and will assume the default
// copy constructor & assignment operators were created, which leads KW to believe there are memory problems.
// Unit& operator=(Unit rhs); // Disallow assignment operator, to prevent leaking of pshape
// Unit(const Unit& other); // Disallow copy constructor, to prevent leaking of pshape
protected:
virtual void RenderAnimation();
virtual void RenderDestroyAnimation();
unsigned int GetDestroyFrameCount() { return(destroyFrames); };
virtual void Bounce(PlayerUnit &player);
private:
static const UnitDefaults defaults; // Must be public so that the factory can reference it
protected:
sf::Shape * pshape{ nullptr };
sf::Vector2f velocity{ (float)0.0, (float)0.0 };
const UnitDefaults * pdefaults;
private:
unsigned int destroyFrames{ 0 };
};
| true |
7da20fcf71a9ad3796f88327d303494a387fd321 | C++ | WuShuo94/uci_cs222p | /cs222p/src/rbf/rbfm.cc | UTF-8 | 31,543 | 2.859375 | 3 | [] | no_license |
#include "rbfm.h"
RecordBasedFileManager* RecordBasedFileManager::_rbf_manager = 0;
RecordBasedFileManager* RecordBasedFileManager::instance()
{
if(!_rbf_manager)
_rbf_manager = new RecordBasedFileManager();
return _rbf_manager;
}
RecordBasedFileManager::RecordBasedFileManager()
{
pfm = PagedFileManager::instance();
}
RecordBasedFileManager::~RecordBasedFileManager()
{
}
RC RecordBasedFileManager::createFile(const string &fileName) {
return pfm->createFile(fileName);
}
RC RecordBasedFileManager::destroyFile(const string &fileName) {
return pfm->destroyFile(fileName);
}
RC RecordBasedFileManager::openFile(const string &fileName, FileHandle &fileHandle) {
return pfm->openFile(fileName,fileHandle);
}
RC RecordBasedFileManager::closeFile(FileHandle &fileHandle) {
return pfm->closeFile(fileHandle);
}
RC RecordBasedFileManager::insertRecord(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const void *data, RID &rid) {
void *pageData = malloc(PAGE_SIZE);
void *formattedData = malloc(PAGE_SIZE);
RecordOffset rOffset;
PageInfo pageInfo;
//find a page with enough space for record inserting
short int dataSize = convertToFormattedData(recordDescriptor, data, formattedData);
rid.pageNum = findAvailablePage(fileHandle, dataSize, pageData);
//all exist pages have no enough space, append new one
if( rid.pageNum == fileHandle.getNumberOfPages() ){
rid.slotNum = 0;
//set the first slot descriptor in the page
rOffset.offset = 0;
rOffset.length = dataSize;
memcpy( pageData, formattedData, dataSize );
memcpy( (char*)pageData+PAGE_SIZE-sizeof(PageInfo)-sizeof(RecordOffset), &rOffset, sizeof(RecordOffset));
//set the page info descriptor
pageInfo.numOfSlots = 1;
pageInfo.recordSize = rOffset.offset + rOffset.length;
memcpy( (char*)pageData+PAGE_SIZE-sizeof(PageInfo) , &pageInfo, sizeof(PageInfo));
//write record data and corresponding descriptor to the page
fileHandle.appendPage(pageData);
//one of the exist pages has enough space.
//since this page been read in findAvailablePage function, and the data of this page has been store in pageData pointer.
//we don't need to read the page from file again for reducing disk IO.
}else{
memcpy( &pageInfo, (char*)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
//reuse the slot of deleted record
bool slotOfDelRec = false;
for(int i = 0; i < pageInfo.numOfSlots; i++) {
memcpy( &rOffset, (char*)pageData+PAGE_SIZE-sizeof(PageInfo)-sizeof(RecordOffset) * (i+1), sizeof(RecordOffset) );
if(rOffset.length == DeleteMark) {
rid.slotNum = i;
slotOfDelRec = true;
break;
}
}
if(!slotOfDelRec) { //current page has no slot of deleted record, append a new slot
rid.slotNum = pageInfo.numOfSlots;
pageInfo.numOfSlots++;
}
rOffset.offset = pageInfo.recordSize;
rOffset.length = dataSize;
pageInfo.recordSize += rOffset.length;
memcpy( (char*)pageData+PAGE_SIZE-sizeof(PageInfo)-sizeof(RecordOffset) * (rid.slotNum+1), &rOffset, sizeof(RecordOffset) );
memcpy( (char*)pageData+PAGE_SIZE-sizeof(PageInfo) , &pageInfo, sizeof(PageInfo));
memcpy( (char*)pageData+rOffset.offset , formattedData, dataSize);
fileHandle.writePage(rid.pageNum, pageData);
}
free(pageData);
free(formattedData);
return 0;
}
RC RecordBasedFileManager::readRecord(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid, void *data) {
void *pageData = malloc(PAGE_SIZE);
if(fileHandle.readPage(rid.pageNum, pageData) == -1) {
return -1;
}
RC rc = readRecordFromPage(fileHandle, recordDescriptor, rid, pageData, data);
free(pageData);
if(rc == -1)
return -1;
return 0;
}
RC RecordBasedFileManager::readRecordFromPage(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid, const void *pageData, void *data) {
RecordOffset recordOffset;
memcpy(&recordOffset, (char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (rid.slotNum + 1), sizeof(RecordOffset));
if(recordOffset.length == DeleteMark) {
// cout << "Deleted record can't be read!" << endl;
data = NULL;
return -1;
}
RID newRid;
if(recordOffset.length == TombstoneMark) {
memcpy(&newRid, (char *)pageData + recordOffset.offset, sizeof(RID));
return readRecord(fileHandle, recordDescriptor, newRid, data);
}
void *formattedData = malloc(PAGE_SIZE);
memcpy(formattedData, (char *)pageData + recordOffset.offset, recordOffset.length);
convertFromFormattedData(recordDescriptor, data, formattedData);
free(formattedData);
return 0;
}
RC RecordBasedFileManager::printRecord(const vector<Attribute> &recordDescriptor, const void *data) {
getDataSize(recordDescriptor, data, true);
return 0;
}
RC RecordBasedFileManager::deleteRecord(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid) {
void *pageData = malloc(PAGE_SIZE);
PageInfo pageInfo;
RecordOffset recordOffset;
if(fileHandle.readPage(rid.pageNum, pageData) == -1) {
return -1;
}
memcpy(&recordOffset, (char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (rid.slotNum + 1), sizeof(RecordOffset));
memcpy(&pageInfo, (char *)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
// cout << "RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "deleting! PageInfo: NumbeOfRecord, RecordSize = " << pageInfo.numOfSlots << ", " << pageInfo.recordSize << endl;
// cout << "RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "deleting! RecordOffset: offset, length = " << recordOffset.offset << ", " << recordOffset.length << endl;
//delete all address of tombstone
if(recordOffset.length == TombstoneMark) {
recordOffset.length = sizeof(RID);
RID newRid;
memcpy(&newRid, (char *)pageData+recordOffset.offset, sizeof(RID));
deleteRecord(fileHandle, recordDescriptor, newRid);
}
shiftData(pageData, pageInfo, recordOffset, rid, recordOffset.length);
recordOffset.length = DeleteMark;
// cout << "RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "deleted! PageInfo: NumbeOfRecord, RecordSize = " << pageInfo.numOfSlots << ", " << pageInfo.recordSize << endl;
// cout << "RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "deleted! RecordOffset: offset, length = " << recordOffset.offset << ", " << recordOffset.length << endl;
memcpy((char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (rid.slotNum + 1), &recordOffset, sizeof(RecordOffset));
memcpy((char *)pageData+PAGE_SIZE-sizeof(PageInfo), &pageInfo, sizeof(PageInfo));
fileHandle.writePage(rid.pageNum, pageData);
free(pageData);
return 0;
}
RC RecordBasedFileManager::updateRecord(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const void *data, const RID &rid) {
void *pageData = malloc(PAGE_SIZE);
void *formattedData = malloc(PAGE_SIZE);
if(fileHandle.readPage(rid.pageNum, pageData) == -1) {
return -1;
}
PageInfo pageInfo;
RecordOffset recordOffset;
RID currentRid = rid;
memcpy(&recordOffset, (char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (rid.slotNum + 1), sizeof(RecordOffset));
//get actual RID
while(recordOffset.length == TombstoneMark) {
memcpy(¤tRid, (char *)pageData + recordOffset.offset, sizeof(RID));
fileHandle.readPage(currentRid.pageNum, pageData);
memcpy(&recordOffset, (char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (currentRid.slotNum + 1), sizeof(RecordOffset));
}
memcpy(&pageInfo, (char *)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
short int dataSize = convertToFormattedData(recordDescriptor, data, formattedData);
short int difference = recordOffset.length - dataSize;
// cout << "Initial RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "updating! recordOffset: offset-length " << recordOffset.offset << ", " << recordOffset.length << ". ";
// cout << "difference: " << difference << endl;
// cout << "Get Current RID[" << currentRid.pageNum << ", " << currentRid.slotNum << "] " << endl;
short int freeSpace = PAGE_SIZE - pageInfo.recordSize - (pageInfo.numOfSlots+1)*sizeof(RecordOffset) - sizeof(PageInfo);
if((difference + freeSpace) >= 0) {
shiftData(pageData, pageInfo, recordOffset, (const RID)currentRid, difference);
memcpy((char*)pageData+recordOffset.offset, formattedData, dataSize);
recordOffset.length = dataSize;
} else {
//current page has no enough space, find a new address and store the updated record
void *newPageData = malloc(PAGE_SIZE); //use new void*. prevent previous pageInfo from being written into a new appended page
RID newRid;
PageInfo newPInfo;
RecordOffset newROffset;
newRid.pageNum = findAvailablePage(fileHandle, dataSize, newPageData);
// cout << "No enough space, find a new RID: " << newRid.pageNum << ", " << newRid.slotNum << endl;
if( newRid.pageNum == fileHandle.getNumberOfPages() ){ //new address points to a new page
newRid.slotNum = 0;
newROffset.offset = 0;
newROffset.length = dataSize;
memcpy( newPageData, formattedData, dataSize );
memcpy( (char*)newPageData+PAGE_SIZE-sizeof(PageInfo)-sizeof(RecordOffset), &newROffset, sizeof(RecordOffset));
newPInfo.numOfSlots = 1;
newPInfo.recordSize = newROffset.offset + newROffset.length;
memcpy( (char*)newPageData+PAGE_SIZE-sizeof(PageInfo) , &newPInfo, sizeof(PageInfo));
fileHandle.appendPage(newPageData);
} else {
fileHandle.readPage(newRid.pageNum, newPageData);
memcpy( &newPInfo, (char*)newPageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
bool slotOfDelRec = false;
for(int i = 0; i < newPInfo.numOfSlots; i++) {
memcpy( &newROffset, (char*)newPageData+PAGE_SIZE-sizeof(PageInfo)-sizeof(RecordOffset) * (i+1), sizeof(RecordOffset) );
if(newROffset.length == 0) {
newRid.slotNum = i;
slotOfDelRec = true;
break;
}
}
if(!slotOfDelRec) { //current page has no slot of deleted record, append a new slot
newRid.slotNum = newPInfo.numOfSlots;
newPInfo.numOfSlots++;
}
newROffset.offset = newPInfo.recordSize;
newROffset.length = dataSize;
newPInfo.recordSize += newROffset.length;
memcpy( (char*)newPageData+PAGE_SIZE-sizeof(PageInfo)-sizeof(RecordOffset) * (newRid.slotNum+1), &newROffset, sizeof(RecordOffset) );
memcpy( (char*)newPageData+PAGE_SIZE-sizeof(PageInfo) , &newPInfo, sizeof(PageInfo));
memcpy( (char*)newPageData+newROffset.offset , formattedData, dataSize);
fileHandle.writePage(newRid.pageNum, newPageData);
}
//modify the information of previous page, and shift data. because the slot of previous record has become tombstone
shiftData(pageData, pageInfo, recordOffset, (const RID)currentRid, recordOffset.length-sizeof(RID));
memcpy((char*)pageData+recordOffset.offset, &newRid, sizeof(RID));
recordOffset.length = TombstoneMark;
free(newPageData);
}
memcpy((char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (currentRid.slotNum + 1), &recordOffset, sizeof(RecordOffset));
memcpy((char *)pageData+PAGE_SIZE-sizeof(PageInfo), &pageInfo, sizeof(PageInfo));
fileHandle.writePage(currentRid.pageNum, pageData);
free(formattedData);
free(pageData);
return 0;
}
// this function is used to calculate the orignal data format's size from given test data
// put the flag here for options of printing
size_t RecordBasedFileManager::getDataSize(const vector<Attribute> &recordDescriptor, const void *data, bool printFlag) {
int offset = 0;
//initialize nullFieldsIndicator
int nullFieldsIndicatorActualSize = ceil((double)recordDescriptor.size() / CHAR_BIT);
unsigned char *nullFieldsIndicator = (unsigned char *) malloc(nullFieldsIndicatorActualSize);
//read the value of nullFieldsIndicator from record (pointer)
memset(nullFieldsIndicator, 0, nullFieldsIndicatorActualSize);
memcpy(nullFieldsIndicator, data, nullFieldsIndicatorActualSize);
//start to read a record, offset move to the first actual field of the record
offset += nullFieldsIndicatorActualSize;
//scan every bit of the nullFieldsIndicator
for(int i=0; i<recordDescriptor.size(); i++){
Attribute attribute = recordDescriptor[i];
string name = attribute.name;
AttrType type = attribute.type;
// if(printFlag) printf("<%d> %s[%d]: ",i,name.c_str(),length); //print description of one field
if(printFlag) printf("%s: ",name.c_str());
if( nullFieldsIndicator[i/8] & (1 << (7-(i%8)) ) ){ // the nth field is corresponding to the (7-(k%8))th bit of the [k/8] bype of the nullFieldsIndicator
if(printFlag) printf("NULL\n");
continue;
}
void *buffer;
if( type == TypeVarChar ){
//use buffer to read the length of varChar
buffer = malloc(sizeof(int));
memcpy( buffer , (char*)data+offset, sizeof(int));
offset += sizeof(int);
int varCharLength = *(int*)buffer;
// if(printFlag) printf("%i ",varCharLength);
free(buffer);
//use buffer to read the content of varChar
buffer = malloc(varCharLength+1); // null terminator
memcpy( buffer, (char*)data+offset, varCharLength);
offset += varCharLength;
((char *)buffer)[varCharLength]='\0';
if(printFlag) printf("%s\n",buffer);
free(buffer);
continue;
}
size_t size;
if( type == TypeReal ){
size = sizeof(float);
buffer = malloc(size);
memcpy( buffer , (char*)data+offset, size);
offset += size;
if(printFlag) printf("%f \n",*(float*)buffer);
}else{ //type = TypeInt
size = sizeof(int);
buffer = malloc(size);
memcpy( buffer , (char*)data+offset, size);
offset += size;
if(printFlag) printf("%i \n",*(int*)buffer);
}
free(buffer);
}
free(nullFieldsIndicator);
return offset;
}
unsigned RecordBasedFileManager::findAvailablePage(FileHandle &fileHandle, const short int dataSize, void *pageData) {
//if no page exist
if(fileHandle.getNumberOfPages() == 0) {
return 0;
}
unsigned pageNum = fileHandle.getNumberOfPages() - 1;
short int freeSpace;
PageInfo pageInfo;
fileHandle.readPage(pageNum, pageData);
memcpy(&pageInfo, (char *)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
freeSpace = PAGE_SIZE - pageInfo.recordSize - (pageInfo.numOfSlots+1)*sizeof(RecordOffset) - sizeof(PageInfo);
//if last page in the file has enough space, return the pageNum
if(freeSpace >= dataSize) {
return pageNum;
}
//find a page with enough space within 0th and (numberOfPages-1)th page
for(pageNum = 0; pageNum < fileHandle.getNumberOfPages() - 1; ++pageNum) {
fileHandle.readPage(pageNum, pageData);
memcpy(&pageInfo, (char *)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
freeSpace = PAGE_SIZE - pageInfo.recordSize - (pageInfo.numOfSlots+1)*sizeof(RecordOffset) - sizeof(PageInfo);
if(freeSpace >= dataSize) {
return pageNum;
}
}
//All of the existing pages have no enough space. then create a new page for the record
pageNum = fileHandle.getNumberOfPages();
return pageNum;
}
short int RecordBasedFileManager::convertToFormattedData(const vector<Attribute> &recordDescriptor, const void *data, void * formattedData) {
short int offset = 0; //offset for input data
short int formattedOffset = 0; //offset for formatted data
int fieldNum = recordDescriptor.size();
int nullFieldsIndicatorActualSize = ceil((double)fieldNum / CHAR_BIT);
unsigned char *nullFieldsIndicator = (unsigned char *) malloc(nullFieldsIndicatorActualSize);
memcpy(nullFieldsIndicator, data, nullFieldsIndicatorActualSize);
formattedOffset = formattedOffset + fieldNum * sizeof(short int);
offset += nullFieldsIndicatorActualSize;
//scan every bit of the nullFieldsIndicator
for(int i=0; i<recordDescriptor.size(); i++){
AttrType type = recordDescriptor[i].type;
if(nullFieldsIndicator[i/8] & (1 << (7-(i%8)))) {
memcpy((char*)formattedData+i*sizeof(short int), &formattedOffset, sizeof(short int));
continue;
}
if(type == TypeVarChar){
void *buffer;
buffer = malloc(sizeof(int));
memcpy(buffer , (char*)data+offset, sizeof(int));
offset += sizeof(int);
int varCharLength = *(int*)buffer;
free(buffer);
if(!varCharLength) { //input an empty string but not NULL. manually insert a '\0' to indicate that it is not NULL.
void *buffer = malloc(sizeof(char));
((char *)buffer)[varCharLength] = '\0';
memcpy((char*)formattedData+formattedOffset, buffer, sizeof(char));
formattedOffset += sizeof(char);
memcpy((char*)formattedData+i*sizeof(short int), &formattedOffset, sizeof(short int));
free(buffer);
continue;
}
memcpy((char*)formattedData+formattedOffset, (char*)data+offset, varCharLength);
offset += varCharLength;
formattedOffset += varCharLength;
memcpy((char*)formattedData+i*sizeof(short int), &formattedOffset, sizeof(short int));
continue;
}
size_t size;
if(type == TypeReal)
size = sizeof(float);
else
size = sizeof(int);
memcpy((char*)formattedData+formattedOffset, (char*)data+offset, size);
offset += size;
formattedOffset += size;
memcpy((char*)formattedData+i*sizeof(short int), &formattedOffset, sizeof(short int));
}
//keep the minimum length of each record
if(formattedOffset < sizeof(RID)) {
for(int i = formattedOffset; i < sizeof(RID); i++) {
*((char *)formattedData+i) = '\0';
}
formattedOffset = sizeof(RID);
}
free(nullFieldsIndicator);
return formattedOffset;
}
short int RecordBasedFileManager::convertFromFormattedData(const vector<Attribute> &recordDescriptor, void *data, const void *formattedData) {
short int offset = 0; //offset for input data
short int preFormattedOffset = 0; //offset for formatted data
short int nextFormattedOffset = 0;
int fieldNum = recordDescriptor.size();
int nullFieldsIndicatorActualSize = ceil((double)fieldNum / CHAR_BIT);
unsigned char *nullFieldsIndicator = (unsigned char *) malloc(nullFieldsIndicatorActualSize);
memset(nullFieldsIndicator, 0, nullFieldsIndicatorActualSize);
preFormattedOffset = preFormattedOffset + fieldNum * sizeof(short int);
offset += nullFieldsIndicatorActualSize;
for(int i=0; i<fieldNum; i++){
AttrType type = recordDescriptor[i].type;
memcpy(&nextFormattedOffset, (char*)formattedData+i*sizeof(short int), sizeof(short int));
if(nextFormattedOffset == preFormattedOffset) {
nullFieldsIndicator[i/8] = nullFieldsIndicator[i/8] | (1 << (7-(i%8)));
continue;
}
if(type == TypeVarChar){
int varCharLength = nextFormattedOffset - preFormattedOffset;
// check whether there is a '\0' char to indicate it is an empty string
if(varCharLength == 1) {
void *emptyBuffer = malloc(sizeof(char));
memcpy(emptyBuffer, (char*)formattedData+preFormattedOffset, varCharLength);
if(*((char*)emptyBuffer) == '\0') {
varCharLength = 0;
memcpy((char*)data+offset , &varCharLength, sizeof(int));
offset += sizeof(int);
offset += varCharLength;
preFormattedOffset = nextFormattedOffset;
free(emptyBuffer);
continue;
}
free(emptyBuffer);
}
memcpy((char*)data+offset , &varCharLength, sizeof(int));
offset += sizeof(int);
memcpy((char*)data+offset, (char*)formattedData+preFormattedOffset, varCharLength);
offset += varCharLength;
preFormattedOffset = nextFormattedOffset;
continue;
}
size_t size;
if(type == TypeReal)
size = sizeof(float);
else
size = sizeof(int);
memcpy((char*)data+offset, (char*)formattedData+preFormattedOffset, size);
offset += size;
preFormattedOffset = nextFormattedOffset;
}
memcpy((char*)data, (char*)nullFieldsIndicator, nullFieldsIndicatorActualSize);
free(nullFieldsIndicator);
return offset;
}
RC RecordBasedFileManager::shiftData(void *pageData, PageInfo &pageInfo, RecordOffset &recordOffset, const RID rid, short int distance) {
short int followROffset = recordOffset.length + recordOffset.offset;
//if deleted record is the last one in the page, shifting is not needed
if(followROffset != pageInfo.recordSize) {
short int shiftDataSize = pageInfo.recordSize - followROffset;
RecordOffset tempROffset;
void *temp = malloc(shiftDataSize);
memcpy(temp, (char*)pageData + followROffset, shiftDataSize);
//if distance is positive, it means data will be moved forward (delete data or update a smaller record) and more free space is available
memcpy((char*)pageData + followROffset - distance, temp, shiftDataSize);
free(temp);
for(int i = 0; i < pageInfo.numOfSlots; i++) {
memcpy(&tempROffset, (char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (i + 1), sizeof(RecordOffset));
if(tempROffset.offset > recordOffset.offset) {
tempROffset.offset = tempROffset.offset - distance;
memcpy((char *)pageData + PAGE_SIZE - sizeof(PageInfo) - sizeof(RecordOffset) * (i + 1), &tempROffset, sizeof(RecordOffset));
}
}
}
// cout << "RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "shifting, PageInfo: RecordSize = " << pageInfo.recordSize << endl;
pageInfo.recordSize = pageInfo.recordSize - distance;
// cout << "RID[" << rid.pageNum << ", " << rid.slotNum << "] " << "shifted, PageInfo: RecordSize = " << pageInfo.recordSize << endl;
return 0;
}
RC RecordBasedFileManager::readAttribute(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid, const string &attributeName, void *data)
{
void *record = malloc(PAGE_SIZE);
readRecord(fileHandle, recordDescriptor, rid, record);
if(getAttributeFromRecord(recordDescriptor, attributeName, record, data) == -1){
free(record);
return -1;
}
free(record);
return 0;
}
RC RecordBasedFileManager::getAttributeFromRecord(const vector<Attribute> &recordDescriptor, const string &attributeName, const void *record, void *data)
{
short int offset = 0;
int length = 0;
Attribute attr;
int nullFieldsIndicatorActualSize = ceil((double)recordDescriptor.size() / CHAR_BIT);
unsigned char *nullFieldsIndicator = (unsigned char *) malloc(nullFieldsIndicatorActualSize);
memcpy(nullFieldsIndicator, record, nullFieldsIndicatorActualSize);
offset += nullFieldsIndicatorActualSize;
memset(data, 0, 1);
for(int i = 0; i < recordDescriptor.size(); i++) {
attr = recordDescriptor.at(i);
if(attr.name == attributeName) {
if(nullFieldsIndicator[i/8] & (1 << (7-(i%8)))){
((char *)data)[0] = ((char *)data)[0] | (1 << 7);
// cout<<attr.name<<" "<<attributeName<<endl;
// ((char *)data)[0] = '\0';
free(nullFieldsIndicator);
return 0;
}
if(attr.type == TypeVarChar) {
memcpy(&length, (char*)record+offset, sizeof(int));
memcpy((char *)data + 1, (char*)record+offset, sizeof(int)+length);
free(nullFieldsIndicator);
return 0;
} else {
memcpy((char *)data + 1, (char*)record+offset, sizeof(int));
free(nullFieldsIndicator);
return 0;
}
}
//current attribute is not desired attribute, check next one
if(nullFieldsIndicator[i/8] & (1 << (7-(i%8)))) {
//corresponding data is NULL. offset += 0.
continue;
}
if(attr.type == TypeVarChar) { //skip a TypeVarChar, length + sizeof(int) bytes.
memcpy(&length, (char*)record+offset, sizeof(int));
offset += (length + sizeof(int));
} else { //skip a TypeFloat or TypeInt, 4 bytes.
offset += sizeof(int);
}
}
//the desired attribute is not found in the attributeDescriptor.
free(nullFieldsIndicator);
return -1;
}
RC RecordBasedFileManager::scan(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const string &conditionAttribute,
const CompOp compOp, const void *value, const vector<string> &attributeNames, RBFM_ScanIterator &rbfm_ScanIterator) {
return rbfm_ScanIterator.prepareIterator(fileHandle,recordDescriptor,conditionAttribute,compOp,value,attributeNames);
}
RC RBFM_ScanIterator::prepareIterator(FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const string &conditionAttribute,
const CompOp compOp, const void *value, const vector<string> &attributeNames)
{
// assert( value != NULL && "value pointer should not be null" );
this->rbfm = RecordBasedFileManager::instance();
rbfm -> openFile(fileHandle.bindFileName, this->fileHandle);
this->recordDescriptor = recordDescriptor;
this->attributeNames = attributeNames;
this->compOp = compOp;
this->value = (char *)value;
this->compResult = 0;
this->c_rid.pageNum = 0;
this->c_rid.slotNum = 0;
this->pageData = malloc(PAGE_SIZE);
this->record = malloc(PAGE_SIZE);
this->conditionValue = malloc(PAGE_SIZE);
if(fileHandle.readPage(c_rid.pageNum, pageData) == -1) {
return -1;
}
memcpy(&(this->pageInfo), (char*)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
for(int i = 0; i < recordDescriptor.size(); i++) {
compAttr = recordDescriptor.at(i);
if (compAttr.name == conditionAttribute) {
// cout << "compAttr.name: " << compAttr.name << endl;
return 0;
}
}
return -1;
}
RC RBFM_ScanIterator::getNextRecord(RID &rid, void *data)
{
while(1) {
if(c_rid.slotNum >= pageInfo.numOfSlots) {
c_rid.pageNum++;
c_rid.slotNum = 0;
if(c_rid.pageNum >= fileHandle.getNumberOfPages())
return EOF;
if(fileHandle.readPage(c_rid.pageNum, pageData) != 0)
return -1;
memcpy(&pageInfo, (char*)pageData+PAGE_SIZE-sizeof(PageInfo), sizeof(PageInfo));
}
// current c_rid is the slot of tombstone, skip this slot and read next one
RecordOffset rOffset;
memcpy(&rOffset, (char*)pageData+PAGE_SIZE-sizeof(PageInfo)-(c_rid.slotNum+1)*sizeof(RecordOffset), sizeof(RecordOffset));
if(rOffset.length == TombstoneMark) {
c_rid.slotNum++;
continue;
}
// current c_rid is the slot of deleted record, skip this slot and read next one
if(rbfm -> readRecordFromPage(fileHandle, recordDescriptor, c_rid, pageData, record) == -1) {
c_rid.slotNum++;
continue;
}
if(rbfm -> getAttributeFromRecord(recordDescriptor, compAttr.name, record, conditionValue) == -1)
return -1;
if(((((char *)conditionValue)[0] & (1 << 7)) && value == NULL && compOp == EQ_OP) || (compOp == NO_OP)) { //Field is NULL
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
if((((char *)conditionValue)[0] & (1 << 7)) | (value == NULL)){
c_rid.slotNum++;
continue;
}
if(compAttr.type == TypeVarChar) {
int len1 = 0;
int len2 = 0;
memcpy(&len1, (char *)conditionValue + 1, sizeof(int));
memcpy(&len2, value, sizeof(int));
char *pc1 = (char *)malloc(len1+1);
char *pc2 = (char *)malloc(len2+1);
memcpy(pc1, (char*)conditionValue+sizeof(int)+1, len1);
memcpy(pc2, (char*)value+sizeof(int), len2);
//!!!Warning!!! the end of char* should be '\0'!!! Otherwise there will be some strange chars at the end.
pc1[len1] = '\0';
pc2[len2] = '\0';
compResult = strcmp(pc1, pc2);
//// cout << len1 << endl;
// cout << len2 << endl;
// cout << pc1 << endl;
// cout << pc2 << endl;
// cout << compResult << endl;
free(pc1);
free(pc2);
} else if(compAttr.type == TypeInt) {
// cout << "comparing TypeInt!!!" << endl;
int v1;
int v2;
memcpy(&v1, (char *)conditionValue+1, sizeof(int));
memcpy(&v2, value, sizeof(int));
compResult = v1 - v2;
// cout << "Comparing TypeInt in rbfm.getNextRecord()." << endl;
// cout << v1 << endl;
// cout << v2 << endl;
// cout << compResult << endl;
// cout<<"---------------------"<<endl;
} else if(compAttr.type == TypeReal) {
float v1;
float v2;
memcpy(&v1, (char *)conditionValue+1, sizeof(float));
memcpy(&v2, value, sizeof(float));
// cout << "comparing TypeReal!!!" << endl;
// cout << v1 << endl;
// cout << v2 << endl;
if(v1>v2 && fabs(v1-v2)>1E-6)
compResult = 1;
else if (v1<v2 && fabs(v1-v2)>1E-6)
compResult = -1;
else
compResult = 0;
// cout << compResult << endl;
}
switch(compOp){
case EQ_OP:
{
if(compResult == 0){
readVectorAttribute(record, data);
// int t_id;
// memcpy(&t_id, (char *)data + 1, sizeof(int));
// cout<<"t_id: "<<t_id<<endl;
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
break;
}
case LT_OP:
{
if(compResult < 0){
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
break;
}
case LE_OP:
{
if(compResult <= 0){
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
break;
}
case GT_OP:
{
if(compResult > 0){
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
break;
}
case GE_OP:
{
if(compResult >= 0){
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
break;
}
case NE_OP:
{
if(compResult != 0){
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
break;
}
case NO_OP:
{
readVectorAttribute(record, data);
rid.pageNum = c_rid.pageNum;
rid.slotNum = c_rid.slotNum;
c_rid.slotNum++;
return 0;
}
}
c_rid.slotNum++;
}
}
RC RBFM_ScanIterator::readVectorAttribute(void *record, void *data){
Attribute attr;
int null_bit = ceil(1.0*attributeNames.size()/8);
int null_bit_r = ceil(1.0*recordDescriptor.size()/8);
unsigned char* null_indicator = (unsigned char*)malloc(null_bit);
unsigned char* null_indicator_r = (unsigned char*)malloc(null_bit_r);
int offset = null_bit;
int offset_r = null_bit_r;
memset(null_indicator, 0, null_bit);
memcpy(null_indicator_r, record, null_bit_r);
// cout<<attributeNames[0]<<endl;
for(int i = 0; i < attributeNames.size(); i++) {
offset_r = null_bit_r;
for(int j = 0; j < recordDescriptor.size(); j++) {
attr = recordDescriptor[j];
if(null_indicator_r[j/8] & (1 << (7 - j % 8))){
if(attributeNames[i] == attr.name) {
null_indicator[i/8] = (null_indicator[i/8] | (1 << (7-(i%8))));
break;
}
continue;
}
if(attr.type == TypeVarChar){
int len = 0;
memcpy(&len, (char *)record + offset_r, sizeof(int));
offset_r += sizeof(int);
if(attributeNames[i] == attr.name) {
memcpy((char *)data + offset, &len, sizeof(int));
offset += sizeof(int);
memcpy((char *)data + offset, (char *)record + offset_r, len);
offset += len;
}
offset_r += len;
}
if(attr.type == TypeInt){
if(attributeNames[i] == attr.name) {
memcpy((char *)data + offset, (char *)record + offset_r, sizeof(int));
offset += sizeof(int);
}
offset_r += sizeof(int);
}
if(attr.type == TypeReal){
if(attributeNames[i] == attr.name) {
memcpy((char *)data + offset, (char *)record + offset_r, sizeof(float));
offset += sizeof(float);
}
offset_r += sizeof(float);
}
}
}
memcpy((char *)data, (char *)null_indicator, null_bit);
free(null_indicator);
free(null_indicator_r);
return 0;
}
RC RBFM_ScanIterator::close() {
c_rid.pageNum = 0;
free(pageData);
free(record);
free(conditionValue);
rbfm->closeFile(fileHandle);
return 0;
};
| true |
d24ce80af972ba1062b96d2d6cf63aadfe6c0bd5 | C++ | Insanious/Lua-compiler | /Environment.cc | UTF-8 | 981 | 3.28125 | 3 | [] | no_license | #include "Environment.h"
#include "Nodes.h"
Environment::Environment() {}
Environment::~Environment() {}
Expression* Environment::read(Expression* variable)
{
if (exists(variable))
{
std::string name = "";
variable->evaluate(name);
return variables[name];
}
return nullptr;
}
void Environment::write(Expression* variable, Expression* expression)
{
std::string name = "";
variable->evaluate(name);
/*if (exists(variable))
{
if (variables[name]->type != expression->type)
{
std::cout << "syntax error: trying to write to variable of different type\n";
return;
}
}*/
variables[name] = expression;
}
bool Environment::exists(Expression* variable)
{
//std::cout << "bool Environment::exists(Expression* variable)\n";
std::string name = "";
variable->evaluate(name);
bool doesExist = variables.count(name) != 0;
/*if (doesExist)
std::cout << "-Variable does exist\n";
else
std::cout << "-Variable does exist\n";*/
return doesExist;
}
| true |
a362c38f99655e821d8b13952440941c2ceaa2f4 | C++ | jusseb/artemis | /software/BeagleBone/beaglebone/source/tests/pycubed_test.cpp | UTF-8 | 4,367 | 2.546875 | 3 | [
"MIT"
] | permissive |
#include <iostream>
#include <fstream>
#include <iomanip>
#include "device/temp_sensors.h"
#include "support/configCosmos.h"
#include "device/PyCubed.h"
using namespace std;
using namespace cubesat;
PyCubed *pycubed;
bool shutdown_received = false;
void Shutdown();
int main(int argc, char ** argv) {
int uart_device, baud_rate;
switch ( argc ) {
case 3:
uart_device = atoi(argv[1]);
baud_rate = atoi(argv[2]);
break;
default:
printf("Usage: pycubed_test uart_num baud_rate\n");
printf("Ex: pycubed_test 4 9600\n");
return 1;
}
pycubed = new PyCubed(uart_device, baud_rate);
pycubed->SetShutdownCallback(Shutdown);
printf("Attempting to connect to PyCubed on UART%d with baud %d\n", uart_device, baud_rate);
const int kConnectAttempts = 5;
// Attempt to connect to the PyCubed
for (int i = 0; i < kConnectAttempts; ++i) {
if ( pycubed->Open() < 0 ) {
printf("Failed to connect to PyCubed. Trying again...\n");
pycubed->Close();
continue;
}
else {
printf("Connected to PyCubed\n");
break;
}
COSMOS_SLEEP(1);
}
// Exit if the PyCubed is not open
if ( !pycubed->IsOpen() ) {
// Exit upon failure to connect
printf("Fatal: could not connect to PyCubed\n");
delete pycubed;
exit(1);
}
PyCubedIMUInfo imu;
PyCubedGPSInfo gps;
PyCubedPowerInfo power;
PyCubedTempInfo temp;
printf("======================================\n");
const int kPollCount = 5;
// Test polling messages
for (int i = 0; i < kPollCount; ++i) {
printf("Polling messages from PyCubed (%d/%d)\n", i, kPollCount);
for (; pycubed->ReceiveNextMessage();) {
}
// Retrieve device info
imu = pycubed->GetIMUInfo();
gps = pycubed->GetGPSInfo();
power = pycubed->GetPowerInfo();
temp = pycubed->GetTempInfo();
printf("======================================\n");
printf("IMU Data: \n");
printf("\tTimestamp: %f\n", imu.utc);
printf("\tAccel: (%.2f, %.2f, %.2f)\n", imu.acceleration.x, imu.acceleration.y, imu.acceleration.z);
printf("\tMagnetic: (%.2f, %.2f, %.2f)\n", imu.magnetometer.x, imu.magnetometer.y, imu.magnetometer.z);
printf("\tGyro: (%.2f, %.2f, %.2f)\n", imu.gyroscope.x, imu.gyroscope.y, imu.gyroscope.z);
printf("\n");
printf("GPS Data: \n");
printf("\tTimestamp: %f\n", gps.utc);
printf("\tHas Fix: %s\n", gps.has_fix ? "true" : "false");
printf("\tLatitude: %.4f degrees\n", gps.latitude);
printf("\tLongitude: %.4f degrees\n", gps.longitude);
printf("\tAltitude: %.2f m\n", gps.altitude);
printf("\tSpeed: %.2f m/s\n", gps.speed);
printf("\tFix Quality: %d\n", gps.fix_quality);
printf("\tSatellites Used: %d\n", gps.sats_used);
printf("\tAzimuth: %.2f degrees\n", gps.azimuth);
printf("\tHoriz. Dilution: %.2f\n", gps.horizontal_dilution);
printf("\n");
printf("Temperature Data: \n");
printf("\tTimestamp: %f\n", temp.utc);
printf("\tCPU Temp: %.2f\n", temp.cpu_temp);
printf("\tBattery Temp: %.2f\n", temp.batt_temp);
printf("\n");
printf("Power Data: \n");
printf("\tTimestamp: %f\n", power.utc);
printf("\tBattery Voltage: %.2f V\n", power.batt_voltage);
printf("\tBattery Current: %.2f mA\n", power.batt_current);
printf("\tSystem Voltage: %.2f V\n", power.sys_voltage);
printf("\tSystem Current: %.2f mA\n", power.sys_current);
printf("======================================\n");
COSMOS_SLEEP(1);
}
// Test startup confirmation signal
printf("Sending startup confirmation signal\n\n");
pycubed->StartupConfirmation();
COSMOS_SLEEP(2);
// Test kill radio signal
printf("Sending 'kill radio' signal\n\n");
pycubed->KillRadio();
COSMOS_SLEEP(2);
// Test shutdown signal
printf("Waiting for shutdown signal...\n");
const int kShutdownWait = 10;
for (int i = 0; i < kShutdownWait && !shutdown_received; ++i) {
// Poll messages
pycubed->ReceiveMessages();
if ( !shutdown_received )
printf("No shutdown signal received\n");
COSMOS_SLEEP(1);
}
if ( !shutdown_received ) {
printf("Did not receive shutdown signal: timed out\n");
}
printf("Test complete. Exiting now.\n");
delete pycubed;
return 0;
}
void Shutdown() {
shutdown_received = true;
printf("Shutdown signal received.\n");
printf("Sending 'handoff' signal.\n");
// Send the handoff signal
pycubed->Handoff();
COSMOS_SLEEP(2);
}
| true |
7d1a6db02e3237db5041726fd1c498046112aaa5 | C++ | yagisumi/ruby-gdiplus | /ext/gdiplus/gdip_utils.h | UTF-8 | 2,079 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
* gdip_utils.h
* Copyright (c) 2017 Yagi Sumiya
* Released under the MIT License.
*/
static inline int
_RB_RANGE_P(VALUE v)
{
return RB_TEST(rb_obj_is_kind_of(v, rb_cRange));
}
static inline float
NUM2SINGLE(VALUE num)
{
return static_cast<float>(NUM2DBL(num));
}
static inline VALUE
SINGLE2NUM(float n)
{
return DBL2NUM(round(static_cast<double>(n) * 1000000.0) / 1000000.0);
}
static inline const char * __method__() { return rb_id2name(rb_frame_this_func()); }
static inline const char * __class__(VALUE self) { return rb_class2name(CLASS_OF(self)); }
template <typename T>
static inline T
clamp(T val, T min, T max)
{
if (val < min) return min;
else if (max < val) return max;
else return val;
}
static inline bool
Integer_p(int argc, VALUE *argv)
{
for (int i = 0; i < argc; ++i) {
if (!RB_INTEGER_TYPE_P(argv[i])) return false;
}
return true;
}
static inline bool
Integer_p(VALUE v1)
{
return (RB_INTEGER_TYPE_P(v1));
}
static inline bool
Integer_p(VALUE v1, VALUE v2)
{
return (Integer_p(v1) && Integer_p(v2));
}
static inline bool
Integer_p(VALUE v1, VALUE v2, VALUE v3)
{
return (Integer_p(v1, v2) && Integer_p(v3));
}
static inline bool
Integer_p(VALUE v1, VALUE v2, VALUE v3, VALUE v4)
{
return (Integer_p(v1, v2, v3) && Integer_p(v4));
}
static inline bool
Float_p(int argc, VALUE *argv)
{
for (int i = 0; i < argc; ++i) {
if (!_RB_FLOAT_P(argv[i])) return false;
}
return true;
}
static inline bool
Float_p(VALUE v1)
{
return (_RB_FLOAT_P(v1));
}
static inline bool
Float_p(VALUE v1, VALUE v2)
{
return (Float_p(v1) && Float_p(v2));
}
static inline bool
Float_p(VALUE v1, VALUE v2, VALUE v3)
{
return (Float_p(v1, v2) && Float_p(v3));
}
static inline bool
Float_p(VALUE v1, VALUE v2, VALUE v3, VALUE v4)
{
return (Float_p(v1, v2, v3) && Float_p(v4));
}
static inline bool
Typeddata_p(int argc, VALUE *argv, const rb_data_type_t *type)
{
for (int i = 0; i < argc; ++i) {
if (!_KIND_OF(argv[i], type)) return false;
}
return true;
} | true |
9ddacf81f275b361f52e930cd8edce5209d6fb12 | C++ | frankencode/fluxkit | /core/src/exceptions.h | UTF-8 | 5,140 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef FLUX_EXCEPTIONS_H
#define FLUX_EXCEPTIONS_H
/** \file exceptions
* \brief Common exception classes
*/
#include <errno.h>
#include <flux/Exception>
namespace flux {
/** \brief User input ambiguous, report back to user and provide guidance
*/
class UsageError: public Exception
{
public:
UsageError(String message): message_(message) {}
~UsageError() throw() {}
virtual String message() const { return message_; }
private:
String message_;
};
/** \brief User requested help
*/
class HelpError: public Exception
{
public:
~HelpError() throw() {}
virtual String message() const { return "No help, yet ..."; }
};
/** \brief Some encoded data is mailformed
*/
class EncodingError: public Exception
{
public:
~EncodingError() throw() {}
};
/** \brief End of input reached although more data is needed
*/
class UnexpectedEndOfInputError: public Exception
{
public:
~UnexpectedEndOfInputError() throw() {}
virtual String message() const { return "Unexpected end of input"; }
};
/** \brief Some buffer size is exceeded
*/
class BufferOverflow: public Exception
{
public:
~BufferOverflow() throw() {}
virtual String message() const { return "Buffer overflow"; }
};
/** \brief Debugging hint on internal system malfunction
*/
class DebugError: public Exception
{
public:
DebugError(String reason, const char *source, int line):
reason_(reason),
source_(source),
line_(line)
{}
~DebugError() throw() {}
virtual String message() const;
private:
String reason_;
const char *source_;
int line_;
};
/** \brief System call failed
*/
class SystemError: public Exception
{
public:
SystemError(int errorCode): errorCode_(errorCode) {}
~SystemError() throw() {}
inline int errorCode() const { return errorCode_; }
protected:
int errorCode_;
};
/** \brief System call failed to perform an action on a named resource (e.g. a file)
*/
class SystemResourceError: public SystemError
{
public:
SystemResourceError(int errorCode, String resource, const char *source, int line):
SystemError(errorCode),
resource_(resource),
source_(source),
line_(line)
{}
~SystemResourceError() throw() {}
inline String resource() const { return resource_; }
inline const char *source() const { return source_; }
inline int line() const { return line_; }
virtual String message() const;
private:
String resource_;
const char *source_;
int line_;
};
/** \brief Debugging hint on system call failure
*/
class SystemDebugError: public SystemError
{
public:
SystemDebugError(int errorCode, const char *source, int line):
SystemError(errorCode),
source_(source),
line_(line)
{}
~SystemDebugError() throw() {}
inline const char *source() const { return source_; }
inline int line() const { return line_; }
virtual String message() const;
private:
const char *source_;
int line_;
};
#define FLUX_DEBUG_ERROR(reason) \
throw DebugError(reason, __FILE__, __LINE__)
#define FLUX_SYSTEM_RESOURCE_ERROR(errorCode, resource) \
throw SystemResourceError(errorCode, resource, __FILE__, __LINE__)
#define FLUX_SYSTEM_DEBUG_ERROR(errorCode) \
throw SystemDebugError(errorCode, __FILE__, __LINE__)
#define FLUX_SYSTEM_ERROR(errorCode, resource) \
{ \
if (resource != "") FLUX_SYSTEM_RESOURCE_ERROR(errorCode, resource); \
else FLUX_SYSTEM_DEBUG_ERROR(errorCode); \
}
/** \brief General error related to a text (progam text, config file, etc.)
*/
class TextError: public Exception
{
public:
inline String text() const { return text_; }
inline int offset() const { return offset_; }
inline String resource() const { return resource_; }
void setResource(String resource) { resource_ = resource; }
protected:
TextError(String text, int offset, String resource = "");
~TextError() throw() {}
String text_;
int offset_;
String resource_;
};
/** \brief Semantic error
*/
class SemanticError: public TextError
{
public:
SemanticError(String reason, String text = "", int offset = -1, String resource = ""):
TextError(text, offset, resource),
reason_(reason)
{}
~SemanticError() throw() {}
inline String reason() const { return reason_; }
virtual String message() const;
private:
String reason_;
};
String signalName(int signal);
/** \brief Signal received
*/
class Interrupt: public Exception
{
public:
Interrupt(int signal);
~Interrupt() throw() {}
inline int signal() const { return signal_; }
String signalName() const;
virtual String message() const;
private:
int signal_;
};
/** \brief Operation timed out
*/
class Timeout: public Exception
{
public:
~Timeout() throw() {}
virtual String message() const { return "Operation timed out"; }
};
} // namespace flux
#endif // FLUX_EXCEPTIONS_H
| true |
24cf4b581be0be8bdaff5c302e346f33bd452687 | C++ | cestrell/ExtendedEuclidean | /extended_euclid.cpp | UTF-8 | 2,756 | 3.484375 | 3 | [] | no_license | // Carlos Estrella
#include <iostream>
#include <gmp.h>
#include <gmpxx.h>
#include <ctime>
using std::cout;
void generateRandomNumbers(mpz_t &num1, mpz_t &num2) {
// Generate random state
gmp_randstate_t state;
unsigned long seed = time(NULL);
gmp_randinit_default(state);
gmp_randseed_ui(state, seed);
// Generate two random 4096 bit integers
mpz_urandomb(num1, state, 4096);
mpz_urandomb(num2, state, 4096);
gmp_printf("Random number 1:\n%Zd\n", num1);
gmp_printf("\nRandom number 2:\n%Zd\n\n", num2);
gmp_randclear(state);
} // generateRandomNumbers
void computeGCD(mpz_t &num1, mpz_t&num2, mpz_t &bezout_x, mpz_t &bezout_y) {
mpz_t x, y, zero;
mpz_inits(x, zero, NULL);
mpz_init_set_ui(y, 1);
// Extended Euclidean Algorithm
while (mpz_cmp(num2, zero) != 0) {
mpz_t quotient, remainder, placeholder;
mpz_inits(quotient, remainder, placeholder, NULL);
mpz_tdiv_q(quotient, num1, num2);
mpz_tdiv_r(remainder, num1, num2);
mpz_set(num1, num2);
mpz_set(num2, remainder);
mpz_t temp_x, temp_y;
mpz_init_set(temp_x, x);
mpz_init_set(temp_y, y);
mpz_mul(placeholder, quotient, x);
mpz_sub(placeholder, bezout_x, placeholder);
mpz_set(x, placeholder);
mpz_set(bezout_x, temp_x);
mpz_mul(placeholder, quotient, y);
mpz_sub(placeholder, bezout_y, placeholder);
mpz_set(y, placeholder);
mpz_set(bezout_y, temp_y);
mpz_clears(quotient, remainder, placeholder, temp_x, temp_y, NULL);
} // while
mpz_clears(x, y, zero, NULL);
} // computeGCD
int main(int argc, char *argv[]) {
// Initialize a and b in GCD(a,b)
mpz_t num1, num2;
mpz_inits(num1, num2, NULL);
// Set numbers accordingly
switch (argc) {
case 1:
generateRandomNumbers(num1, num2);
break;
case 3:
mpz_set_str(num1, argv[1], 10);
mpz_set_str(num2, argv[2], 10);
break;
default:
cout << "Usage: " << argv[0] << " [NUM1] [NUM2]\n";
cout << "If input is provided, two numbers are required.\n";
cout << "Otherwise, computes GCD of two random numbers.\n";
mpz_clears(num1, num2, NULL);
exit(0);
} // switch
// Compute GCD using the GMP implementation
mpz_t gmp_gcd_res;
mpz_init(gmp_gcd_res);
mpz_gcd(gmp_gcd_res, num1, num2);
gmp_printf("GMP GCD:\n%Zd\n", gmp_gcd_res);
mpz_clear(gmp_gcd_res);
// Compute GCD using extended euclidean algorithm implementation
mpz_t bezout_x, bezout_y;
mpz_init_set_ui(bezout_x, 1);
mpz_init(bezout_y);
computeGCD(num1, num2, bezout_x, bezout_y);
// Print computed results
gmp_printf("\nComputed GCD:\n%Zd\n", num1);
gmp_printf("\nBezout Coefficient for number 1:\n%Zd\n", bezout_x);
gmp_printf("\nBezout Coefficient for number 2:\n%Zd\n\n", bezout_y);
// Clear memory locations
mpz_clears(num1, num2, bezout_x, bezout_y, NULL);
return 0;
} // main | true |
b3097a886de0763405f6a8cb946885ee6a24fd83 | C++ | andrea-acampora/IoT-Smart-Dam | /src/dam_remotehydrometer/TrackingTask.cpp | UTF-8 | 494 | 2.796875 | 3 | [] | no_license | #include "TrackingTask.h"
TrackingTask::TrackingTask(Hydrometer* hydrometer, WaterLevel* waterLevel){
this->hydrometer = hydrometer;
this->waterLevel = waterLevel;
}
void TrackingTask::init(int period){
Task::init(period);
state = ON;
}
void TrackingTask::tick(){
switch (state)
{
case ON:
waterLevel->setWaterLevel(this->hydrometer->getCurrentWaterLevel());
break;
case OFF:
this->setActive(false);
break;
}
}
| true |
93042d235261441f0dcfdd133010ab6e16dcefd7 | C++ | yeungbri/eau2 | /src/network/queue.h | UTF-8 | 1,767 | 3.4375 | 3 | [] | no_license | /*
* Code is referenced from CS4500 lecture, authored by Prof. Jan Vitek.
*/
// lang::Cpp
#pragma once
#include <vector>
#include <map>
#include "thread.h"
#include "message.h"
/**
* FIFO queue of messages with atomic push and pop
* author: vitekj@me.com
*/
class MessageQueue
{
public:
std::vector<std::shared_ptr<Message>> queue_;
Lock lock_;
MessageQueue() {}
/**
* Pushes message on to queue
*/
void push(std::shared_ptr<Message> msg)
{
lock_.lock();
queue_.push_back(msg);
lock_.unlock();
lock_.notify_all();
}
/**
* Removes and returns the first message in the queue
*/
std::shared_ptr<Message> pop()
{
lock_.lock();
while (queue_.size() == 0)
{
lock_.wait();
}
auto result = queue_.back();
queue_.pop_back();
lock_.unlock();
lock_.notify_all();
return result;
}
/**
* Returns size of queue
*/
size_t size()
{
return queue_.size();
}
/**
* Prints the contents of this queue
*/
void print()
{
for (auto m : queue_)
{
m->print();
}
}
};
/**
* Associates threads to node id's
* author: vitekj@me.com
*/
class ThreadNodeMap
{
public:
std::map<std::string, size_t> map;
Lock lock_;
/** Associates thread with node idx */
void set_u(std::string k, size_t v)
{
lock_.lock();
map.insert_or_assign(k, v);
lock_.unlock();
}
/** Get the node idx associated with thread */
size_t get(std::string k)
{
lock_.lock();
auto search = map.find(k);
if (search != map.end())
{
lock_.unlock();
return search->second;
}
else
{
lock_.unlock();
std::string errmsg = "Cannot get key: ";
errmsg += k;
throw std::runtime_error(errmsg);
}
}
}; | true |
f8b2ea323ad74f14012e68c759910d015674f497 | C++ | Ayushaps1/coding | /c++/built_tree_from_preorder_and_inorder.cpp | UTF-8 | 1,227 | 3.59375 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct node{
int data;
node* left;
node* right;
node(int val){
data=val;
left=NULL;
right=NULL;
}
};
int search(int inorder[],int start,int end,int curr){
for(int i=start;i<=end;i++){
if(inorder[i]==curr){
return i;
}
}
return -1;
}
node* built_tree(int preorder[],int inorder[],int start,int end){
// if(start>end){ //we dont need this but still for saftey we can use this
// return NULL;
// }
static int idx=start;
int curr=preorder[idx];
idx++;
node* Node=new node(curr);
if(start==end){
return Node;
}
int pos=search(inorder,start,end,curr);
Node->left=built_tree(preorder,inorder,start,pos-1);
Node->right=built_tree(preorder,inorder,pos+1,end);
return Node;
}
void inorder_print(node* root){
if(root){
inorder_print(root->left);
cout<<root->data<<" ";
inorder_print(root->right);
}
}
int main(){
int preorder[]={1,2,4,5,3,6,7};
int inorder[]={4,2,5,1,6,3,7};
//buit tree
node* root=built_tree(preorder,inorder,0,6);
inorder_print(root);
return 0;
} | true |
112cf0d402f6105a4acaebf42e00cdd473ce8bc7 | C++ | forspy/share | /2018-7-21 strcpy_test.cpp | WINDOWS-1252 | 219 | 2.84375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char name[20] = "hello";
char cpName[10];//С
//strcpy(cpName, name);
strncpy(cpName, name, 2);
cpName[2] = '\0';
cout << cpName << endl;
} | true |
5df02ba0a570835b7a2275379adcb76f4f4392f1 | C++ | Mouleeswaran/Moulees | /power of 2 or not.cpp | UTF-8 | 457 | 3.59375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class PowerofTwo
{
public:
PowerofTwo(int num)
{
int count;
if(num==0)
{
cout<<"Numbwr is zero";
}
else
while(num!=1)
{
count=0;
if(num%2==0)
{
num=num/2;
count=1;
}
else
{
cout<<"NO";
break;
}
}
if(count==1)
cout<<"YES";
}
};
int main() {
int n;
cout<<"Enter a number\n";
cin>>n;
PowerofTwo p(5);
return 0;
}
| true |
d422d856e70cefc23fbe7f2ab4c41a60d72d5a7b | C++ | Nayaco/OpenGLBoilerplate | /Core/Utility/Random.cpp | UTF-8 | 903 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "Random.hpp"
namespace randomx {
static std::random_device _rand_dev;
float random(float lower_bound, float upper_bound) {
std::mt19937 _mt(_rand_dev());
std::uniform_real_distribution<float> _gen(0.0f, 1.0f);
return _gen(_mt) * (upper_bound - lower_bound) + lower_bound;
}
imap1d rand(int __length) {
std::mt19937 _mt(_rand_dev());
std::uniform_real_distribution<float> _gen(0.0f, 1.0f);
imap1d _res(__length);
for (auto i = 0; i < __length; ++i) {
_res[i] = _gen(_mt);
}
return _res;
}
imap2d rand2(int __width, int __height) {
std::mt19937 _mt(_rand_dev());
std::uniform_real_distribution<float> _gen(0.0f, 1.0f);
imap2d _res(__width);
for (auto i = 0; i < __width; ++i) {
_res[i].reserve(__height);
for(auto j = 0; j < __height; ++j) {
_res[i][j] = _gen(_mt);
}
}
return _res;
}
} | true |
0467ccb6985ffc30f512b91f882d4993d23397f2 | C++ | migashko/faslib-sandbox | /debris/fas/serialization/json/ser/serialize_integer.hpp | UTF-8 | 1,272 | 2.9375 | 3 | [] | no_license | #ifndef FAS_SERIALIZATION_JSON_SERIALIZER_SERIALIZE_INTEGER_HPP
#define FAS_SERIALIZATION_JSON_SERIALIZER_SERIALIZE_INTEGER_HPP
namespace fas { namespace json{
template<typename T>
struct is_signed_integer
{
enum { value = T(-1) < T(1) };
static inline bool less_zero(T v)
{
return value && (v < 0);
}
};
template<typename T>
struct integer_digits
{
enum { result = sizeof(T)*2 + sizeof(T)/2 + sizeof(T)%2 + is_signed_integer<T>::value };
};
template<typename T, typename R>
inline R serialize_integer(T value, R r)
{
typedef /*typename R::value_type*/char value_type;
value_type buffer[integer_digits<T>::result];
register value_type *beg = buffer;
register value_type *end = buffer;
if ( value == 0 )
{
*(end++) = '0';
}
else
{
if ( is_signed_integer<T>::less_zero(value) )
{
*(end++)='-';
++beg;
for( ; value!=0 ; ++end, value/=10)
*end = '0' - value%10;
}
else
{
for( ; value!=0 ; ++end, value/=10)
*end = '0' + value%10;
}
}
for ( register value_type* cur = end ; cur-beg > 1;--cur, ++beg)
{
*beg ^= *(cur-1);
*(cur-1)^=*beg;
*beg^=*(cur-1);
}
for (beg = buffer; r && beg!=end; ++beg)
*(r++)=*beg;
return r;
}
}}
#endif
| true |
612c26c090e7f0ec80546ac731cffe41f3a01f31 | C++ | kkabdol/Cocos_DotPictures | /DotPictures/Classes/Picture.cpp | UTF-8 | 2,540 | 2.546875 | 3 | [] | no_license | //
// Picture.cpp
// DotPictures
//
// Created by Seonghyeon Choe on 1/2/13.
//
//
#include "Picture.h"
using namespace cocos2d;
const unsigned int kMaxSegment = 7;
static Picture s_sharedPicture;
static bool s_bFirstRun = true;
Picture* Picture::sharedPicture(void)
{
if (s_bFirstRun)
{
s_sharedPicture.init();
}
return &s_sharedPicture;
}
bool Picture::init(void)
{
CCArray* pictures = CCArray::createWithContentsOfFile("Pictures.plist");
this->pictureIndex = rand() % pictures->count();
CCDictionary* curPicture = dynamic_cast<CCDictionary*>(pictures->objectAtIndex(this->pictureIndex));
const char* filename = curPicture->valueForKey("file")->getCString();
if ( !CCImage::initWithImageFile(filename)) {
return false;
}
s_bFirstRun = false;
pictures->release();
// max score = sum(4^(n-1)*n)*c n : 1~(maxSegment-1)
this->score = 10000000;
this->minusScorePerPop = 1;
return true;
}
unsigned int Picture::getMaxSegment()
{
return kMaxSegment;
}
unsigned char Picture::getPixelRColor(const cocos2d::CCPoint& point)
{
if (point.x < 0 || point.x >= this->getWidth() ||
point.y < 0 || point.y >= this->getHeight()) {
return 255;
} else {
const unsigned char* data = this->getData();
const int index = point.y*this->getWidth() + point.x;
return data[index*4 + 0];
}
}
unsigned char Picture::getPixelGColor(const cocos2d::CCPoint& point)
{
if (point.x < 0 || point.x >= this->getWidth() ||
point.y < 0 || point.y >= this->getHeight()) {
return 255;
} else {
const unsigned char* data = this->getData();
const int index = point.y*this->getWidth() + point.x;
return data[index*4 + 1];
}
}
unsigned char Picture::getPixelBColor(const cocos2d::CCPoint& point)
{
if (point.x < 0 || point.x >= this->getWidth() ||
point.y < 0 || point.y >= this->getHeight()) {
return 255;
} else {
const unsigned char* data = this->getData();
const int index = point.y*this->getWidth() + point.x;
return data[index*4 + 2];
}
}
void Picture::addPop(unsigned int seg)
{
if (this->score <= 1000) {
return;
}
this->score -= this->minusScorePerPop;
this->score = (this->score > 1000) ? this->score : 1000;
this->minusScorePerPop *= 1.05;
}
long long Picture::getScoreCanGet() {
return this->score;
} | true |
cad4a50f7d20109c22c86fdd0247ded708c376b1 | C++ | saurav-chandra/cpp_test | /assgmnt/4.cpp | UTF-8 | 2,137 | 4.21875 | 4 | [] | no_license | /*
4. Write a C program that uses stack operations to convert a given infix expression into its postfix
Equivalent, Implement the stack using an array.
*/
#include<bits/stdc++.h>
using namespace std;
#define MAX 15
class Stack
{
private:
int top;
public:
void push(char x);
char pop();
void display();
int stackTop();
bool empty();
char arr[MAX];
Stack()
{
top = -1;
}
};
void Stack::push(char x)
{
if(top == MAX)
cout << "Stack Full";
else
arr[++top] = x;
}
char Stack::pop()
{
if(top <= -1)
{
cout << "Stack Empty";
return 0;
}
else
{
int x = arr[top--];
return x;
}
}
void Stack::display()
{
cout << "Postfix expression is : ";
for(int i = 0; i <= top ; i++)
{
cout << arr[i];
}
}
int Stack::stackTop()
{
return arr[top];
}
bool Stack::empty()
{
if(top == -1)
return true;
return false;
}
int priority(char a)
{
int temp;
if (a == '^')
temp = 3;
else if (a == '*' || a == '/')
temp = 2;
else if (a == '+' || a == '-')
temp = 1;
return temp;
}
int main()
{
Stack postfix, operators;
//stack<char> operators;
string infix;
int i;
cout << "Enter an infix expression : ";
getline(cin, infix);
for(i = 0; i < infix.length(); i++)
{
if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/' || infix[i] == '^')
{
while(!operators.empty() && priority(operators.stackTop()) >= priority(infix[i]))
{
postfix.push(operators.stackTop());
operators.pop();
}
operators.push(infix[i]);
}
else
postfix.push(infix[i]);
}
while (!operators.empty())
{
postfix.push(operators.stackTop());
operators.pop();
}
postfix.display();
return 0;
} | true |
9bedc22064ddb3e1e6b9ee8b755ba96de3aaeb00 | C++ | sergey-pashaev/practice | /cpp/hackerrank/src/arrays-left-rotation.cpp | UTF-8 | 1,346 | 4.25 | 4 | [] | no_license | // arrays: left rotation
// A left rotation operation on an array shifts each of the array's
// elements 1 unit to the left. For example, if 2 left rotations are
// performed on array [1, 2, 3, 4, 5], then the array would become [3,
// 4, 5, 1, 2].
// Given an array a of n integers and a number, d, perform d left
// rotations on the array. Return the updated array to be printed as a
// single line of space-separated integers.
// Function Description
// Complete the function rotLeft in the editor below. It should return
// the resulting array of integers.
// rotLeft has the following parameter(s):
// An array of integers a.
// An integer d, the number of rotations.
#include <catch2/catch.hpp>
#include <cassert>
#include <vector>
using namespace std;
vector<int> lrot(const vector<int>& v, int d) {
const std::size_t n = v.size();
assert(d > 0);
assert(d <= n);
vector<int> ret(v);
for (std::size_t i = 0; i < n; ++i) {
ret[(i + n - d) % n] = v[i];
}
return ret;
}
TEST_CASE("arrays: left rotation") {
REQUIRE(lrot({1, 2, 3, 4, 5}, 1) == vector<int>({2, 3, 4, 5, 1}));
REQUIRE(lrot({1, 2, 3, 4, 5}, 2) == vector<int>({3, 4, 5, 1, 2}));
REQUIRE(lrot({1, 2, 3, 4, 5}, 3) == vector<int>({4, 5, 1, 2, 3}));
REQUIRE(lrot({1, 2, 3, 4, 5}, 4) == vector<int>({5, 1, 2, 3, 4}));
}
| true |
e2ab67799eee41e430813a1a3f296ce24a0c3f47 | C++ | romulorafas/pds2_si_ufmg_2019_01 | /Lab 02.04 - Palíndromo/listaencadeada.h | UTF-8 | 1,458 | 3.5 | 4 | [] | no_license | #ifndef LISTAENCADEADA_H_
#define LISTAENCADEADA_H_
struct node_t
{
int elemento;
node_t *proximo;
node_t *anterior;
};
class ListaEncadeada
{
private:
node_t *_inicio_lista;
node_t *_fim_lista;
int _total_elementos;
public:
// *CONSTRUTOR
ListaEncadeada();
// *DESTRUTOR
~ListaEncadeada();
// *MÉTODOS
void insere_elemento(int); // (a) insere_elemento(int). Insere um elemento no fim da lista.
void insere_primeiro(int); // (b) insere_primeiro(int). Insere um elemento no inicio da lista.
int get_iesimo(int); // (c) get_iesimo(int). Retorna um elemento na posição i
int remover_elemento(); // (d) remover_elemento(). Remove um elemento no fim da lista.
int remover_primeiro(); // (e) remover_primeiro(). Remove o primeiro elemento da lista.
void inserir_iesimo(int, int); // (f) inserir_iesimo(int, int). Insere um elemento na posicão i.
int remover_iesimo(int); // (g) remover_iesimo(int). Remove um elemento na posição
int tamanho(); // (h) tamanho(). Retorna o tamanho da lista.
void remove_consecutivos(); // (i) remover elementos consecutivos com um mesmo valor
int k_esimo(bool, int); // (j) encontrar o k-ésimo elemento de uma lista encadeada. Sua funçã deve operar nos dois sentidos. Assuma que true é do início para o fim, false é o contrário.
bool checa_palindromo(); // (k) checar se uma lista duplamente encadeada é um palíndromo.
};
#endif /* LISTAENCADEADA_H_ */ | true |
8b9630b6980cc3e1a2a1db494ee6513211c862c8 | C++ | matthewjmiller1/rpc-transport-tests | /src/rt_client_server/transport.cc | UTF-8 | 946 | 2.703125 | 3 | [
"MIT"
] | permissive | /* First, so it stays self-compiling */
#include "transport.hpp"
#include <sstream>
#include <iostream>
#include <iomanip>
namespace rt {
RcvFn Server::_rcvFn = nullptr;
const uint8_t *
DataBuf::cStrToAddr(const char *cStr)
{
return reinterpret_cast<const uint8_t *>(cStr);
}
std::string
DataBuf::bytesToHex(const uint8_t *buf, size_t len)
{
std::stringstream ss;
ss << "0x" << std::hex << std::setfill('0');
for (auto i = 0U; i < len; ++i) {
ss << std::hex << std::setw(2) << static_cast<int>(buf[i]);
}
return ss.str();
}
Server::Server(std::string address, uint16_t port)
: _address(address), _port(port)
{
}
void
Server::setRcvFn(RcvFn fn)
{
// XXX: make MP safe, if needed.
_rcvFn = fn;
}
RcvFn
Server::getRcvFn()
{
return _rcvFn;
}
Client::Client(std::string serverAddress, uint16_t serverPort)
: _serverAddress(serverAddress), _serverPort(serverPort)
{
}
} // namespace rt
| true |
25a8d37f4fe9e05aa9f2e9b81e17dcb2342bf445 | C++ | vi3tkhi3m/cecs-282 | /Prog6 - MegaWar/Player.cpp | UTF-8 | 476 | 2.984375 | 3 | [] | no_license | #include "Player.h"
Player::Player(const int id)
{
this->id = id;
}
int Player::getId()
{
return id;
}
double Player::getFierceness()
{
double temp = 0.0;
for (auto& it : getPile()) {
temp += it.getValue();
}
if (getPile().empty())
return temp;
return temp / getPileSize();
}
int Player::getAmountOfBattles()
{
return battles;
}
int Player::getAmountOfWins()
{
return wins;
}
void Player::addBattle()
{
battles++;
}
void Player::addWin()
{
wins++;
}
| true |
7b30bf5930fe83000ad28e3de66c7bf15a180722 | C++ | xiaohaowudi/DesignPatterSampleCode | /Iterator/Iterator.cpp | UTF-8 | 396 | 2.625 | 3 | [] | no_license | #include "Iterator.h"
IIterator* CAggregate::get_iterator() {
return new CIterator(this);
}
void CIterator::first() {
m_index = 0;
}
void CIterator::next() {
if (m_index < m_aggregate_ptr->m_data_set.size()) {
m_index++;
}
}
bool CIterator::is_done() {
return m_index == m_aggregate_ptr->m_data_set.size();
}
DATA CIterator::current() {
return m_aggregate_ptr->m_data_set[m_index];
} | true |
9b13512e421d1f9d48aa061110847ef3c88c2f76 | C++ | rajobasu/IOI-Prep | /POI/Seafaring.cpp | UTF-8 | 1,995 | 2.6875 | 3 | [] | no_license | /*
SOLUTION : do a dijkstra from each node and get the shortest even and odd length paths. Check parity with given d.
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <queue>
#include <deque>
#include <iomanip>
#include <cmath>
#include <set>
#include <stack>
#include <map>
#include <unordered_map>
#define FOR(i,n) for(int i=0;i<n;i++)
#define FORE(i,a,b) for(int i=a;i<=b;i++)
#define ll long long
#define ld long double
//#define int short
#define vi vector<int>
#define pb push_back
#define ff first
#define ss second
#define ii pair<int,int>
#define iii pair<ll,ii>
#define pll pair<ll,ll>
#define plll pair<ll,pll>
//#define mp make_pair
#define vv vector
#define endl '\n'
using namespace std;
const int MAXN = 10000 + 5;
const short INF = 15000;
vv<short> g[MAXN]; // 0->n-1 = {node, even}, n->2*n-1 = {node, odd};
short dist[MAXN/2][MAXN];
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,m,k;
cin >> n >> m >> k;
FOR(i,n)FOR(j,2*n)dist[i][j] = INF;
FOR(i,n)dist[i][i] = 0;
FOR(i,m){
int a,b;
cin >> a >> b;
a--;b--;
g[a].pb((short)(b+n));
g[b].pb((short)(a+n));
g[a+n].pb((short)(b));
g[b+n].pb((short)(a));
}
FOR(i,n){
// source is i;
queue<int> q;
q.push(i);
while(!q.empty()){
int node = q.front();q.pop();
for(auto e : g[node]){
if(dist[i][e] <= dist[i][node] + 1)continue;
dist[i][e] = dist[i][node]+1;
q.push(e);
}
}
}
FOR(i,k){
int a,b,c;
cin >> a >> b >> c;
a--;b--;
if(c%2 == 0){
if(dist[a][b] == INF){
cout << "NIE" << endl;
}else if(a == b and g[a].size() == 0){
cout << "NIE" << endl;
}else if(dist[a][b] <= c){
cout << "TAK" << endl;
}else{
cout << "NIE" << endl;
}
}else{
if(dist[a][b+n] == INF){
cout << "NIE" << endl;
}else if(dist[a][b+n] <= c){
cout << "TAK" << endl;
}else{
cout << "NIE" << endl;
}
}
}
return 0;
} | true |
e3fc0cdb41d53a38b97eba6c31df0a973af04484 | C++ | MarcelFagundes/algoritmos-Cpp | /Final/code/finding_the_running_median.cpp | UTF-8 | 6,147 | 3.3125 | 3 | [] | no_license | //Source code do curso Algoritmos com C++ por Fabio Galuppo
//Ministrado em 2021 na Agit - https://www.agit.com.br/cursoalgoritmos.php
//Fabio Galuppo - http://member.acm.org/~fabiogaluppo - fabiogaluppo@acm.org
//Maio 2021
//Problem extract from here: https://www.hackerrank.com/challenges/find-the-running-median/problem
//g++ -O3 finding_the_running_median.cpp -o finding_the_running_median.exe
//cl /Fo.\obj\ /EHsc /O2 finding_the_running_median.cpp /link /out:finding_the_running_median.exe
#include <vector>
#include <memory>
#include <limits>
#include <iostream>
using namespace std;
static const bool RED = true;
static const bool BLACK = false;
struct int_rbnode
{
bool is_red;
std::int32_t value;
size_t size;
std::unique_ptr<int_rbnode> left;
std::unique_ptr<int_rbnode> right;
};
struct llrb
{
llrb() : root(nullptr), count(0)
{
}
void insert(std::int32_t value)
{
root = insert_rec(std::move(root), value);
root->is_red = BLACK;
++count;
}
int_rbnode* top() const
{
return root.get();
}
int_rbnode* kth(size_t index) const
{
return kth_rec(root, index);
}
size_t size() const
{
return count;
}
private:
std::unique_ptr<int_rbnode> insert_rec(std::unique_ptr<int_rbnode> node, std::int32_t value)
{
if (nullptr == node)
{
std::unique_ptr<int_rbnode> new_node{new int_rbnode};
new_node->value = value;
new_node->is_red = RED;
new_node->size = 1;
return new_node;
}
//search insertion point
auto result = value - node->value;
if (result > 0)
{
//to right
node->right = insert_rec(std::move(node->right), value);
}
else //if (result < 0 || result == 0)
{
//to left
node->left = insert_rec(std::move(node->left), value);
}
//update size
node->size = subtree_size(node->right) + subtree_size(node->left) + 1;
//adjust nodes
//left child black, right child red
if(!is_red(node->left) && is_red(node->right))
{
node = rotate_left(std::move(node));
}
//left child red, left grandchild red
if (is_red(node->left) && is_red(node->left->left))
{
node = rotate_right(std::move(node));
}
//left child red, right child red
if (is_red(node->left) && is_red(node->right))
{
flip_colors(node);
}
return node;
}
static bool is_red(const std::unique_ptr<int_rbnode>& node)
{
if (nullptr == node)
return false;
return node->is_red;
};
static size_t subtree_size(const std::unique_ptr<int_rbnode>& node)
{
if (nullptr == node)
return 0;
return node->size;
}
static std::unique_ptr<int_rbnode> rotate_left(std::unique_ptr<int_rbnode> node)
{
//rotate
std::unique_ptr<int_rbnode> temp = std::move(node->right);
node->right = std::move(temp->left);
temp->left = std::move(node);
temp->is_red = temp->left->is_red;
temp->left->is_red = RED;
//update size
temp->size = temp->left->size;
temp->left->size = subtree_size(temp->left->left) + subtree_size(temp->left->right) + 1;
return temp;
}
static std::unique_ptr<int_rbnode> rotate_right(std::unique_ptr<int_rbnode> node)
{
//rotate
std::unique_ptr<int_rbnode> temp = std::move(node->left);
node->left = std::move(temp->right);
temp->right = std::move(node);
temp->is_red = temp->right->is_red;
temp->right->is_red = RED;
//update size
temp->size = temp->right->size;
temp->right->size = subtree_size(temp->right->left) + subtree_size(temp->right->right) + 1;
return temp;
}
static void flip_colors(std::unique_ptr<int_rbnode>& node)
{
node->left->is_red = BLACK;
node->right->is_red = BLACK;
node->is_red = RED;
}
static int_rbnode* kth_rec(const std::unique_ptr<int_rbnode>& node, size_t index)
{
if (nullptr == node)
return nullptr;
size_t rank = subtree_size(node->left) + 1;
if (index == rank)
{
return node.get();
}
else if (index < rank)
{
return kth_rec(node->left, index);
}
else
{
return kth_rec(node->right, index - rank);
}
}
private:
std::unique_ptr<int_rbnode> root;
size_t count;
};
static double compute_median(llrb& t)
{
size_t index = t.size() / 2;
auto* node = t.kth(index + 1);
double median = node->value;
if (!(t.size() & 0x1))
{
node = t.kth(index);
median = (median + node->value) / 2.0;
}
return median;
}
vector<double> running_median(vector<int> a) {
vector<double> medians;
llrb t;
for (int i : a)
{
t.insert(i);
medians.push_back(compute_median(t));
}
return medians;
}
//Test cases:
//6 12 4 5 3 8 7 expected output: 12 8 5 4.5 5 6
//10 1 2 3 4 5 6 7 8 9 10 expected output: 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5
int main()
{
int a_count;
cin >> a_count;
vector<int> a(a_count);
for (int a_itr = 0; a_itr < a_count; a_itr++) {
int a_item;
cin >> a_item;
a[a_itr] = a_item;
}
vector<double> result = running_median(a);
for (int result_itr = 0; result_itr < result.size(); result_itr++) {
cout << result[result_itr];
if (result_itr != result.size() - 1) {
cout << " ";
}
}
cout << "\n";
return 0;
}
| true |
71f10e0ebc23a9e525c17aafa4aa15180518be2d | C++ | biprodas/OJ-Solutions | /UVa/11461 - Square Numbers.cpp | UTF-8 | 381 | 2.796875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int ar[100005];
bool isSquare(int n){
int sq = sqrt(n);
return sq*sq==n;
}
void pre(){
for(int i=1;i<100005;i++){
ar[i]=ar[i-1];
if(isSquare(i)) ar[i]++;
}
}
int main(){
pre();
int a, b;
while(scanf("%d %d", &a, &b)){
if(!a && !b) break;
cout<<ar[b]-ar[a-1]<<endl;
}
}
| true |
141903755aec124406615c76280963e0e0d00e2e | C++ | yurkiss/LogParserCpp | /BaseParsingStrategy.h | UTF-8 | 1,731 | 2.78125 | 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: BaseParsingStrategy.h
* Author: yrid
*
* Created on October 6, 2015, 12:16 PM
*/
#ifndef BASEPARSINGSTRATEGY_H
#define BASEPARSINGSTRATEGY_H
#include <fstream>
class ParsingStrategy
{
public:
ParsingStrategy(){};
virtual ~ParsingStrategy(){};
virtual void parse(std::ifstream* fileStream, const std::streampos fromPos = std::ios::beg, const std::streampos toPos = std::ios::end) =0;
};
class LineParsingStrategy : public ParsingStrategy
{
virtual void parse(std::ifstream* fileStream, const std::streampos fromPos = std::ios::beg, const std::streampos toPos = std::ios::end)
override
{
if(fileStream->is_open())
{
std::streampos fr = fromPos;
if( fr == std::ios::beg )
{
fr = 0;
}
std::streampos to = toPos;
if (to == std::ios::end)
{
fileStream->seekg(0, std::ios::end);
to = fileStream->tellg();
}
}
}
};
class SymbolParsingStrategy : public ParsingStrategy
{
virtual void parse(std::ifstream* fileStream, const std::streampos fromPos = std::ios::beg, const std::streampos toPos = std::ios::end)
override
{
if (fileStream->is_open())
{
std::streampos fr = fromPos;
if (fr == std::ios::beg)
{
fr = 0;
}
std::streampos to = toPos;
if (to == std::ios::end)
{
fileStream->seekg(0, std::ios::end);
to = fileStream->tellg();
}
}
}
};
#endif /* BASEPARSINGSTRATEGY_H */
| true |