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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e78080ef560c2a336b5a6c26e8a782c3d3343c5c | C++ | huipengly/Cpp-Primer | /ch17/ex17.3/query_result_tuple.h | UTF-8 | 981 | 3.015625 | 3 | [
"CC0-1.0"
] | permissive | /**
* @brief QueryResult use tuple
*
* @file query_result_tuple.h
* @author huipengly
* @date 2018-09-22
*/
#ifndef _QUERY_RESULT_H_
#define _QUERY_RESULT_H_
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <tuple>
typedef std::tuple<std::string, std::shared_ptr<std::set<std::vector<int>::size_type>>, std::shared_ptr<std::vector<std::string>>> QueryResult;
std::string makr_plural(size_t ctr, const std::string &word, const std::string &ending)
{
return (ctr > 1) ? word + ending : word;
}
std::ostream& print(std::ostream &os, const QueryResult &qr)
{
os << std::get<0>(qr) << " occurs " << std::get<1>(qr)->size() << " " << makr_plural(std::get<1>(qr)->size(), "time", "s") << std::endl;
for (auto num : *(std::get<1>(qr)))
{
os << "\t(line " << num + 1 << ") " << *(std::get<2>(qr)->begin() + num) << std::endl;
}
return os;
}
#endif | true |
46aab804a38ddf8ca19f281fa0be49341a296be1 | C++ | lidan233/newCpuRender | /util/manipulation.cpp | UTF-8 | 4,600 | 3.171875 | 3 | [] | no_license | //
// Created by 李源 on 2019-11-29.
//
#include "manipulation.h"
Vec3f manipulation::m2v(Matrix41 m)
{
return Vec3f(m[0][0]/m[3][0],m[1][0]/m[3][0],m[2][0]/m[3][0]) ;
}
Matrix41 manipulation::v2m(Vec3f v)
{
Matrix41 m ;
m[0][0] = v[0] ;
m[1][0] = v[1] ;
m[2][0] = v[2] ;
m[3][0] = 1.f ;
return m ;
}
Matrix44 manipulation::viewport(int x,int y,int w,int h,int depth)
{
Matrix44 m = Matrix44::indentity() ;
m[0][3] = x+w/2.f ;
m[1][3] = y+h/2.f ;
m[2][3] = depth/2.f;
m[0][0] = w/2.f ;
m[1][1] = h/2.f ;
m[2][2] = depth/2.f ;
return m ;
}
Matrix44 manipulation::zoom(float factor)
{
Matrix44 Z = Matrix44::indentity() ;
Z[0][0] = Z[1][1] = Z[2][2] = factor ;
return Z ;
}
void manipulation::zoom(Matrix44& mat, float factor)
{
mat[0][0] *= factor ;
mat[1][1] *= factor ;
mat[2][2] *= factor ;
}
Matrix44 manipulation::tranlation(Vec3f v)
{
Matrix44 Tr = Matrix44::indentity();
Tr[0][3] = v.x ;
Tr[1][3] = v.y ;
Tr[2][3] = v.z ;
return Tr ;
}
void manipulation::translation(Matrix44& mat,Vec3f v)
{
mat[0][3] += v.x ;
mat[1][3] += v.y ;
mat[2][3] += v.z ;
}
Matrix44 manipulation::rotation_x(float cosangle,float sinangle)
{
Matrix44 R = Matrix44::indentity() ;
R[1][1] = R[2][2] = cosangle ;
R[1][2] = -sinangle ;
R[2][1] = sinangle ;
return R ;
}
Matrix44 manipulation::rotation_y(float cosangle,float sinangle)
{
Matrix44 R = Matrix44::indentity() ;
R[0][0] = R[2][2] = cosangle ;
R[0][2] = -sinangle ;
R[2][0] = sinangle ;
return R ;
}
Matrix44 manipulation::rotation_z(float cosangle,float sinangle)
{
Matrix44 R = Matrix44::indentity() ;
R[0][0] = R[1][1] = cosangle ;
R[0][1] = -sinangle ;
R[1][0] = sinangle ;
return R ;
}
Matrix44 manipulation::projection(float camera){
Matrix44 R = Matrix44::indentity() ;
R[3][2] = -1.f/float(camera) ;
return R ;
}
Matrix44 manipulation::lookAt(Vec3f eye,Vec3f center ,Vec3f up)
{
Vec3f z = (eye-center).normalize() ;
Vec3f x = cross(up,z).normalize() ;
Vec3f y = cross(z,x).normalize() ;
Matrix44 minv = Matrix44::indentity() ;
for(int i = 0; i< 3;i++)
{
minv[0][i] = x[i] ;
minv[1][i] = y[i] ;
minv[2][i] = z[i] ;
minv[i][3] = -center[i] ;
}
return minv ;
}
Matrix44 manipulation::lookAtMatrix( Vec3f const & eye, Vec3f const & center, Vec3f const & up)
{
Vec3f const f((center - eye).normalize());
Vec3f const s((cross(f, up)).normalize());
Vec3f const u(cross(s, f));
Matrix44 res = Matrix44::indentity() ;
res[0][0] = s.x;
res[1][0] = s.y;
res[2][0] = s.z;
res[0][1] = u.x;
res[1][1] = u.y;
res[2][1] = u.z;
res[0][2] =-f.x;
res[1][2] =-f.y;
res[2][2] =-f.z;
res[3][0] =-(s * eye);
res[3][1] =-(u * eye);
res[3][2] =(f * eye);
return res.transpose();
}
Matrix44 manipulation::rotate(Matrix44 const & m,float angle,Vec3f const & v)
{
float const a = angle;
float const c = cos(a);
float const s = sin(a);
Vec3f axis(v.normalize());
Vec3f temp((float(1) - c) * axis);
Matrix44 Rotate ;
Rotate[0][0] = c + temp[0] * axis[0];
Rotate[0][1] = 0 + temp[0] * axis[1] + s * axis[2];
Rotate[0][2] = 0 + temp[0] * axis[2] - s * axis[1];
Rotate[1][0] = 0 + temp[1] * axis[0] - s * axis[2];
Rotate[1][1] = c + temp[1] * axis[1];
Rotate[1][2] = 0 + temp[1] * axis[2] + s * axis[0];
Rotate[2][0] = 0 + temp[2] * axis[0] + s * axis[1];
Rotate[2][1] = 0 + temp[2] * axis[1] - s * axis[0];
Rotate[2][2] = c + temp[2] * axis[2];
Matrix44 Result;
Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2];
Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2];
Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2];
Result[3] = m[3];
return Result.transpose();
}
Matrix44 manipulation::perspective(float fovy, float aspect, float zNear, float zFar)
{
assert(abs(aspect - std::numeric_limits<float>::epsilon()) > static_cast<float>(0));
float const tanHalfFovy = tan(fovy / static_cast<float>(2));
Matrix44 Result;
Result[0][0] = static_cast<float>(1) / (aspect * tanHalfFovy);
Result[1][1] = static_cast<float>(1) / (tanHalfFovy);
Result[2][2] = - (zFar + zNear) / (zFar - zNear);
Result[2][3] = - static_cast<float>(1);
Result[3][2] = - (static_cast<float>(2) * zFar * zNear) / (zFar - zNear);
return Result.transpose();
}
| true |
1c9ea8fb6feef4a6753f7fccafb6b03a8719b8e0 | C++ | DivyaGoyal28/C_plus_plus | /smartPointer.cpp | UTF-8 | 1,169 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <memory>
using namespace std;
template <typename T> class SP
{
private:
T *ptr;
public:
static int refcount;
SP(T *ptr =NULL):ptr(ptr)
{
refcount++;
}
SP(const SP<T>& sp):ptr(sp.ptr)
{
cout << "copy ctor" <<endl;
refcount++;
}
~SP()
{
cout << "delete ptr" <<endl;
refcount--;
if(refcount==0)
delete ptr;
}
T &operator * ()
{
return *ptr;
}
T &operator -> ()
{
return ptr;
}
SP<T> &operator = (const SP<T> &sp)
{
if(this != &sp)
{
refcount--;
if(refcount==0)
delete ptr;
ptr=sp.ptr;
refcount++;
}
return *this;
}
void fun()
{
cout << "calling fun p=" << *ptr <<endl;
}
};
template <typename T> int SP<T>::refcount=0;
int main()
{
SP<int> p=new int(10);
p.fun();
cout << "count="<< SP<int>::refcount <<endl;
SP<int> q(new int(20)) ;
q.fun();
cout << "count="<< SP<int>::refcount <<endl;
SP<char> q1(new char('d'));
q1.fun();
cout << "count="<< SP<char>::refcount <<endl;
SP<char> q2(new char('d'));
q2.fun();
cout << "count="<< SP<char>::refcount <<endl;
SP<char> q3 = q1;
q3.fun();
cout << "count="<< SP<char>::refcount <<endl;
return 0;
}
| true |
0559c5050f3f8fa373db231d02fceb4abcc04aca | C++ | LiZhenhuan1019/Caculator | /copyable_unique_ptr.h | UTF-8 | 669 | 2.9375 | 3 | [] | no_license | #ifndef COPYABLE_UNIQUE_PTR_H
#define COPYABLE_UNIQUE_PTR_H
#include <c++/bits/unique_ptr.h>
template <typename _Tp, typename _Dp = std::default_delete<_Tp> >
class copyable_unique_ptr:public std::unique_ptr<_Tp,_Dp>
{
public:
copyable_unique_ptr() = default;
using std::unique_ptr<_Tp,_Dp>::unique_ptr;
copyable_unique_ptr(copyable_unique_ptr const&src)
:std::unique_ptr<_Tp,_Dp>(new _Tp(*src))
{}
copyable_unique_ptr(copyable_unique_ptr&&src) = default;
copyable_unique_ptr& operator=(copyable_unique_ptr const&src) = default;
copyable_unique_ptr& operator=(copyable_unique_ptr&&src) = default;
};
#endif // COPYABLE_UNIQUE_PTR_H
| true |
1c58c9258ed2ada09d00e08b149668d21f12cd1a | C++ | Benoit3/Sumd-for-Arduino | /Sumd.ino | UTF-8 | 1,025 | 2.703125 | 3 | [
"MIT"
] | permissive |
#include <ESP8266WiFi.h>
#include "SumdRx.h"
//remote control status
bool failSafe=true;
SumdRx *sumdDecoder;
void setup() {
//Start communication to serial port
Serial.begin(115200);
delay(100);
//Attach SUMD decoder to the serial port
sumdDecoder= new SumdRx();
}
void loop()
{
uint8_t index;
//process sumd input
//due to lead time from previous decoding, buffer may overflow and being corrupted -> reset
sumdDecoder->reset();
while(Serial.available() > 0) sumdDecoder->add(Serial.read());
//display failsafe status on console
if (failSafe && !sumdDecoder->failSafe()) {
failSafe=false;
Serial.println("Reception OK");
}
else if (!failSafe && sumdDecoder->failSafe()) {
failSafe=true;
Serial.println("Reception Lost");
}
//display channel status
if (!sumdDecoder->failSafe()) {
for(index=0;index<sumdDecoder->channelRx;index++) {
Serial.print(sumdDecoder->channel[index]);
Serial.print(" ");
}
Serial.println();
}
delay(100);
}
| true |
da099e21b2488b3e2d0e43ece03a900beacd9ca9 | C++ | ciaranegan/graphics_game | /hud.cpp | UTF-8 | 1,327 | 3 | 3 | [] | no_license | #include "hud.hpp"
HUD::HUD(int gl_width, int gl_height)
{
assert(init_text_rendering ("freemono.png", "freemono.meta", gl_width, gl_height));
}
void HUD::draw(int lives, int level)
{
_lives_id = add_text("Lives Remaining: ", 0.0f, 1.0f, 75.0f, 0.0f, 0.8f, 0.2f, 0.5f);
_level_id = add_text("Level: ", -1.0f, 1.0f, 75.0f, 1.0f, 0.0f, 0.0f, 1.0f);
int a, b;
char lives_str[50];
char level_str[50];
sprintf(lives_str, "Lives Remaining: %d", lives);
sprintf(level_str, "Level: %d", level);
update_text(_lives_id, lives_str);
update_text(_level_id, level_str);
draw_texts();
remove_text();
remove_text();
}
void HUD::startMenu()
{
_menu_id = add_text("Welcome to Bomb Dodger.\n"
"Move the ball to the corner with the arrow in it\n"
"while avoiding the red bombs.\n"
"Arrow keys to move and A&D keys to change camera angle.\n"
"Press Enter to begin",
-0.90f, 0.5f, 50.0f, 1.0f, 1.0f, 1.0f, 1.0f);
draw_texts();
remove_text();
}
void HUD::restartMenu()
{
_menu_id = add_text("Game over...\nPress Enter to restart",
-0.75f, 0.5f, 100.0f, 1.0f, 0.0f, 0.0f, 1.0f);
draw_texts();
remove_text();
}
void HUD::gameWon()
{
_game_won_id = add_text("Congratulations!\nYou Won!\nPress Enter to restart",
-0.75f, 0.5f, 100.0f, 1.0f, 0.0f, 0.0f, 1.0f);
draw_texts();
remove_text();
} | true |
575adc15e0d27a08dc363602de9088145faadb86 | C++ | WankaiLiu/pa3-yil317-wal033 | /Vertex.cpp | UTF-8 | 1,495 | 3.625 | 4 | [] | no_license | #include "Vertex.hpp"
#include <iostream>
// Method implementations here
using namespace std;
Vertex::Vertex(const std::string &name){
this->name = name;
this->visited = 0;
this->distance = 4294967294;
}
//Add a new edge to the vertex.
void Vertex::Addedge(const std::string node,Edge newEdge){
this->edges.insert(make_pair(node,newEdge));
}
//Add a new MST edge to the vertex.
void Vertex::AddMSTedge( Vertex* node,Edge newEdge){
pair <Vertex*, Edge> tempPair = make_pair(node,newEdge);
this->MSTedges.insert(tempPair);
}
//Compute the total cost of adjacent edges.
unsigned int Vertex::GetVertexCost(){
std::unordered_map<std::string, Edge>::iterator it;
Edge edge;
unsigned int totalCost=0;
for(it = edges.begin(); it != edges.end(); it++){
edge=it->second;
totalCost += edge.getCost();
}
return totalCost;
}
//Set the distance.
void Vertex::SetDist(unsigned int distance){
this->distance = distance;
}
//Set the value of visit.
void Vertex::SetVisit(bool visited){
this->visited = visited;
}
//Get the value of visit.
bool Vertex::GetVisit(){
if (this->visited == 0){
return 0;
}
else{
return 1;
}
}
//Get the distance of vertex.
unsigned int Vertex::GetDist(){
return this->distance;
}
//Get the adjacent edge of this vertex.
std::unordered_map<std::string, Edge> Vertex::Getedges(){
return this->edges;
}
//Get the adjacent MST edge of this vertex.
std::unordered_map<Vertex*, Edge> Vertex::GetMSTedges(){
return this->MSTedges;
}
| true |
9664e74e0afb726df344a3d5d066561e9c319ba1 | C++ | SAKET-SK/Semester4-SPPU-Data-Structures-and-Files-Lab | /SeqFile.cpp | UTF-8 | 3,693 | 3.078125 | 3 | [] | no_license | #include<fstream>
#include <iostream>
#include<string.h>
using namespace std;
struct stud
{
int rno;
char nm[10];
}s;
void create()
{
ofstream fout;
int n,i;
fout.open("stud1.txt",ios::out); //fout=write into file
cout<<"\nEnter the Number of record=";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\nEnter roll no & name=";
cin>>s.rno>>s.nm;
fout<<endl<<s.rno<<"\t"<<s.nm;
}
fout.close();
}
void display()
{
ifstream fin;
fin.open("stud1.txt",ios::in); //fin = read from file
while(!fin.eof())
{
fin>>s.rno>>s.nm;
cout<<"\n"<<s.rno<<"\t"<<s.nm;
}
fin.close();
}
void search()
{
ifstream fin;
int fl,key;
cout<<"\nEnter number of element=";
cin>>key;
fin.open("stud1.txt",ios::in); //fin = read from file
while(!fin.eof())
{
fin>>s.rno>>s.nm;
if(s.rno==key)
{
fl=1;
break;
}
}
if(fl==1)
cout<<"\nElement found"<<s.rno<<"\t"<<s.nm;
else
cout<<"\nElement not found";
fin.close();
}
void delete_rec()
{
ifstream fin,fin1;
ofstream fout,fout1;
int key,flag=0;
cout<<"\n Enter the key to be deleted=";
cin>>key;
fin.open("stud1.txt",ios::in);//fin = read from file
fout.open("temp.txt",ios::out);//out = write
while(!fin.eof())
{
fin>>s.rno>>s.nm;
if(key==s.rno)
{
flag=1;
}
else
fout<<endl<<s.rno<<s.nm;
}
fin.close();
fout.close();
fin1.open("temp.txt",ios::in);
fout1.open("stud1.txt",ios::out);
while(!fin1.eof())
{
fin1>>s.rno>>s.nm;
fout1<<endl<<s.rno<<s.nm;
}
fin1.close();
fout1.close();
if(flag!=1)
cout<<"\nRecord Not found!!";
else
display();
}
void update_rec()
{
ifstream fin,fin1;
ofstream fout,fout1;
int key,flag=0;
cout<<"\n Enter the key to be updated=";
cin>>key;
fin.open("stud1.txt",ios::in);//fin = read from file
fout.open("temp.txt",ios::out);//out = write
while(!fin.eof())
{
fin>>s.rno>>s.nm;
if(key==s.rno)
{
flag=1;
cout<<"\nEnter new record(Roll no,Name)=";
cin>>s.rno>>s.nm;
fout<<endl<<s.rno<<s.nm;
}
else
fout<<endl<<s.rno<<s.nm;
}
fin.close();
fout.close();
fin1.open("temp.txt",ios::in);
fout1.open("stud1.txt",ios::out);
while(!fin1.eof())
{
fin1>>s.rno>>s.nm;
fout1<<endl<<s.rno<<s.nm;
}
fin1.close();
fout1.close();
if(flag!=1)
cout<<"\nRecord Not found!!";
else
display();
}
int main()
{
int res;
int ch;
do
{
cout<<"\n1.Create\n2.Dispaly\n3.Search\n4.Delete Record\n5.Update";
cout<<"\nEnter your choice==";
cin>>ch;
switch(ch)
{
case 1:create();
break;
case 2:display();
break;
case 3:search();
break;
case 4:delete_rec();
break;
case 5:update_rec();
break;
}
}while(ch<7);
}
/*
*
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==1
Enter the Number of record=5
Enter roll no & name=1 suchita
Enter roll no & name=2 monika
Enter roll no & name=3 sarika
Enter roll no & name=4 madhuri
Enter roll no & name=5 priyanka
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==2
1 suchita
2 monika
3 sarika
4 madhuri
5 priyanka
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==3
Enter number of element=1
Element found=1 suchita
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==3
Enter number of element=25
Element not found
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==4
Enter the key to be deleted=2
1 suchita
3 sarika
4 madhuri
5 priyanka
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==5
Enter the key to be updated=5
Enter new record(Roll no,Name)51 radhika
1 suchita
3 sarika
4 madhuri
51 radhika
1.Create
2.Dispaly
3.Search
4.Delete Record
5.Update
Enter your choice==7
*
*/
| true |
58ec26af5bfa19683c207977aa8c2402234afe77 | C++ | slallement/domnetwork | /include/Cell.h | UTF-8 | 1,025 | 2.640625 | 3 | [] | no_license | #ifndef CELL_H
#define CELL_H
#include <SFML/Network.hpp>
#include <SFML/Graphics.hpp>
class Gameboard;
sf::Packet& operator>>(sf::Packet& packet, Gameboard& gameboard);
sf::Packet& operator<<(sf::Packet& packet, const Gameboard& gameboard);
class Cell
{
public:
Cell(){};
Cell(float cellradius, sf::Vector2f position, float cellCapacity);
Cell(float cellradius, float posx, float posy, float cellCapacity);
void setOwner(int ownerId);
int getOwner() const;
void update(float dt);
virtual ~Cell();
protected:
float radius;
sf::Vector2f pos;
sf::Uint16 capacity;
sf::Uint8 idOwner;
sf::Uint16 units;
float time;
static const float TSCALE;
private:
friend class Gameboard;
friend class Link;
friend sf::Packet& operator>>(sf::Packet& packet, Gameboard& gameboard);
friend sf::Packet& operator<<(sf::Packet& packet, const Gameboard& gameboard);
};
#endif // CELL_H
| true |
98d7585207bd53319af552bb4c997c717606e9af | C++ | ligi214/2019-2_DS_project | /hw5/algorithms.cpp | UTF-8 | 5,687 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "algorithms.hpp"
using namespace std;
#define WHITE 0
#define GRAY 1
#define BLACK 2
int dfs_time = 0;
void dfs_visit(Adj_Node** adj_list, DFS_Node** vertices, int s){
dfs_time++;
vertices[s]->d_time = dfs_time;
vertices[s]->color = GRAY;
Adj_Node* v = adj_list[s];
while(v){
if(v && vertices[v->vertex]->color==WHITE){
dfs_visit(adj_list, vertices, v->vertex);
vertices[v->vertex]->pred = vertices[s];
}
v = v->next;
}
dfs_time++;
vertices[s]->f_time = dfs_time;
vertices[s]->color = BLACK;
}
void dfs_visualize(DFS_Node** vertices, int v_num){
for(int i=0;i<v_num;i++){
cout << "[Vertex #" << vertices[i]->vertex << "]\t";
cout << "d_time: " << vertices[i]->d_time;
cout << ", f_time: " << vertices[i]->f_time;
if(vertices[i]->pred){
cout << ", predecessor: Vertex #" << vertices[i]->pred->vertex << endl;
}
else{
cout << ", predecessor: NIL" << endl;
}
}
}
void dfs(Adj_Node** adj_list, int v_num, int e_num){
DFS_Node** vertices = new DFS_Node*[v_num];
// Initialize vertices array
for(int i=0;i<v_num;i++){
vertices[i] = (DFS_Node*)(malloc(sizeof(DFS_Node)));
vertices[i]->vertex=i;
vertices[i]->d_time=0;
vertices[i]->f_time=0;
vertices[i]->color=WHITE;
vertices[i]->pred=NULL;
}
// Drive DFS operation
for(int i=0;i<v_num;i++){
if(vertices[i]->color==WHITE){
dfs_visit(adj_list, vertices, i);
}
}
dfs_time = 0;
dfs_visualize(vertices, v_num);
cout << endl;
}
void bfs_visit(Adj_Node** adj_list, BFS_Node** vertices, int v_num, int s){
BFS_Node_Queue queue = BFS_Node_Queue(v_num*2);
vertices[s]->d = 0;
vertices[s]->color = GRAY;
queue.enqueue(vertices[s]);
while(!queue.isEmpty()){
BFS_Node* u = queue.dequeue();
vertices[u->vertex]->color = BLACK;
Adj_Node* v = adj_list[u->vertex];
while(v){
if(v && vertices[v->vertex]->color==WHITE){
vertices[v->vertex]->color = GRAY;
vertices[v->vertex]->pred = vertices[u->vertex];
vertices[v->vertex]->d = vertices[u->vertex]->d + 1;
queue.enqueue(vertices[v->vertex]);
}
v = v->next;
}
}
}
void bfs_visualize(BFS_Node** vertices, int v_num){
for(int i=0;i<v_num;i++){
cout << "[Vertex #" << vertices[i]->vertex << "]\t";
cout << "d: " << vertices[i]->d;
if(vertices[i]->pred){
cout << ", predecessor: Vertex #" << vertices[i]->pred->vertex << endl;
}
else{
cout << ", predecessor: NIL" << endl;
}
}
}
void bfs(Adj_Node** adj_list, int v_num, int e_num, int s){
BFS_Node** vertices = new BFS_Node*[v_num];
for(int i=0;i<v_num;i++){
vertices[i] = (BFS_Node*)(malloc(sizeof(BFS_Node)));
vertices[i]->vertex = i;
vertices[i]->d = -1;
vertices[i]->color = WHITE;
vertices[i]->pred = NULL;
}
bfs_visit(adj_list, vertices, v_num, s);
bfs_visualize(vertices, v_num);
cout << endl;
}
void prim_visualize(MST_Node** vertices, int v_num){
int total_key = 0;
for(int i=0;i<v_num;i++){
cout << "[Vertex #" << vertices[i]->vertex << "]\t";
cout << "key: " << vertices[i]->key;
total_key += vertices[i]->key;
if(vertices[i]->pred){
cout << ", predecessor: Vertex #" << vertices[i]->pred->vertex << endl;
}
else{
cout << ", predecessor: NIL" << endl;
}
}
cout << "Total key : " << total_key << endl;
}
void prim(Adj_Node** adj_list, int v_num, int e_num){
MST_Node** vertices = new MST_Node*[v_num];
for(int i=0;i<v_num;i++){
vertices[i] = (MST_Node*)(malloc(sizeof(MST_Node)));
vertices[i]->vertex = i;
vertices[i]->key = INF;
vertices[i]->pred = NULL;
}
bool in_tv[v_num];
for(int i=0;i<v_num;i++){
in_tv[i] = false;
}
int selected = 0;
vertices[selected]->key = 0;
int i; // number of vertices in TV
for(i=0;i<v_num;i++){
int min_vertex = v_num;
int min_value = INF;
for(int j=0;j<v_num;j++){
if(vertices[j]->key < min_value && !in_tv[j]){
min_vertex = j;
min_value = vertices[j]->key;
}
}
selected = min_vertex; // Add vertex 0 at first iteration
if(selected >= v_num && min_value == INF){ // no such edge
break;
}
in_tv[selected] = true; // add selected vertex to TV
Adj_Node* v = adj_list[selected];
while(v){
if(v->weight < vertices[v->vertex]->key && !in_tv[v->vertex]){
vertices[v->vertex]->key = v->weight;
vertices[v->vertex]->pred = vertices[selected];
}
v = v->next;
}
}
if(i<v_num) cout << "no spanning tree" << endl << endl;
else{
prim_visualize(vertices, v_num);
cout << endl;
}
}
void dijkstra_visualize(int dist[], int pred[], int v_num, int source){
string s = "";
for(int i=0;i<v_num;i++){
cout << "[Vertex #" << i << "]\t";
if(source == i){
cout << "Source vertex, Length of the path: 0" << endl;
}
else if(pred[i] >= 0){
cout << "Shortest path: ";
int temp = i;
while(temp!=source){
s = "-" + to_string(temp) + s;
temp = pred[temp];
}
s = to_string(source) + s;
cout << s;
cout << ", Length of the path: " << dist[i] << endl;
s = "";
}
else{
cout << "No path exists" << endl;
}
}
cout << endl;
}
void dijkstra(int** length, int v_num, int e_num, int source){
int dist[v_num];
int pred[v_num];
bool s[v_num];
for(int i=0;i<v_num;i++){
dist[i] = INF;
pred[i] = -1;
s[i] = false;
}
dist[source] = 0;
int u;
int min_value = INF;
for(int i=0;i<v_num;i++){
min_value = INF;
// choose(n)
for(int j=0;j<v_num;j++){
if(dist[j]<min_value && !s[j]){
min_value = dist[j];
u = j;
}
}
s[u]=true;
for(int w=0;w<v_num;w++){
if(!s[w] && length[u][w]<INF && dist[u]+length[u][w] < dist[w]){
dist[w] = dist[u]+length[u][w];
pred[w] = u;
}
}
}
dijkstra_visualize(dist, pred, v_num, source);
}
| true |
c0409c021bc81e4048acbd76cb1a3d8b7f6f5d0d | C++ | pareddy113/Vehicle-Inventory-System | /src/FileHandle.cpp | UTF-8 | 1,543 | 2.953125 | 3 | [] | no_license |
#include "FileHandle.h"
void FileHandle::writeFile(int id,Car& car){
ofstream myfile;
switch(id){
case 1:
myfile.open("1.txt");
myfile<<car.id()<<endl<<car.make()<<endl<<car.model()<<endl<<car.year()<<endl<<car.date()<<endl<<car.cost()<<endl<<car.picture();
myfile.close();
break;
case 2:
myfile.open("2.txt");
myfile<<car.id()<<endl<<car.make()<<endl<<car.model()<<endl<<car.year()<<endl<<car.date()<<endl<<car.cost()<<endl<<car.picture();
myfile.close();
break;
case 3:
myfile.open("3.txt");
myfile<<car.id()<<endl<<car.make()<<endl<<car.model()<<endl<<car.year()<<endl<<car.date()<<endl<<car.cost()<<endl<<car.picture();
myfile.close();
break;
case 4:
myfile.open("4.txt");
myfile<<car.id()<<endl<<car.make()<<endl<<car.model()<<endl<<car.year()<<endl<<car.date()<<endl<<car.cost()<<endl<<car.picture();
myfile.close();
break;
case 5:
myfile.open("5.txt");
myfile<<car.id()<<endl<<car.make()<<endl<<car.model()<<endl<<car.year()<<endl<<car.date()<<endl<<car.cost()<<endl<<car.picture();
myfile.close();
break;
}
}
Car* FileHandle::readFile(int id,Car& car){
string line;
string strarray[7];
int i=0;
string str=to_string(id);
ifstream myfile (str+".txt");
if(myfile.is_open()){
for( line; getline( myfile, line);)
{
strarray[i]=line;
i++;
}
car.id(stoi(strarray[0]));
car.make(strarray[1]);
car.model(strarray[2]);
car.year(stoi(strarray[3]));
car.date(strarray[4]);
car.cost(stoi(strarray[5]));
car.picture(strarray[6]);
return &car;
}
myfile.close();
}
| true |
88bbef02e24010727576f7745deb3e3150f4c9f7 | C++ | tenquitran/GreenTopazTracer | /GreenTopazTracer/GreenTopazTracer.h | UTF-8 | 2,555 | 2.84375 | 3 | [] | no_license | #pragma once
#include "ImagePlane.h"
namespace GreenTopazTracerApp
{
// The ray tracer.
class GreenTopazTracer
{
public:
// Parameters: imageWidth - width of the image to trace (in pixels);
// imageHeight - height of the image to trace (in pixels);
// threadCount - number of threads to perform ray tracing;
// maxTracingSteps - maximum number of steps for ray tracing.
// Throws: Exception, std::bad_alloc
GreenTopazTracer(int imageWidth, int imageHeight, unsigned int threadCount, int maxTracingSteps);
virtual ~GreenTopazTracer();
// Start ray tracing the scene.
void traceScene();
// Prepare the image data for usage by the WIC image exporter.
// Parameters: stride - stride value for the resulting image;
// bufferSize - size of the returned data buffer, in bytes.
// Returns: the image data buffer.
std::unique_ptr<BYTE[]> exportForWicImageProcessor(UINT& stride, UINT& bufferSize) const
{
return m_imagePlane.exportForWicImageProcessor(stride, bufferSize);
}
// Get raw image data (BGR format).
// Parameters: size - number of elements.
std::unique_ptr<COLORREF[]> getRawDataBGR(size_t& size) const
{
return m_imagePlane.getRawDataBGR(size);
}
int getHorizontalResolution() const
{
return m_imagePlane.getHorizontalResolution();
}
int getVerticalResolution() const
{
return m_imagePlane.getVerticalResolution();
}
const unsigned int getThreadCount() const
{
return ThreadCount;
}
private:
GreenTopazTracer(const GreenTopazTracer&) = delete;
GreenTopazTracer& operator=(const GreenTopazTracer&) = delete;
static DWORD WINAPI threadProc(LPVOID pArg);
DWORD threadProc();
// Trace the specified ray.
// Parameters: ray - ray to trace;
// steps - number of tracing steps already performed.
Color traceRay(const Ray& ray, int steps) const;
public:
std::vector<CHandle> m_threads;
private:
const int HorizontalResolution = {};
const int VerticalResolution = {};
// Number of pixels in the image.
const long PixelCount = {};
// Number of threads to perform ray tracing.
const unsigned int ThreadCount = {};
// Maximum number of steps for ray tracing.
const int MaxTracingSteps = {};
ImagePlane m_imagePlane;
Scene m_scene;
// Used to get the next pixel to process.
PixelCounter m_pixelCounter;
// Tone mapping object (empty if we are not using HDR).
std::unique_ptr<ToneMapper> m_spToneMapper;
};
}
| true |
50db3eeec44a7fb9c413cbd4a335ee6354f80992 | C++ | 15831944/miniSQL | /miniSQL/miniSQL/index_list.h | UTF-8 | 1,085 | 2.625 | 3 | [] | no_license | #pragma once
#include <map>
#include "typedef.h"
#include "element.h"
#include <string>
#include <vector>
using namespace std;
class index_list
{
public:
index_list();
~index_list();
NODE_TYPE m_node_type;
int m_parent_offset;
int m_next_offset;
ATTRIBUTE_TYPE m_attr_type;
int m_char_num;
map<string, int> m_list_char;
map<int, int> m_list_int;
map<float, int> m_list_float;
string m_index_name;
int offset;
void clear();
int size();
bool is_full();
void insert(element e, int offset);
void del(element e);
void del_char(string s);
void del_int(int i);
void del_float(float f);
index_list right_part(int disk_offset);
int find_offset(element e);
int find_offset(string s);
int find_offset(int i);
int find_offset(float f);
int find_offset_for_record(element e);
int find_offset_for_record(string s);
int find_offset_for_record(int i);
int find_offset_for_record(float f);
vector<int> get_sons_offset();
vector<int> get_sons_offset_char();
vector<int> get_sons_offset_int();
vector<int> get_sons_offset_float();
element first();
};
| true |
e7a65013bdf0226b76dea17b73919cec87577a51 | C++ | jungvely97/vending_machine1 | /widget.cpp | UTF-8 | 1,445 | 2.78125 | 3 | [] | no_license | #include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
int money = 0;
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::change_money(int n){
money += n;
ui->lcdNumber->display(money);
button();
}
void Widget::on_pb10_clicked()
{
change_money(10);
}
void Widget::on_pb50_clicked()
{
change_money(50);
}
void Widget::on_pb100_clicked()
{
change_money(100);
}
void Widget::on_pb500_clicked()
{
change_money(500);
}
void Widget::on_pbCoffee_clicked()
{
change_money(-100);
}
void Widget::on_pbTea_clicked()
{
change_money(-150);
}
void Widget::on_pbCoke_clicked()
{
change_money(-200);
}
void Widget::on_pbReset_clicked()
{
int num10 = 0, num50 = 0, num100 = 0, num500 = 0;
if(money >= 500) num500 = money / 500;
money %= 500;
if(money >= 100) num100 = money / 100;
money %= 100;
if(money >= 50) num50 = money / 50;
money %= 50;
if(money >= 10) num10 = money / 10;
money %= 10;
ui->lcdNumber->display(money);
QMessageBox msg;
QString str = QString("500: %1, 100: %2, 50: %3, 10: %4").arg(num500).arg(num100).arg(num50).arg(num10);
msg.information(nullptr,"change", str);
}
void Widget::button(){
ui->pbCoffee->setEnabled(money >= 100);
ui->pbTea->setEnabled(money >= 150);
ui->pbCoke->setEnabled(money >= 200);
}
| true |
6aec43a4a3979c3f218ec982d5f80875f54230e7 | C++ | allscale/allscale_compiler | /test/data_requirements/matrix_transpose/matrix_transpose.cpp | UTF-8 | 870 | 2.921875 | 3 | [] | no_license |
#include <chrono>
#include <allscale/api/user/algorithm/pfor.h>
#include <allscale/api/user/data/static_grid.h>
const int N = 1000;
using namespace allscale::api::user::data;
using namespace allscale::api::user::algorithm;
using Element = double;
using Matrix = StaticGrid<Element,N,N>;
using Point = typename Matrix::coordinate_type;
using myClock = std::chrono::high_resolution_clock;
int main() {
// create two matrixes
Matrix A;
Matrix B;
auto start = myClock::now();
// perform transformation
pfor(A.size(),[&](const Point& p) {
B[{p.y,p.x}] = A[p];
A[p]++;
});
auto end = myClock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cerr << "Completed in " << ms << "ms\n";
std::cerr << "Throughput: " << ((sizeof(Element)*N*N)/(double)ms/(1024*1024)) << "MiB/s\n";
return EXIT_SUCCESS;
}
| true |
bd116c9298e136ebcae44f5b5749c06b63099f80 | C++ | eujuu/Algorithm | /baekjoon/백준 2522 별 찍기 - 12.cpp | UTF-8 | 390 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int k = n - i; k > 0; k--)
cout << " ";
for (int s = 0; s < i; s++)
cout << "*";
cout << "\n";
}
for (int i = 1; i < n; i++) {
for (int s = 0; s < i; s++)
cout << " ";
for (int k = n - i; k > 0; k--)
cout << "*";
cout << "\n";
}
} | true |
2abf2f8770e7ce2aff68f3089341604bfdce2dda | C++ | korslund/UnpackCpp | /zip/tests/zipfile_test.cpp | UTF-8 | 1,087 | 2.78125 | 3 | [] | no_license | #include "zip/zipfile.hpp"
#include <mangle/stream/servers/file_stream.hpp>
#include <iostream>
#include "misc/dirwriter.hpp"
using namespace std;
using namespace UnpackCpp;
using namespace Mangle::Stream;
int main(int argc, char **argv)
{
ZipFile zip;
std::string file = "test.zip";
std::string where = "";
if(argc >= 2) file = argv[1];
if(argc >= 3) where = argv[2];
cout << "Reading " << file << endl;
try
{
zip.openZipArchive(FileStream::Open(file));
if(where != "")
{
DirWriter dir(where);
cout << " Unpacking to " << where << ":\n";
for(int i=0; i<zip.files.size(); i++)
{
const ZipFile::File &f = zip.files[i];
cout << " " << f.name << " " << f.comp << "=>" << f.size;
StreamPtr out = dir.open(f.name);
if(out) zip.unpackFile(i, out);
else cout << " (directory)";
cout << endl;
}
}
}
catch(exception &e)
{
cout << "\nERROR: " << e.what() << endl;
}
return 0;
}
| true |
b53919714a721894142c2f3957956cdbb42da4c1 | C++ | Esme01/C-codingPractise | /build/array/VerticalQuestion.cpp | UTF-8 | 1,305 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
using namespace std;
int main()
{
int i,ok,abc,de,x,y,z,count=0;
char s[20],buf[99];
scanf("%s",s);//输入的字符串前面不用加定位符,与输入数字不同
for (abc =111; abc <= 999; abc++)
{
/* code */
for ( de = 11; de <= 99; de++)
{
/* code */
x=abc*(de%10);
y=abc*(de/10);
z=abc*de;
sprintf(buf,"%d%d%d%d%d",abc,de,x,y,z);
//把信息输出到字符串
//相当于把这五个数合并变成一个字符串!
//之后只要检测这个字符串中每个字符是否在集合里面即可
ok=1;//判断变量
for(i=0;i<strlen(buf);i++)
if (strchr(s,buf[i])==NULL)
{
/* code */
ok=0;
}
if (ok)
{
/* code */
printf("<%d>\n",++count);
printf("%5d\nX%4d\n-----\n%5d\n%4d\n-----\n%5d\n\n",abc,de,x,y,z);
//用%4d的方法排列数的位置!妙!
}
}
}
printf("The number of solutions= %d\n",count);
return 0;
}
| true |
0d088b15e61ca4e60346c0f956d677ca08acb897 | C++ | snulion-study/algorithm-int | /sangwon/ch25_DisjointSet/25-3.cpp | UTF-8 | 803 | 3.125 | 3 | [] | no_license | // 25.3 에디터 전쟁 문제를 해결하는 상호 배타적 집합의 구현
#include <vector>
using namespace std;
struct BipartiteUnionFind {
vector<int> parent, rank, enemy, size;
BipartiteUnionFind(int n): parent(n), rank(n, 0), enemy(n, -1), size(n, 1) {
for(int i = 0; i < n; ++i) parent[i] = i;
}
int find(int u) {
if(parent[u] == u) return u;
return parent[u] = find(parent[u]);
}
int merge(int u, int v) {
if(u == -1 || v == -1) return max(u, v);
u = find(u); v = find(v);
if(u == v) return u;
if(rank[u] > rank[v]) swap(u, v);
if(rank[u] == rank[v]) rank[v]++;
parent[u] = v;
size[v] += size[u];
return v;
}
bool dis(int u, int v) {}
bool ack(int u, int v) {}
}; | true |
8f67c480ce1602f9bb87abd916988f4b7a8f28fa | C++ | shilpiroy98/SDL-ConnectFour | /SDL_tutorial/GameManager.cpp | UTF-8 | 1,014 | 2.890625 | 3 | [] | no_license | //
// GameManager.cpp
// SDL_tutorial
//
// Created by Shilpi Roy on 15/12/20.
// Copyright © 2020 Shilpi Roy. All rights reserved.
//
#include "GameManager.hpp"
GameManager::GameManager(SDL_Renderer* renderer) {
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
board = std::make_unique<Board>(renderer);
}
GameManager::~GameManager() {
}
void GameManager::displayBoard(SDL_Renderer* const renderer, int const* turn) const {
board->display(renderer, turn);
}
bool GameManager::handleBoardClickEvent(SDL_Renderer* const renderer, int const* x, int const* y, int const* turn) const {
return board->handleClickEvent(renderer, x, y, turn);
}
bool GameManager::handleHoverEvent(SDL_Renderer* const renderer, int const* x, int const* y, int const* turn) const {
return board->handleHoverEvent(renderer, x, y, turn);
}
bool GameManager::checkWinState(SDL_Renderer* const renderer, int const* turn) const {
return board->checkWinState(renderer, turn);
}
| true |
93bf036665f0ed055817f0c62cdf05569a7dc23a | C++ | 0xC4m3l-jiang/TheWayToHeaven_sakura | /llvm/asst2/src/liveness.cpp | UTF-8 | 5,271 | 2.71875 | 3 | [] | no_license | #include "framework.h"
namespace {
// 声明一个Variable类,便于打印
// 直接用Value* 输出会输出地址
class Variable
{
private:
const Value * _val;
public:
Variable(const Value * val) : _val(val) {}
bool operator==(const Variable & val) const
{ return _val == val.getValue(); }
const Value* getValue() const { return _val; }
friend raw_ostream & operator<<(raw_ostream & outs, const Variable & val);
};
raw_ostream & operator<<(raw_ostream & outs, const Variable & var)
{
outs << "["; var._val->printAsOperand(outs, false); outs << "]";
return outs;
}
} // namespace anonymous
// unordered_set需要自己定义一个hash函数
namespace std{
// Construct a hash code for 'Variable'.
template <>
struct hash <Variable> {
std::size_t operator()(const Variable &var) const {
std::hash <const Value *> value_ptr_hasher;
std::size_t value_hash = value_ptr_hasher((var.getValue()));
return value_hash;
}
};
};
namespace {
/// @todo Implement @c Liveness using the @c dfa::Framework interface.
class Liveness final : public dfa::Framework < Variable,
dfa::Direction::Backward >
{
protected:
virtual BitVector IC() const override
{
//(空集)
return BitVector(_domain.size(), false);
}
virtual BitVector BC() const override
{
// (空集)
return BitVector(_domain.size(), false);
}
// 进行并集操作
virtual BitVector MeetOp(const BasicBlock & bb) const override
{
// 初始化 result
BitVector result(_domain.size(), false);
for(const BasicBlock* block : successors(&bb))
{
// 通常来讲,所有后驱基础块的第一条 Instruction 的IN集合就是当前基础块的OUT集
const Instruction& first_inst_in_block = block->front();
BitVector curr_bv = _inst_bv_map.at(&first_inst_in_block);
// 但这里要对含有phi指令的基础块作特殊处理
for(auto phi_iter = block->phis().begin();
phi_iter != block->phis().end(); phi_iter++)
{
const PHINode & phi_inst = *phi_iter;
for(auto phi_inst_iter = phi_inst.block_begin();
phi_inst_iter != phi_inst.block_end(); phi_inst_iter++)
{
// 获取PHI指令中的各个前驱基础块
BasicBlock* const &curr_bb = *phi_inst_iter;
// 如果当前前驱基础块不是现在的基础块
if(curr_bb != &bb)
{
// 得到该基本块中定义的变量
const Value* curr_val = phi_inst.getIncomingValueForBlock(curr_bb);
// 如果当前值在 domain 中存在(避免常量等) 需要修改为 false
int idx = getVN(Variable(curr_val));
if(idx != -1)
{
// 将临时变量中对应变量的bit设置为false
assert(curr_bv[idx] = true);
curr_bv[idx] = false;
}
}
}
}
// 与临时变量做集合并操作
result |= curr_bv;
}
return result;
}
// 判断是否 被 kill 等。
virtual bool TransferFunc(const Instruction & inst,
const BitVector & ibv,
BitVector & obv) override
{
BitVector new_obv = ibv;
// use操作
for(auto iter = inst.op_begin(); iter != inst.op_end(); iter++)
{
const Value* val = dyn_cast<Value>(*iter);
assert(val != NULL);
// 如果当前Variable存在于domain
if(_domain.find(val) != _domain.end())
new_obv[getVN(val)] = true;
}
// def操作。不是所有的指令都会定值,例如ret,所以要设置条件判断
if(getVN(&inst) != -1)
new_obv[getVN(&inst)] = false;
bool hasChanged = new_obv != obv;
obv = new_obv;
return hasChanged;
}
virtual void InitializeDomainFromInstruction(const Instruction & inst) override
{
for(auto iter = inst.op_begin(); iter != inst.op_end(); iter++)
if (isa < Instruction > (*iter) || isa < Argument > (*iter))
_domain.emplace(Variable(*iter));
}
public:
static char ID;
Liveness() : dfa::Framework < domain_element_t,
direction_c > (ID) {}
virtual ~Liveness() override {}
};
char Liveness::ID = 1;
RegisterPass < Liveness > Y ("liveness", "Liveness");
} // namespace anonymous | true |
c095beb988d88043ca9efeaa766e08d107403957 | C++ | hkt0504/Android-Card-Game | /Trix/src/CardGame/Classes/engine/level/ComplexLevel.cpp | UTF-8 | 12,474 | 2.640625 | 3 | [] | no_license | #include "ComplexLevel.h"
#include "Hand.h"
#include "Player.h"
USING_NS_CC;
ComplexLevel::ComplexLevel()
{
playedCount = 0;
duplicateK = INVALID;
duplicateQ[0] = INVALID;
duplicateQ[1] = INVALID;
duplicateQ[2] = INVALID;
duplicateQ[3] = INVALID;
kingPlayed = false;
queenPlayed = 0;
}
ComplexLevel::~ComplexLevel()
{
}
/** return is finished and calculate score */
bool ComplexLevel::evaluateScore(int turn)
{
CCLog("Call ComplexLevel::evaluateScore");
Card card = table->playedCards[table->closedCardCount];
Suit suitLed = card.suit;
int highest_index = 0;
int highest_value = 0;
int qSuit = 0;
int diamond = 0;
int kingIndex = -1;
for (int i = 0; i < 4; i++) {
card = table->playedCards[i + table->closedCardCount];
if (card.suit == DIAMOND) {
diamond ++;
}
if (card.value == CARD_Q) {
SET_BIT(qSuit, card.suit);
SET_BIT(queenPlayed, card.suit);
}
if (card.isHK()) {
kingIndex = i;
kingPlayed = true;
}
if (card.suit == suitLed && card.value > highest_value) {
highest_value = card.value;
highest_index = i;
}
}
int winner = (turn + highest_index) % PLAYER_NUM;
// lotosh score.
players[winner]->score -= SCORE_LOTOSH;
players[winner]->eatLotosh ++;
// diamond score.
if (diamond > 0) { //diamond is played
players[winner]->score -= diamond * SCORE_DIAMOND;
players[winner]->eatDiamond += diamond;
}
// queen score
if (qSuit != 0) { //queen is played
Suit suits[4] = {HEART, CLOVER, DIAMOND, SPADE};
int dups[4] = {DUP_H_Q, DUP_C_Q, DUP_D_Q, DUP_S_Q};
for (int i = 0; i < 4; i++) {
if (HAS_BIT(qSuit, suits[i])) {
players[winner]->score -= SCORE_QUEEN;
SET_BIT(players[winner]->eatKQ, dups[i]);
if (duplicateQ[i] != INVALID) {
REMOVE_BIT(players[duplicateQ[i]]->duplicates, dups[i]);
if (partner) {
players[winner]->score -= SCORE_QUEEN;
if (duplicateQ[i] == winner || duplicateQ[i] == ((winner + 2) % PLAYER_NUM)) {
players[(duplicateQ[i] + 1) % PLAYER_NUM]->score += SCORE_QUEEN;
} else {
players[duplicateQ[i]]->score += SCORE_QUEEN;
}
} else {
if (winner != duplicateQ[i]) {
players[winner]->score -= SCORE_QUEEN;
players[duplicateQ[i]]->score += SCORE_QUEEN;
}
}
}
}
}
}
// H-King score
if (kingIndex != -1) { //King is played
players[winner]->score -= SCORE_KING;
SET_BIT(players[winner]->eatKQ, DUP_K);
if (duplicateK != INVALID) {
REMOVE_BIT(players[duplicateK]->duplicates, DUP_K);
if (partner) {
players[winner]->score -= SCORE_KING;
if (duplicateK == winner || duplicateK == ((winner + 2) % PLAYER_NUM)) {
players[(duplicateK + 1) % PLAYER_NUM]->score += SCORE_KING;
} else {
players[duplicateK]->score += SCORE_KING;
}
} else {
if (winner != duplicateK) {
players[winner]->score -= SCORE_KING;
players[duplicateK]->score += SCORE_KING;
}
}
}
}
playedCount ++;
if (playedCount == PLAYER_CARD_NUM) {
return true;
}
return false;
}
bool ComplexLevel::getDuplicateList(int player, int& duplicates)
{
CCLog("Call ComplexLevel::getDuplicateList");
Level::getDuplicateList(player, duplicates);
bool result = false;
Hand *hand = players[player]->hand;
if (hand->findCard(HEART, CARD_K) != INVALID) {
SET_BIT(duplicates, DUP_K);
result = true;
}
if (hand->findCard(HEART, CARD_Q) != INVALID) {
SET_BIT(duplicates, DUP_H_Q);
result = true;
}
if (hand->findCard(CLOVER, CARD_Q) != INVALID) {
SET_BIT(duplicates, DUP_C_Q);
result = true;
}
if (hand->findCard(DIAMOND, CARD_Q) != INVALID) {
SET_BIT(duplicates, DUP_D_Q);
result = true;
}
if (hand->findCard(SPADE, CARD_Q) != INVALID) {
SET_BIT(duplicates, DUP_S_Q);
result = true;
}
return result;
}
void ComplexLevel::setDuplicate(int player, int duplicates)
{
CCLog("Call ComplexLevel::setDuplicate");
if (HAS_BIT(duplicates, DUP_K)) {
duplicateK = player;
}
int flags[4] = { DUP_H_Q, DUP_C_Q, DUP_D_Q, DUP_S_Q };
for (int i = 0; i < 4; i++) {
if (HAS_BIT(duplicates, flags[i])) {
duplicateQ[i] = player;
}
}
}
bool ComplexLevel::thinkDuplicate(int player, int& duplicates)
{
CCLog("Call ComplexLevel::thinkDuplicate");
Level::thinkDuplicate(player, duplicates);
bool result = false;
Hand *hand = players[player]->hand;
if (hand->findCard(HEART, CARD_K) != INVALID && hand->countSuit(HEART) >= 5) {
SET_BIT(duplicates, DUP_K);
result = true;
}
if (hand->findCard(HEART, CARD_Q) != INVALID && hand->countSuit(HEART) >= 5) {
SET_BIT(duplicates, DUP_H_Q);
result = true;
}
if (hand->findCard(CLOVER, CARD_Q) != INVALID && hand->countSuit(CLOVER) >= 5) {
SET_BIT(duplicates, DUP_C_Q);
result = true;
}
if (hand->findCard(DIAMOND, CARD_Q) != INVALID && hand->countSuit(DIAMOND) >= 5) {
SET_BIT(duplicates, DUP_D_Q);
result = true;
}
if (hand->findCard(SPADE, CARD_Q) != INVALID && hand->countSuit(SPADE) >= 5) {
SET_BIT(duplicates, DUP_S_Q);
result = true;
}
return result;
}
Card ComplexLevel::thinkCardInSuit(Hand *hand, Suit suit, int turn)
{
CCLog("Call ComplexLevel::thinkCardInSuit");
Card card;
card.suit = suit;
int player = INVALID;
int highestOnTable = table->highestCardInTrick(suit, player);
// team is highest played
if (partner && player == table->trickCardCount - 2) {
if (table->isLastPlayerInTrick()) {
card.value = highestCardInSuit(hand, suit);
return card;
} else if (table->trickCardCount > 1) {
card.value = nearestCardWithTeam(hand, suit, highestOnTable);
return card;
}
}
// if suit is Heart, and I have Heart-K and there is Heart-A on table, then play It
if (suit == HEART && hand->findCard(HEART, CARD_K) != INVALID && highestOnTable > CARD_K){
card.value = CARD_K;
return card;
}
// if I have Q-Card, and there is power card than Q on table, then play Q-card
if (hand->findCard(suit, CARD_Q) != INVALID && highestOnTable > CARD_Q) {
card.value = CARD_Q;
return card;
}
card.value = nearestCard(hand, suit, highestOnTable);
return card;
}
Card ComplexLevel::thinkCardOutSuit(Hand *hand, Suit suit, int turn)
{
CCLog("Call ComplexLevel::thinkCardOutSuit");
Card card;
// team is highest played
if (partner && table->isTeamHighest(suit)) {
return highestCardOutSuit(hand, suit);
}
//If I have Heart-K, play it
if (hand->findCard(HEART, CARD_K) != INVALID) {
card.suit = HEART;
card.value = CARD_K;
return card;
}
// If I have Q-Card, play It
Suit suits[4] = {HEART, CLOVER, DIAMOND, SPADE};
for (int i = 0; i < 4; i++) {
if (suit != suits[i] && duplicateQ[i] == turn && hand->findCard(suits[i], CARD_Q) != INVALID) {
card.suit = suits[i];
card.value = CARD_Q;
return card;
}
}
for (int i = 0; i < 4; i++) {
if (suit != suits[i] && hand->findCard(suits[i], CARD_Q) != INVALID) {
card.suit = suits[i];
card.value = CARD_Q;
return card;
}
}
//If suit is not D-card, and I have D card, then play power D-card
if (suit != DIAMOND && hand->hasSuit(DIAMOND)){
card.suit = DIAMOND;
card.value = hand->highestCard(DIAMOND);
return card;
}
// find highest card.
int v = CARD_BLANK;
Suit s = BLANK;
hand->highestCardOfAll(&s, &v);
card.suit = s;
card.value = v;
return card;
}
Card ComplexLevel::thinkCardFirst(Hand *hand, int turn)
{
CCLog("Call ComplexLevel::thinkCardFirst");
Card card;
int exceptSuit = 0;
if (duplicateK == turn && !kingPlayed) {
exceptSuit |= HEART;
}
Suit suits[4] = {HEART, CLOVER, DIAMOND, SPADE};
for (int i = 0; i < 4; i++) {
if (duplicateQ[i] == turn && !HAS_BIT(queenPlayed, suits[i])) {
exceptSuit |= suits[i];
}
}
if (partner) {
int team = (turn + 2) % PLAYER_NUM;
if (duplicateK == team && !kingPlayed) {
exceptSuit |= HEART;
}
for (int i = 0; i < 4; i++) {
if (duplicateQ[i] == team && !HAS_BIT(queenPlayed, suits[i])) {
exceptSuit |= suits[i];
}
}
}
card = lowestCardExcept(hand, turn, exceptSuit);
if (card.isInvalid()) {
card = lowestCardExcept(hand, turn, 0);
if (!card.isInvalid()) {
return card;
}
} else {
return card;
}
// If I have K, A, play this
for (int i = 0; i < PLAYER_CARD_NUM; i++) {
Card hcard = hand->card(i);
if (hcard.suit != BLANK && !hcard.isHK() && !hcard.isQ()) {
return hcard;
}
}
// if I have D-Card, play lowest D-Card
if (hand->hasSuit(DIAMOND)) {
card.suit = DIAMOND;
card.value = hand->lowestCard(DIAMOND);
return card;
}
// If I have Q-Card, play It
for (int i = 0; i < 4; i++) {
if (hand->findCard(suits[i], CARD_Q) != INVALID) {
card.suit = suits[i];
card.value = CARD_Q;
return card;
}
}
// If I have Heart-K, play it
if (hand->findCard(HEART, CARD_K) != INVALID) {
card.suit = HEART;
card.value = CARD_K;
return card;
}
return card;
}
int ComplexLevel::highestCardInSuit(Hand *hand, Suit suit)
{
for (int i = CARD_A; i >= CARD_2; i--) {
if ((suit == HEART && i == CARD_K) || i == CARD_Q) {
continue;
}
if (hand->findCard(suit, i) != INVALID) {
return i;
}
}
if (hand->findCard(suit, CARD_Q) != INVALID)
return CARD_Q;
if (hand->findCard(suit, CARD_K) != INVALID)
return CARD_K;
return 0;
}
Card ComplexLevel::highestCardOutSuit(Hand *hand, Suit suit)
{
Card ret;
ret.suit = BLANK;
ret.value = CARD_BLANK;
for ( int i = 0; i < PLAYER_CARD_NUM; i++) {
Card card = hand->card(i);
if (card.suit != BLANK && card.value > ret.value && !card.isHK() && !card.isQ() && !card.isD()) {
ret = card;
}
}
if (ret.suit == BLANK) {
if (suit != DIAMOND) {
int value = hand->highestCard(DIAMOND);
if (value >= CARD_2 && value != CARD_Q) {
ret.suit = DIAMOND;
ret.value = value;
return ret;
}
}
for (int i = 0; i < PLAYER_CARD_NUM; i++) {
Card card = hand->card(i);
if (card.suit != BLANK) {
return card;
}
}
}
return ret;
}
Card ComplexLevel::lowestCardExcept(Hand *hand, int turn, int exceptSuit)
{
Card card;
card.set(BLANK, 0);
// i have lowest card and play it
Suit suit4Lows[4] = { DIAMOND, CLOVER, SPADE, HEART };
for (int i = 0; i < 4; i++) {
if (!HAS_BIT(exceptSuit, suit4Lows[i]) && hand->hasSuit(suit4Lows[i]) && !table->isFinishedSuit(hand, suit4Lows[i])) {
int value = hand->lowestCard(suit4Lows[i]);
if (table->isLowestCard(suit4Lows[i], value) || value < CARD_4) {
card.set(suit4Lows[i], value);
return card;
}
}
}
int power = CARD_MAX;
int index = INVALID;
// get lowest card
for (int i = 0; i < PLAYER_CARD_NUM; i++) {
if (hand->cardSuit(i) != BLANK) {
int suit = hand->cardSuit(i);
int value = hand->cardValue(i);
if (value >= CARD_Q || HAS_BIT(exceptSuit, suit)) {
continue;
}
if (value < power) {
index = i;
power = value;
}
}
}
if (index != INVALID) {
card.set(hand->cardSuit(index), hand->cardValue(index));
return card;
}
return card;
}
int ComplexLevel::nearestCardWithTeam(Hand *hand, Suit suit, int highestOnTable)
{
for (int i = highestOnTable - 1; i >= CARD_2; i--) {
if (suit == HEART) {
if (hand->findCard(suit, i) != INVALID && i != CARD_K && i != CARD_Q) {
return i;
}
} else {
if (hand->findCard(suit, i) != INVALID && i != CARD_Q) {
return i;
}
}
}
return highCard(hand, suit, highestOnTable);
}
int ComplexLevel::nearestCard(Hand *hand, Suit suit, int highestOnTable)
{
int value = hand->lowCard(suit, highestOnTable);
if (value == 0) { // if i haven't low card
return highCard(hand, suit, highestOnTable);
}
return value;
}
int ComplexLevel::highCard(Hand *hand, Suit suit, int highestOnTable)
{
int value = 0;
if (table->isLastPlayerInTrick()) { // last play
if (suit == HEART) {
for (int i = CARD_A; i >= CARD_2; i--) {
if (hand->findCard(suit, i) != INVALID && i != CARD_Q && i != CARD_K) {
return i;
}
}
} else {
for (int i = CARD_A; i >= CARD_2; i--) {
if (hand->findCard(suit, i) != INVALID && i != CARD_Q) {
return i;
}
}
}
} else {
if (suit == HEART) {
for (int i = highestOnTable + 1; i <= CARD_A; i++) {
if (hand->findCard(suit, i) != INVALID && i != CARD_Q && i != CARD_K) {
return i;
}
}
} else {
for (int i = highestOnTable + 1; i <= CARD_A; i++) {
if (hand->findCard(suit, i) != INVALID && i != CARD_Q) {
return i;
}
}
}
}
if (hand->findCard(suit, CARD_Q) != INVALID) {
return CARD_Q;
}
if (hand->findCard(suit, CARD_K) != INVALID) {
return CARD_K;
}
return value;
}
| true |
df5fbae2c7ba3d722d0c246539b514487fa1c2ce | C++ | 5l1v3r1/go-engine | /engine/src/engine/_engine.cpp | ISO-8859-1 | 2,692 | 2.53125 | 3 | [] | no_license | #include "engine/_engine.h"
#include "engine/_instance.h"
#include "_systems.h"
// User
#include "instances.h"
CEngine gEngine;
using namespace std;
CEngine::CEngine(): title("GO-Engine"), running(false)
{
}
bool CEngine::Init(int argc, char* argv[])
{
for(int i = 0; i < argc; i++)
arguments.push_back(string(argv[i]));
current_instance = "";
running = true;
if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
gSystem_Debug.msg_box(Debug::error, ERROR_FATAL_INIT, "Could not load SDL module");
return false;
}
/** Mas mdulos y libreras de SDL aqu **/
if(!Systems_Init())
{
return false;
}
if(!User_Engine_Loader())
{
gSystem_Debug.msg_box(Debug::error, ERROR_FATAL_INIT, "Could not load engine settings (User_Engine_Loader)");
return false;
}
if(!User_Instance_Loader())
{
gSystem_Debug.msg_box(Debug::error, ERROR_FATAL_INIT, "Could not load instance settings (User_Instance_Loader)");
return false;
}
if(instances.size() == 0)
{
gSystem_Debug.msg_box(Debug::error, ERROR_FATAL_INIT, "There are no Instances to load! Add some in User_Instance_Loader().");
return false;
}
return true;
}
void CEngine::Close()
{
RemoveAllInstances();
Systems_Close();
SDL_Quit();
}
int CEngine::OnExecute(int argc, char* argv[])
{
Init(argc, argv);
while(current_instance != "" && running)
{
if(instances.find(current_instance) != instances.end())
current_instance = instances[current_instance]->OnExecute();
else { // Error y salir
gSystem_Debug.error("From CEngine::OnExecute: Error, instance \"%s\" not defined.", current_instance.c_str());
Exit();
}
// Resetear contenido de los sistemas.
Systems_Reset();
}
Close();
return 0;
}
void CEngine::AddInstance(fboolpointer load_gameObject_function, string resource_file, string instance_name)
{
if(instances.find(instance_name) == instances.end()) {
CInstance* new_instance = new CInstance(load_gameObject_function, resource_file);
instances[instance_name] = new_instance;
if(current_instance == "")
current_instance = instance_name;
}
else {
gSystem_Debug.error("From CEngine::AddInstance: Cannot add instance with name \"%s\" (existing name).", instance_name.c_str());
}
//instances.push_back(new_instance);
}
void CEngine::RemoveAllInstances()
{
for(map<string, CInstance*>::iterator it = instances.begin(); it != instances.end(); ++it)
{
delete it->second;
}
instances.clear();
}
void CEngine::SetIcon(string icon_dir)
{
SDL_Surface* icon = Utils::sdl_cargar_img(icon_dir);
SDL_SetWindowIcon(gRender.window, icon);
SDL_FreeSurface(icon);
}
| true |
8c73824ecd3839dbae66dff0ac5692a398335469 | C++ | Cmdeew/r-type | /client/Element.h | UTF-8 | 967 | 2.84375 | 3 | [] | no_license | #ifndef ELEMENT_H
#define ELEMENT_H
#include <iostream>
#include <list>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
class Element
{
private:
unsigned char _posX;
unsigned char _posY;
unsigned char _life;
unsigned char _ID;
unsigned char _type;
std::list<sf::Sprite> _lSprite;
Element();
public:
std::list<sf::Sprite>::iterator _iter;
Element(unsigned char x, unsigned char y, unsigned char life,
unsigned char id, unsigned char type);
~Element();
void setPosX(unsigned char);
void setPosY(unsigned char);
void setLife(unsigned char);
void setID(unsigned char);
void setType(unsigned char);
void setSprite(const std::list<sf::Texture> &list);
void setPosSprite(sf::Sprite &sprite);
unsigned char& getPosX();
unsigned char& getPosY();
unsigned char& getLife();
unsigned char& getID();
unsigned char& getType();
std::list<sf::Sprite> &getSprite();
};
#endif
| true |
673d4196e2f15d4664a73a49035afb8888667a4d | C++ | jonathan500/TPA | /exercicio02.cpp | ISO-8859-1 | 506 | 2.765625 | 3 | [] | no_license | /*
Programa: rea de um triangulo.
Autor: Jonathan Ricardo Pereira Izidoro.
Data: 29/09/2019.
Data da Alterao: 30/09/2019
*/
#include<stdio.h>
#include <conio.h>
#include <windows.h>
#include<locale.h>
int main(){
setlocale(LC_ALL,"""");
int base = 0, altura = 0, area = 0;
printf("Informe o tamanho da base do tringulo:\n");
scanf("%i",&base);
printf("Informe a altura do tringulo:\n");
scanf("%i", &altura);
area = (base*altura)/2;
printf("A area do tringulo corresponde : %i \n",area);
system("pause");
}
| true |
8497215ea64ef7c80e2c2cf0cb555fd0f6fa0033 | C++ | dariuszlesiecki/OOP-1 | /lab13/lab13.cpp | UTF-8 | 1,132 | 3.546875 | 4 | [] | no_license | /*
Celem zadania jest przećwiczenie wyjątków.
Proszę napisać klasę Number, która pozwala na
przechowanie liczb tylko w pewnym określonym zakresie.
Proszę uzupełnić brakujące metody tak, by wynik programu
był taki jak na końcu tego pliku.
*/
#include "Number.h"
#include <iostream>
#include <stdexcept>
int main() {
Number::setRange(-3, 4);
try{
Number n1(3); //ok
n1.print();
n1.value() = -2.5; //ok
n1.print();
try{
const Number n2(2); //ok
std::cout << "second number: " << n2.value() << std::endl;
Number n3(-4); // tu za mała liczba
n3.print();
}
catch(const std::out_of_range &e){
std::cout << "exception: " << e.what() << std::endl;
}
n1.value() = 5; // nie ok
n1.print();
std::cout<<"THIS IS TOO FAR..."<<std::endl;
}
catch(const std::out_of_range &e){
std::cout << "exception: " << e.what() << std::endl;
}
}
/* wynik
Number: 3 is in the range [-3, 4]
Number: -2.5 is in the range [-3, 4]
second number: 2
exception: Out of range during construction
exception: Out of range during assignment
*/ | true |
af9e1b3f165594b49887aaeb4d5bce6e939661ca | C++ | ShwetaArora12/myDSA_code-base | /BinarySearch.cpp | UTF-8 | 2,605 | 4.21875 | 4 | [] | no_license | #include <iostream>
// Recursive implementation of Binary Search Algorithm to return
// the position of target x in the sub-array array[low..high]
int binarySearch(int array[], int low, int high, int key)
{
// Base condition (search space is exhausted)
if (low > high)
return -1;
// we find the mid value in the search space and
// compares it with target value
/*[Note: we can also use low + (high - low)/2 to avoid overflow.
Consider an example where the data type of the low and high is integer.
So integer has an upper range of 65535 if it is an unsigned integer.
Now consider the value of low as 2048 and high as 65530.
Now if you calculate (low + high) .Clearly 65530 + 2048 is larger that 65535 (max value stored in 2 bytes)
and this would result in an overflow,
So, it will give you a wrong result due to overflow of integer data type.
Now if you calculate mid as low + ( high -low )/2 ,
it will give you a correct result]*/
int mid = (low + high)/2; // overflow can happen
// int mid = low + (high - low)/2;
// Base condition (target value is found)
if (key == array[mid])
return mid;
// discard all elements in the right search space
// including the mid element
else if (key < array[mid])
return binarySearch(array, low, mid - 1, key);
// discard all elements in the left search space
// including the mid element
else
return binarySearch(array, mid + 1, high, key);
}
// Recursive implementation of Binary Search Algorithm
int main(void)
{
int array[] = { 2, 5, 6, 8, 9, 10 };
int target = 5;
int n = sizeof(array)/sizeof(array[0]);
int low = 0, high = n - 1;
int index = binarySearch(array, low, high, target);
if (index != -1)
printf("Element found at index %d", index);
else
printf("Element not found in the array");
return 0;
}
/* Try more Inputs
case 1:
actual = binarySearch([16, 19, 20, 23, 45, 56, 78, 90, 96, 100],0,9,45)
expected = 4
case2:
actual = binarySearch([2, 3, 4, 10, 40],0,4,10)
expected = 3
case3:
actual = binarySearch([3, 4, 5, 6, 7, 8, 9],0,6,4)
expected = 1
*/
/* ---------------Iterative approach--------------
binarySearch(array, int x)
low = 0, high = array.length - 1;
while (low <= high)
int mid = low + ((high-low)/2);
if (x == array[mid])
return mid
else if (x < array[mid])
high = mid - 1;
else
low = mid + 1
return -1
*/
| true |
f91aa141b5eba4ddb2d3762dd417ac75b128469f | C++ | STabaresG/CursoFCII_UdeA-2020-2 | /Documentos/Seguimiento1/CC1152704745/exp_func/exp_f.h | UTF-8 | 688 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
class exp_f{
public:
exp_f();
void print_expval();
void set_x(double); // Resets the argument of exp function. Recalculates exp() function
void set_N(unsigned long long int); // Resets the truncation number of the series. Recalculates exp() function
unsigned long long int fac(unsigned long long int); // Calculation of factotial given N
void start_interactive();
private:
unsigned long long int N; // Number of terms to truncate the series
double x; // Argument of exponential function
double exp_val; // Value of exponential function
double exp(double, unsigned long long int); // Calculation of exponential given x and N
};
| true |
98d3e1ddefb9358c2aee8deeb457eb0686fbafc1 | C++ | Mesiow/Illusion-Engine | /IllusionEngine/src/Gui/Button.cpp | UTF-8 | 3,804 | 2.625 | 3 | [] | no_license | #include "../pcHeaders.h"
#include "Button.h"
#include "../Engine.h"
namespace Illusion
{
namespace gui
{
Button::Button(sf::Vector2f position, Size size,
sf::Color idle, sf::Color hover, sf::Color pressed)
{
flag_ = Flag::idle;
btnColors_[Colors::idleColor] = idle;
btnColors_[Colors::hoverColor] = hover;
btnColors_[Colors::pressColor] = pressed;
this->position_ = position;
this->size_ = size;
switch (size)
{
case Size::large:
button_.setSize(getButtonSize(size));
break;
case Size::medium:
button_.setSize(getButtonSize(size));
case Size::Small:
button_.setSize(getButtonSize(size));
break;
}
//set position of button in middle of window without setting the buttons origin
button_.setPosition(sf::Vector2f(position.x - button_.getGlobalBounds().width/2,
position.y + button_.getGlobalBounds().height/2));
button_.setFillColor(btnColors_[Colors::idleColor]);
}
Button::~Button()
{
}
void Button::handleEvents(sf::Event &e)
{
flag_ = Flag::idle;
if (containsMouse(button_.getGlobalBounds()))
flag_ = Flag::hover;
switch (e.type)
{
case sf::Event::MouseButtonPressed:
{
if (e.mouseButton.button == sf::Mouse::Left)
{
if (containsMouse(button_.getGlobalBounds()))
{
flag_ = Flag::pressed;
function_();
}
}
}
break;
default:
break;
}
}
void Button::update()
{
switch (flag_)
{
case Flag::idle:
button_.setFillColor(btnColors_[Colors::idleColor]);
text_.setFillColor(txtColors_[Colors::idleColor]);
break;
case Flag::hover:
button_.setFillColor(btnColors_[Colors::hoverColor]);
text_.setFillColor(txtColors_[Colors::hoverColor]);
break;
case Flag::pressed:
button_.setFillColor(btnColors_[Colors::pressColor]);
text_.setFillColor(txtColors_[Colors::pressColor]);
break;
default:
break;
}
}
void Button::draw(sf::RenderTarget &target)
{
target.draw(button_);
target.draw(text_);
}
void Button::setPosition(const sf::Vector2f pos)
{
button_.setPosition(pos);
updateText();
}
void Button::setText(const std::string &str, sf::Font &font, uint charSize,
sf::Color idle, sf::Color hover, sf::Color pressed)
{
txtColors_[Colors::idleColor] = idle;
txtColors_[Colors::hoverColor] = hover;
txtColors_[Colors::pressColor] = pressed;
text_.setCharacterSize(charSize);
text_.setFont(font);
text_.setString(str);
/*text_.setOrigin(text_.getGlobalBounds().left + text_.getGlobalBounds().width / 2,
text_.getGlobalBounds().top - text_.getGlobalBounds().height / 2);
*/
text_.setPosition(
button_.getPosition().x + (button_.getGlobalBounds().width / 2.f) - text_.getGlobalBounds().width / 2.f,
button_.getPosition().y + (button_.getGlobalBounds().height / 3.f) - text_.getGlobalBounds().height / 2.f
);
text_.setFillColor(txtColors_[Colors::idleColor]);
}
void Button::setStr(const std::string str)
{
text_.setString(str);
updateText();
}
void Button::updateText()
{
text_.setPosition(
button_.getPosition().x + (button_.getGlobalBounds().width / 2.f) - text_.getGlobalBounds().width / 2.f,
button_.getPosition().y + (button_.getGlobalBounds().height / 3.f) - text_.getGlobalBounds().height / 2.f
);
/*text_.setPosition(button_.getPosition().x + text_.getGlobalBounds().width/10,
button_.getPosition().y + text_.getGlobalBounds().height);*/
}
void Button::setFunction(std::function<void(void)> func)
{
function_ = func;
}
sf::Vector2f Button::getPosition() const
{
return sf::Vector2f(position_.x - button_.getGlobalBounds().width / 2,
position_.y + button_.getGlobalBounds().height / 2); //get position of origin
}
}
} | true |
e4c5ddddcc3538a87427a3b1adc07efe5164bfcc | C++ | BlackLunx/projectMAM | /menu.cpp | UTF-8 | 4,865 | 2.703125 | 3 | [] | no_license | //
// Created by JG on 03.06.2019.
//
#include <SFML/Graphics.hpp>
#include "game.cpp"
#include <vector>
#include <iostream>
using namespace sf;
void selectLevel(RenderWindow& window);
void menu(RenderWindow &window){
Texture newGame_TX1, newGame_TX2, exit_TX1, exit_TX2, background_TX, cursorTX;
newGame_TX1.loadFromFile("Images/newgamefirst.png");
newGame_TX2.loadFromFile("Images/newgamesecond.png");
exit_TX1.loadFromFile("Images/exitfirst.png");
exit_TX2.loadFromFile("Images/exitsecond.png");
background_TX.loadFromFile("Images/mainpicture.png");
cursorTX.loadFromFile("Images/cursor.png");
Sprite newGameSP(newGame_TX1), newGameSPHL(newGame_TX2), exitSP(exit_TX1), exitSPHL(exit_TX2), backgroundSP(background_TX), cursorSP(cursorTX);
newGameSP.setPosition(800, 200);
exitSP.setPosition(800, 260);
newGameSPHL.setPosition(800, 200);
exitSPHL.setPosition(800, 260);
while(window.isOpen()){
int currentPosition = 0;
Event event;
while (window.pollEvent(event)){
if (event.type == Event::Closed){
window.close();
exit(0);
}
}
if(IntRect(800, 200, 150, 40).contains(Mouse::getPosition(window))){
currentPosition = 1;
cursorSP.setPosition(static_cast<Vector2f>(Mouse::getPosition(window)));
}
if(IntRect(800, 260, 150, 40).contains(Mouse::getPosition(window))){
currentPosition = 2;
cursorSP.setPosition(static_cast<Vector2f>(Mouse::getPosition(window)));
}
if(Mouse::isButtonPressed(Mouse::Left)){
if(currentPosition == 1){
sleep(seconds(0.1));
selectLevel(window);
//startGame(window);
}
if(currentPosition == 2){
window.close();
}
}
window.clear();
window.draw(backgroundSP);
if(currentPosition == 1){
window.setMouseCursorVisible(false);
window.draw(newGameSPHL);
window.draw(exitSP);
window.draw(cursorSP);
}
else{
window.draw(newGameSP);
if(currentPosition == 2){
window.setMouseCursorVisible(false);
window.draw(exitSPHL);
window.draw(cursorSP);
}
else{
window.setMouseCursorVisible(true);
window.draw(exitSP);
}
}
window.display();
}
}
void selectLevel(RenderWindow& window){
Texture backgroundTX, cursorTX;
backgroundTX.loadFromFile("Images/levelMenu.png");
cursorTX.loadFromFile("Images/cursor.png");
std::vector<Texture> textures(8);
textures[0].loadFromFile("Images/easyFirst.png");
textures[1].loadFromFile("Images/easySecond.png");
textures[2].loadFromFile("Images/mediumFirst.png");
textures[3].loadFromFile("Images/mediumSecond.png");
textures[4].loadFromFile("Images/hardFirst.png");
textures[5].loadFromFile("Images/hardSecond.png");
textures[6].loadFromFile("Images/backFirst.png");
textures[7].loadFromFile("Images/backSecond.png");
Sprite background(backgroundTX), cursorSP(cursorTX);
std::vector<std::pair<Sprite, Sprite> > draws(4);
for(int i = 0;i < 4;i++){
draws[i].first.setTexture(textures[i * 2]);
draws[i].second.setTexture(textures[i * 2 + 1]);
draws[i].first.setPosition(800, 200 + i * 60);
draws[i].second.setPosition(800, 200 + i * 60);
}
while(window.isOpen()){
Event event;
while (window.pollEvent(event)){
if (event.type == Event::Closed){
window.close();
exit(0);
}
}
std::vector<int> isHere(4, 0);
for(int i = 0;i < 4;i++){
if(IntRect(800, 200 + i * 60, 150, 40).contains(Mouse::getPosition(window))){
isHere[i] = 1;
cursorSP.setPosition(static_cast<Vector2f>(Mouse::getPosition(window)));
}
}
if(Mouse::isButtonPressed(Mouse::Left)){
for(int i = 0;i < 3;i++) if(isHere[i]){
sleep(seconds(0.1));
startGame(window, i);
}
if(isHere[3]){
return;
}
}
window.clear();
window.draw(background);
bool wasInButton = false;
for(int i = 0;i < 4;i++){
if(isHere[i]){
window.draw(draws[i].second);
wasInButton = 1;
}
else{
window.draw(draws[i].first);
}
}
window.setMouseCursorVisible(!wasInButton);
if(wasInButton){
window.draw(cursorSP);
}
window.display();
}
} | true |
0736848fe90aeee868d961008fa9a60e13122118 | C++ | capcoders/SPOJ_PTIT | /P166SUMA-src.cpp | UTF-8 | 915 | 2.515625 | 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.
*/
//package p166suma;
import java.util.Scanner;
/**
*
* @author Cuong Nguyen
*/
public class Main {
/**
* @param args the command line arguments
*/
static int MAX = 5005;
static int []d = new int [MAX];
static int res = 0;
static int n;
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
n = in.nextInt();
for (int i = 1; i <= n; i++) d[i] = 0;
for (int i = 1; i <= n; i++){
int x = in.nextInt();
if (x <= n) d[x] = 1;
}
for (int i = 1; i <= n; i++){
res += d[i];
}
res = n - res;
System.out.println(res);
}
}
| true |
b148b70463db22edd079f562584569b50ad03e2a | C++ | Sigrids/Compiler | /staticSemantics.cpp | UTF-8 | 3,523 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include "exceptions.h"
#include "tree.h"
#include "staticSemantics.h"
int find(std::vector<std::string> varStack, std::string str)
{
for (int i = varStack.size() - 1; i >= 0; i--)
{
if (varStack[i] == str)
{
return i;
}
}
return -1;
}
void printStack(std::vector<std::string> varStack)
{
std::cout << "Stack:\n";
for (int i = varStack.size() - 1; i >= 0; i--)
{
std::cout << varStack[i] << "\n";
}
std::cout << "End Stack\n";
}
StaticSemantics::StaticSemantics()
{
tree = NULL;
}
StaticSemantics::StaticSemantics(Tree* root)
{
loadTree(root);
}
void StaticSemantics::loadTree(Tree* root)
{
tree = root;
}
void StaticSemantics::checkTree()
{
std::vector <std::string> localStack;
std::vector <std::string> globalStack;
travel(tree, localStack, globalStack);
}
void StaticSemantics::travel(Tree* node, std::vector<std::string>& localStack, std::vector<std::string>& globalStack)
{
if (node == NULL)
{
return;
}
if (node->node_name == "program")
{
StaticSemantics::travel(node->child1, localStack, globalStack);
StaticSemantics::travel(node->child2, localStack, globalStack);
}
else if (node->node_name == "block")
{
std::vector<std::string> blockLocalStack;
std::vector<std::string> blockGlobalStack = globalStack;
for (int i = 0; i < localStack.size(); i++)
{
blockGlobalStack.push_back(localStack[i]);
}
StaticSemantics::travel(node->child1, blockLocalStack, blockGlobalStack);
StaticSemantics::travel(node->child2, blockLocalStack, blockGlobalStack);
}
else if (node->node_name == "R")
{
if (node->child1->node_name == "end")
{
if (node->child1->token->getTokenEnum() == TokenEnum::id_tk)
{
std::string var = node->child1->token->getTokenStr();
//std::cout << var << "<-r\n";
if (find(localStack, var) < 0 && find(globalStack, var) < 0)
{
std::cout << var << "\n";
throw CompilerException("Var above not defined in END");
}
}
}
else
{
StaticSemantics::travel(node->child1, localStack, globalStack);
}
}
else if (node->node_name == "in")
{
std::string var = node->child1->token->getTokenStr();
if (find(localStack, var) < 0 && find(globalStack, var) < 0)
{
std::cout << var << "\n";
throw CompilerException("Var above not defined in IN.");
}
}
else if (node->node_name == "assign")
{
std::string var = node->child1->token->getTokenStr();
if (find(localStack, var) < 0 && find(globalStack, var) < 0)
{
std::cout << var << "\n";
throw CompilerException("Var above not defined in ASSIGN");
}
StaticSemantics::travel(node->child2, localStack, globalStack);
}
else if (node->node_name == "vars")
{
std::string var = node->child1->token->getTokenStr();
if (find(localStack, var) >= 0)
{
std::cout << var << "\n";
throw CompilerException("Var above already defined in VARS.");
}
localStack.push_back(var);
StaticSemantics::travel(node->child3, localStack, globalStack);
}
else
{
if (node->child1 != NULL) StaticSemantics::travel(node->child1, localStack, globalStack);
if (node->child2 != NULL) StaticSemantics::travel(node->child2, localStack, globalStack);
if (node->child3 != NULL) StaticSemantics::travel(node->child3, localStack, globalStack);
if (node->child4 != NULL) StaticSemantics::travel(node->child4, localStack, globalStack);
}
}
| true |
9bc8dfcf238c58ef525ad49674c8be4864e16ab5 | C++ | NanguangChou/algoritm_solution | /algorithm_005_longestPalindrome/algorithm_005_longestPalindrome/main.cpp | UTF-8 | 1,211 | 3.25 | 3 | [] | no_license | //
// main.cpp
// algorithm_005_longestPalindrome
//
// Created by zhounanguang on 15/12/17.
// Copyright © 2015年 zhounanguang. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
unsigned long len = s.length();
if(!len){
return "";
}
int i;
int left,right;
int max = 0;
int start = 0;
string curlongest;
string result;
for(i=0; i<2*len; i++){
left = i/2;
right = i/2;
if(i%2==1){
right++;
}
curlongest = this->palindrome(s,left,right);
if(max < curlongest.length()){
start = i;
result = curlongest;
max = curlongest.length();
}
}
return result;
}
string palindrome(string s1, int left, int right){
while( left>=0 && right<=s1.length() && s1[left]==s1[right] ){
left --;
right ++;
}
left++;
right--;
return s1.substr(left,right-left+1);
}
};
int main(int argc, const char * argv[]) {
// insert code here...
string s = "a";
Solution sol;
cout<<sol.longestPalindrome(s)<<endl;
return 0;
}
| true |
3a815e5b68fb2ad8b57cc7a76d8e0c31b3917b31 | C++ | mridul88/Programs | /self made - not working/merg_2sorted_array.CPP | UTF-8 | 1,180 | 3.171875 | 3 | [] | no_license | #include<cstdio>
using namespace std;
/* this program is to merge two sorted array into a sorted array*/
int c[7];
void enter(int n)
{
int static k=0;
c[k]=n;
k++;
}
int main()
{
int i,j,l,*a,*b,n,m;
char flag='z';
printf("enter the size of one array");
scanf("%d",&n);
printf("\n enter the elements of first array");
a=new int[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the size of second array");
scanf("%d",&m);
b=new int [m];
printf("\n enter the elements of second array");
for(i=0;i<m;i++)
scanf("%d",&b[i]);
j=i=0;
while(flag=='z')
{
while(a[i]>=b[j]) /* first the element of first array is compared */
{
enter(b[j]);
if(j<m-1)
j++;
else
{ flag='b';
break;
}
}
while(b[j]>a[i])
{
enter(a[i]);
if(i<n-1)
i++;
else
{ if(flag=='b')
flag='c';
else
flag='a';
break;
}
}
}
if(flag=='a')
for(l=0;l+j<m;l++)
enter(b[j+l]);
else if (flag=='b')
for(l=0;l+i<n;l++)
enter(a[i+l]);
for(i=0;i<(m+n);i++)
printf("\t%d",c[i]);
while(getchar()!='\n');
getchar();
return 0;
}
| true |
03c03fcc4c6b0c32f5a3f528d7e36545ceaadb44 | C++ | SierraBOI/sierra | /CurrentBlinkSetup.ino | UTF-8 | 2,771 | 2.796875 | 3 | [] | no_license | const int ledPin = 12; // the number of the LED pin
int ledState = LOW;
int commandState;
int buttonState;
int a = 0;
int blinkCount = 0;
bool startBlink = false;
unsigned long previousMillis = 0; // will store last time LED was updated
// constants won't change:
const long interval = 1000; // interval at which to blink (milliseconds)
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(8, OUTPUT);
pinMode(10, OUTPUT);
Serial.begin(9600);
}
void loop()
{
commandState = analogRead(A0);
Serial.println(commandState);
if (commandState == 959)
{
startBlink = true;
}
if (startBlink)
{
checkInterval();
startBlink = false;
}
// Left Blinker Setup
buttonState = analogRead(A0);
delay(40);
if (buttonState == 133)
{
digitalWrite(10, !digitalRead(10));
delay(40);
}
}
void checkInterval()
{
Serial.println("8x if");
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
Serial.println("if 1");
Serial.println(currentMillis);
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*2)
{
Serial.println("if 2");
Serial.println(currentMillis);
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*3)
{
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*4)
{
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*5)
{
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*6)
{
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*7)
{
previousMillis = currentMillis;
switchButton(ledPin);
}
if (currentMillis - previousMillis >= interval*8)
{
previousMillis = currentMillis;
switchButton(ledPin);
}
}
void switchButton(int switchLed)
{
if (ledState == LOW)
{
ledState = HIGH;
}
else
{
ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(switchLed, ledState);
} | true |
41ec4f44324d6126207d809eb88db5a6b5d355a5 | C++ | ZyronMelancon/Bunnies | /Bunnies/LinkedList.h | UTF-8 | 274 | 2.6875 | 3 | [] | no_license | #pragma once
#include "Bunny.h"
class ListNode
{
private:
Bunny bunny;
ListNode * next;
public:
ListNode(Bunny b, ListNode * next);
};
class LinkedList
{
private:
public:
LinkedList();
~LinkedList();
bool Empty();
void Insert(Bunny b);
void Remove(ListNode n);
}; | true |
b39327128294f202ef30fcaf28b0e9c7dd0e53cc | C++ | bedomohamed/jumpingIntoCpp | /Chapter 5/99Bottles/main.cpp | UTF-8 | 315 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int x;
for(x = 99; x > 0; x--){
cout << x << " bottles of beer on the wall, " << x << " bottles of beer." << "\n";
cout << "take one down and pass it around " << x - 1 << " bottles of beer on the wall." << "\n";
}
return 0;
}
| true |
f507b3039d4f30ce91e2a130cf54416eaf539021 | C++ | shreyasbalaji/cilk_alg_tmp | /cilk_stable_sort.h | UTF-8 | 6,169 | 2.859375 | 3 | [] | no_license | #ifndef CILKSTL_STABLE_SORT_H
#define CILKSTL_STABLE_SORT_H
#include <cilk/cilk.h>
#include <cilk/reducer.h>
#include <cilk/reducer_opadd.h>
#include <algorithm>
#include <cstdlib>
#include <iterator>
namespace cilkstl {
namespace __parallel {
namespace __sort {
constexpr int CILKSTL_PARALLEL_CUTOFF =
4000; // cutoff below which the sort routine will default to serial execution
constexpr int CILKSTL_PARALLEL_MERGE_CUTOFF =
1000; // cutoff below which the merge routine will default to serial execution
/**
* This file implements a standard parallel mergesort algorithm using a single temporary buffer of
* equal size to the input sequence
*/
template <class _DataType>
class StableSortBuffer {
public:
StableSortBuffer(size_t size) { data_ = (_DataType *)malloc(size * sizeof(_DataType)); }
~StableSortBuffer() { delete data_; }
_DataType *data() { return data_; }
private:
_DataType *data_;
// disallow copies
StableSortBuffer(const StableSortBuffer &);
StableSortBuffer &operator=(const StableSortBuffer &);
};
template <class _RandomAccessIterator1, class _RandomAccessIterator2, class _RandomAccessIterator3,
class _CompareFunc>
void serial_merge(_RandomAccessIterator1 as, _RandomAccessIterator1 ae, _RandomAccessIterator2 bs,
_RandomAccessIterator2 be, _RandomAccessIterator3 cs, _CompareFunc comp) {
while (as < ae && bs < be) {
if (comp(*bs, *as))
*cs++ = std::move(*bs++);
else
*cs++ = std::move(*as++);
}
while (as < ae) *cs++ = std::move(*as++);
while (bs < be) *cs++ = std::move(*bs++);
}
template <class _RandomAccessIterator1, class _RandomAccessIterator2>
void move_contents(_RandomAccessIterator1 first, _RandomAccessIterator1 last,
_RandomAccessIterator2 out) {
typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type diff1_t;
typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type diff2_t;
typedef typename std::common_type<diff1_t, diff2_t>::type diff_t;
diff_t range_width = last - first;
cilk_for(diff_t k = 0; k < range_width; ++k) { *(out + k) = std::move(*(first + k)); }
}
template <class _RandomAccessIterator1, class _RandomAccessIterator2, class _RandomAccessIterator3,
class _CompareFunc>
void parallel_merge(_RandomAccessIterator1 as, _RandomAccessIterator1 ae, _RandomAccessIterator2 bs,
_RandomAccessIterator2 be, _RandomAccessIterator3 cs, _CompareFunc comp) {
typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type diff1_t;
typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type diff2_t;
typedef typename std::iterator_traits<_RandomAccessIterator3>::difference_type diff3_t;
typedef typename std::common_type<diff1_t, diff2_t, diff3_t>::type diff_t;
diff_t a_range_width = ae - as;
diff_t b_range_width = be - bs;
if (a_range_width + b_range_width < CILKSTL_PARALLEL_MERGE_CUTOFF) {
serial_merge(as, ae, bs, be, cs, comp);
return;
}
diff_t a_delta, b_delta;
_RandomAccessIterator1 am;
_RandomAccessIterator2 bm;
if (a_range_width > b_range_width) {
a_delta = a_range_width - (ae - as) / 2;
am = as + a_delta;
bm = std::lower_bound(bs, be, *(as + a_delta), comp);
b_delta = bm - bs;
} else {
b_delta = (be - bs) / 2;
bm = bs + b_delta;
am = std::upper_bound(as, ae, *(bs + b_delta), comp);
a_delta = am - as;
}
cilk_spawn parallel_merge(as, am, bs, bm, cs, comp);
parallel_merge(am, ae, bm, be, cs + a_delta + b_delta, comp);
return;
}
template <class _RandomAccessIterator1, class _RandomAccessIterator2, class _CompareFunc>
bool merge_sort(_RandomAccessIterator1 first, _RandomAccessIterator1 last,
_RandomAccessIterator2 out, _CompareFunc comp) {
// returns true if output is stored in temporary buffer and false if output remains in original
typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type diff1_t;
typedef typename std::iterator_traits<_RandomAccessIterator2>::difference_type diff2_t;
typedef typename std::common_type<diff1_t, diff2_t>::type diff_t;
typedef typename std::iterator_traits<_RandomAccessIterator1>::value_type value_t;
diff_t range_width = last - first;
_RandomAccessIterator1 middle = first + range_width / 2;
_RandomAccessIterator2 out_middle = out + range_width / 2;
_RandomAccessIterator2 out_last = out + range_width;
// default to serial stable_sort on small range sizes
if (range_width / 2 <= CILKSTL_PARALLEL_CUTOFF) {
std::stable_sort(first, middle, comp);
std::stable_sort(middle, last, comp);
parallel_merge(first, middle, middle, last, out, comp);
return true; // contents in buffer out
}
bool r1 = cilk_spawn merge_sort(first, middle, out, comp);
bool r2 = merge_sort(middle, last, out_middle, comp);
cilk_sync;
if (r1 && r2) {
parallel_merge(out, out_middle, out_middle, out_last, first, comp);
return false;
} else if (!r1 && !r2) {
parallel_merge(first, middle, middle, last, out, comp);
return true;
} else if (r1) {
move_contents(middle, last, out_middle);
parallel_merge(out, out_middle, out_middle, out_last, first, comp);
return false;
} else {
move_contents(first, middle, out);
parallel_merge(out, out_middle, out_middle, out_last, first, comp);
return false;
}
}
template <class _RandomAccessIterator, class _CompareFunc>
void stable_sort(_RandomAccessIterator first, _RandomAccessIterator last, _CompareFunc comp) {
typedef typename std::iterator_traits<_RandomAccessIterator>::difference_type diff_t;
typedef typename std::iterator_traits<_RandomAccessIterator>::value_type value_t;
diff_t range_width = last - first;
if (range_width < CILKSTL_PARALLEL_CUTOFF) {
std::stable_sort(first, last, comp);
return;
}
StableSortBuffer<value_t> buffer(range_width);
bool result = merge_sort(first, last, buffer.data(), comp);
if (result) move_contents(buffer.data(), buffer.data() + range_width, first);
}
} // namespace __sort
} // namespace __parallel
}; // namespace cilkstl
#endif
| true |
fe1c02f1fb2e0196f976f79cae28bc677f26d70f | C++ | lamboxn/MCF | /MCF/Core/ArrayView.hpp | UTF-8 | 4,371 | 2.703125 | 3 | [] | no_license | // 这个文件是 MCF 的一部分。
// 有关具体授权说明,请参阅 MCFLicense.txt。
// Copyleft 2013 - 2015, LH_Mouse. All wrongs reserved.
#ifndef MCF_CORE_ARRAY_VIEW_HPP_
#define MCF_CORE_ARRAY_VIEW_HPP_
#include "../Utilities/Assert.hpp"
#include "../Utilities/CountOf.hpp"
#include <type_traits>
#include <initializer_list>
#include <cstddef>
#include "StringView.hpp"
namespace MCF {
template<typename ElementT>
class Vector;
template<class ElementT>
class ArrayView {
private:
ElementT *x_pBegin;
std::size_t x_uSize;
public:
constexpr ArrayView(std::nullptr_t = nullptr) noexcept
: x_pBegin(nullptr), x_uSize(0)
{
}
constexpr ArrayView(ElementT &rhs) noexcept
: x_pBegin(std::addressof(rhs)), x_uSize(1)
{
}
constexpr ArrayView(ElementT *pBegin, std::size_t uSize) noexcept
: x_pBegin(pBegin), x_uSize(uSize)
{
}
template<std::size_t kSizeT>
constexpr ArrayView(ElementT (&rhs)[kSizeT]) noexcept
: x_pBegin(rhs), x_uSize(kSizeT)
{
}
template<StringType kTypeT,
std::enable_if_t<
std::is_same<typename StringView<kTypeT>::Char, std::remove_cv_t<ElementT>>::value,
int> = 0>
constexpr ArrayView(StringView<kTypeT> rhs) noexcept
: x_pBegin(rhs.GetData()), x_uSize(rhs.GetSize())
{
}
constexpr ArrayView(Vector<ElementT> &rhs) noexcept
: x_pBegin(rhs.GetData()), x_uSize(rhs.GetSize())
{
}
public:
constexpr ElementT *GetBegin() const noexcept {
return x_pBegin;
}
constexpr ElementT *GetEnd() const noexcept {
return x_pBegin + x_uSize;
}
constexpr ElementT *GetData() const noexcept {
return x_pBegin;
}
constexpr std::size_t GetSize() const noexcept {
return x_uSize;
}
public:
explicit constexpr operator ElementT *() const noexcept {
return GetData();
}
constexpr ElementT &operator[](std::size_t uIndex) const noexcept {
ASSERT_MSG(uIndex < GetSize(), L"索引越界。");
return GetData();
}
};
template<class ElementT>
class ArrayView<const ElementT> {
private:
const ElementT *x_pBegin;
std::size_t x_uSize;
public:
constexpr ArrayView(std::nullptr_t = nullptr) noexcept
: x_pBegin(nullptr), x_uSize(0)
{
}
constexpr ArrayView(const ElementT &rhs) noexcept
: x_pBegin(std::addressof(rhs)), x_uSize(1)
{
}
constexpr ArrayView(const ElementT *pBegin, std::size_t uSize) noexcept
: x_pBegin(pBegin), x_uSize(uSize)
{
}
template<std::size_t kSizeT>
constexpr ArrayView(const ElementT (&rhs)[kSizeT]) noexcept
: x_pBegin(rhs), x_uSize(kSizeT)
{
}
template<std::size_t kSizeT>
constexpr ArrayView(ElementT (&rhs)[kSizeT]) noexcept
: x_pBegin(rhs), x_uSize(kSizeT)
{
}
template<StringType kTypeT,
std::enable_if_t<
std::is_same<typename StringView<kTypeT>::Char, std::remove_cv_t<ElementT>>::value,
int> = 0>
constexpr ArrayView(StringView<kTypeT> rhs) noexcept
: x_pBegin(rhs.GetData()), x_uSize(rhs.GetSize())
{
}
constexpr ArrayView(const Vector<const ElementT> &rhs) noexcept
: x_pBegin(rhs.GetData()), x_uSize(rhs.GetSize())
{
}
constexpr ArrayView(const Vector<ElementT> &rhs) noexcept
: x_pBegin(rhs.GetData()), x_uSize(rhs.GetSize())
{
}
constexpr ArrayView(std::initializer_list<const ElementT> rhs) noexcept
: x_pBegin(rhs.begin()), x_uSize(rhs.size())
{
}
constexpr ArrayView(std::initializer_list<ElementT> rhs) noexcept
: x_pBegin(rhs.begin()), x_uSize(rhs.size())
{
}
public:
constexpr const ElementT *GetBegin() const noexcept {
return x_pBegin;
}
constexpr const ElementT *GetEnd() const noexcept {
return x_pBegin + x_uSize;
}
constexpr const ElementT *GetData() const noexcept {
return x_pBegin;
}
constexpr std::size_t GetSize() const noexcept {
return x_uSize;
}
public:
explicit constexpr operator const ElementT *() const noexcept {
return GetData();
}
constexpr const ElementT &operator[](std::size_t uIndex) const noexcept {
ASSERT_MSG(uIndex < GetSize(), L"索引越界。");
return GetData();
}
};
template<class ElementT>
decltype(auto) begin(const ArrayView<ElementT> &rhs) noexcept {
return rhs.GetBegin();
}
template<class ElementT>
decltype(auto) cbegin(const ArrayView<ElementT> &rhs) noexcept {
return begin(rhs);
}
template<class ElementT>
decltype(auto) end(const ArrayView<ElementT> &rhs) noexcept {
return rhs.GetEnd();
}
template<class ElementT>
decltype(auto) cend(const ArrayView<ElementT> &rhs) noexcept {
return end(rhs);
}
}
#endif
| true |
125f683f589f31642a9f288cbe463caf1f05611c | C++ | Md-Sanaul-Haque-Shanto/Competitive-Contest-Problesm-Solutions | /PEG Judge/BlueBook - Cross Country.cpp | UTF-8 | 769 | 3.03125 | 3 | [] | no_license | /*
Bismillah Hir Rahmanir Rahim
Md Sanaul Haque Shanto
Email : mdsanaulhaqueshanto@gmail.com
Solution Date : Feb 26/17, 2:01:46 am BDT
Problems Link: https://wcipeg.com/problem/p100ex4
*/
#include <iostream>
#include <map>
#include <string>
using namespace std;
const map<string, string> descriptions {
{"MG", "midget girls"},
{"MB", "midget boys"},
{"JG", "junior girls"},
{"JB", "junior boys"},
{"SG", "senior gilrs"},
{"SB", "senior boys"}
};
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
string code;
cin >> code;
if (descriptions.count(code))
{
cout << descriptions.at(code);
}
else
{
cout << "invalid code";
}
cout << '\n';
return 0;
}
| true |
61f5b3f3c596b7e27db2619c0067483b86ce9a5b | C++ | SherifOmarAbdelAziz/ArcadeApp | /src/Shapes/Shape.h | UTF-8 | 427 | 2.625 | 3 | [] | no_license | /*
* Shape.h
*
* Created on: Feb 13, 2021
* Author: sherif
*/
#ifndef SHAPES_SHAPE_H_
#define SHAPES_SHAPE_H_
#include <vector>
#include "Vec2D.h"
using namespace std;
class Shape {
public:
virtual Vec2D GetCenterPoint() const = 0;
virtual ~Shape() {}
void MoveBy(const Vec2D &mypoint);
virtual vector<Vec2D> GetPoints() {return mPoints;}
protected:
vector<Vec2D> mPoints;
};
#endif /* SHAPES_SHAPE_H_ */
| true |
41a235f8ed97a3bbc7cbf816c461e7e508b87b09 | C++ | mstrechen/competitive-programming | /CodeForces.com/regular_rounds/#497/C.cxx | UTF-8 | 563 | 2.796875 | 3 | [
"MIT"
] | permissive |
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for(auto & i : a)
cin >> i;
sort(a.begin(), a.end());
int ans = 0;
int unused = 0;
for(auto it = a.begin(); it != a.end(); it = upper_bound(a.begin(), a.end(), *it) ){
int cnt = upper_bound(a.begin(), a.end(), *it) - it;
ans += min(unused, cnt);
unused += cnt - min(unused, cnt);
}
cout << ans;
return 0;
} | true |
bb077cd15bb84e8e722c970dd0be6a8832683325 | C++ | mugur9/cpptruths | /cpp0x/multi_inheritance.cpp | UTF-8 | 5,214 | 3.484375 | 3 | [] | no_license | #include <iostream>
void test1(void) {
class A
{
public:
virtual ~A() = default;
};
class B : public A
{
public:
virtual ~B() = default;
};
class C
{
public:
virtual ~C() = default;
};
class D : public B, public C
{
public:
virtual ~D() = default;
};
D *pd = new D();
std::cout << "pd=" << pd << "\n";
A *pa = pd; // No pointer arithmetic pa points to same location as pd.
std::cout << "pa=" << pa << "\n";
B *pb = pd; // No pointer arithmetic pb points to same location as pd.
std::cout << "pb=" << pb << "\n";
C *pc = pd;
std::cout << "pc=" << pc << "\n";
pd = static_cast<D*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
std::cout << "pd=" << pd << "\n";
pd = static_cast<D*>(pb); // No Pointer Arithmetic performed by compiler, pb and pd points to same location
std::cout << "pd=" << pd << "\n";
pd = static_cast<D*>(pc);
std::cout << "pd=" << pd << "\n";
}
void virtual_inheritance_dynamic_cast_test(void) {
class A
{
int a;
public:
virtual ~A() = default;
};
class B : public virtual A
{
int b;
public:
virtual ~B() = default;
};
class C : public virtual A
{
int c;
public:
virtual ~C() = default;
};
class D : public B, public C
{
int d;
public:
virtual ~D() = default;
};
D *pd = new D();
std::cout << "pd=" << pd << "\n";
A *pa = pd; // No pointer arithmetic pa points to same location as pd.
std::cout << "pa=" << pa << "\n";
B *pb = pd; // No pointer arithmetic pb points to same location as pd.
std::cout << "pb=" << pb << "\n";
C *pc = pd;
std::cout << "pc=" << pc << "\n";
pd = static_cast<D*>(pb); // No Pointer Arithmetic performed by compiler, pb and pd points to same location
std::cout << "b to d pd=" << pd << "\n";
pd = static_cast<D*>(pc);
std::cout << "c to d pd=" << pd << "\n";
//pd = static_cast<D*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
//pb = static_cast<B*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
//pc = static_cast<C*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
//std::cout << "pd=" << pd << "\n";
pd = dynamic_cast<D*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
//pb = static_cast<B*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
//pc = static_cast<C*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
std::cout << "a to d pd=" << pd << "\n";
void *v = pa;
pd = dynamic_cast<D*>(static_cast<A *>(v));
std::cout << "v to d pd=" << pd << "\n";
}
void test3(void) {
class Object {
public:
virtual ~Object() = default;
};
class A : public Object
{
public:
virtual ~A() = default;
};
class B : public A
{
public:
virtual ~B() = default;
};
class D : public B
{
public:
virtual ~D() = default;
};
D *pd = new D();
std::cout << "pd=" << pd << "\n";
A *pa = pd; // No pointer arithmetic pa points to same location as pd.
std::cout << "pa=" << pa << "\n";
B *pb = pd; // No pointer arithmetic pb points to same location as pd.
std::cout << "pb=" << pb << "\n";
//C *pc = pd;
//std::cout << "pc=" << pc << "\n";
pd = static_cast<D*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
std::cout << "pd=" << pd << "\n";
pd = static_cast<D*>(pb); // No Pointer Arithmetic performed by compiler, pb and pd points to same location
std::cout << "pd=" << pd << "\n";
//pd = static_cast<D*>(pc);
//std::cout << "pd=" << pd << "\n";
void *v = pd;
//Object *o = static_cast<Object *>(v);
pb = static_cast<B *>(v);
std::cout << "pb=" << pb << "\n";
}
void test4(void) {
class Object {
public:
virtual ~Object() = default;
};
class A : public virtual Object
{
public:
virtual ~A() = default;
};
class B : public A
{
public:
virtual ~B() = default;
};
class C : public virtual Object
{
public:
virtual ~C() = default;
};
class D : public B, public C {
public:
virtual ~D() = default;
};
D *pd = new D();
std::cout << "pd=" << pd << "\n";
A *pa = pd; // No pointer arithmetic pa points to same location as pd.
std::cout << "pa=" << pa << "\n";
B *pb = pd; // No pointer arithmetic pb points to same location as pd.
std::cout << "pb=" << pb << "\n";
C *pc = pd;
std::cout << "pc=" << pc << "\n";
//pd = static_cast<D*>(pa); // No Pointer Arithmetic performed by compiler, pa and pd points to same location
//std::cout << "pd=" << pd << "\n";
pd = static_cast<D*>(pb); // No Pointer Arithmetic performed by compiler, pb and pd points to same location
std::cout << "pd=" << pd << "\n";
pd = static_cast<D*>(pc);
std::cout << "pd=" << pd << "\n";
Object *o = static_cast<Object *>(pc);
void *v = o;
pd = dynamic_cast<D *>(static_cast<Object *>(o));
std::cout << "v=" << v << ", o=" << o << ", from void* pd=" << pd << "\n";
}
int main(void) {
//test1();
// virtual_inheritance_dynamic_cast_test();
//test3();
test4();
}
| true |
fc9c856c7ff45f82ac8e7525815a4d974e9ff2b3 | C++ | jafffy/VKGL | /src/OpenGL/frontend/gl_formats.cpp | UTF-8 | 32,594 | 2.5625 | 3 | [
"MIT"
] | permissive | /* VKGL (c) 2018 Dominik Witczak
*
* This code is licensed under MIT license (see LICENSE.txt for details)
*/
#include "Common/macros.h"
#include "OpenGL/frontend/gl_formats.h"
typedef struct InternalFormatData
{
OpenGL::FormatDataType data_type;
uint32_t n_components;
/* For base and compressed internal formats, "1" indicates the component is used.
* For sized internal formats, non-zero value indicates the component is used and describes the component size in bits.
*/
uint32_t component_size_r;
uint32_t component_size_g;
uint32_t component_size_b;
uint32_t component_size_a;
uint32_t component_size_depth;
uint32_t component_size_stencil;
uint32_t component_size_shared;
bool is_base_internal_format;
bool is_compressed_internal_format;
bool is_sized_internal_format;
InternalFormatData()
{
memset(this,
0,
sizeof(*this) );
}
InternalFormatData(const OpenGL::FormatDataType& in_data_type,
const uint32_t& in_n_components,
const uint32_t& in_component_size_r,
const uint32_t& in_component_size_g,
const uint32_t& in_component_size_b,
const uint32_t& in_component_size_a,
const uint32_t& in_component_size_depth,
const uint32_t& in_component_size_stencil,
const uint32_t& in_component_size_shared,
const bool& in_is_base_internal_format,
const bool& in_is_compressed_internal_format,
const bool& in_is_sized_internal_format)
:data_type (in_data_type),
n_components (in_n_components),
component_size_r (in_component_size_r),
component_size_g (in_component_size_g),
component_size_b (in_component_size_b),
component_size_a (in_component_size_a),
component_size_depth (in_component_size_depth),
component_size_stencil (in_component_size_stencil),
component_size_shared (in_component_size_shared),
is_base_internal_format (in_is_base_internal_format),
is_compressed_internal_format(in_is_compressed_internal_format),
is_sized_internal_format (in_is_sized_internal_format)
{
/* Stub */
}
} InternalFormatData;
OpenGL::PixelFormat;
static const std::unordered_map<OpenGL::InternalFormat, InternalFormatData> g_gl_internalformat_data =
{
/* Base internal formats */
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::Depth_Component, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 0, 0, 0, 0, 1, 0, 0, true, false, false)},
{OpenGL::InternalFormat::Depth_Stencil, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 0, 0, 0, 0, 1, 1, 0, true, false, false)},
{OpenGL::InternalFormat::Red, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 1, 0, 0, 0, 0, 0, 0, true, false, false)},
{OpenGL::InternalFormat::RG, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 1, 1, 0, 0, 0, 0, 0, true, false, false)},
{OpenGL::InternalFormat::RGB, InternalFormatData(OpenGL::FormatDataType::Unknown, 3, 1, 1, 1, 0, 0, 0, 0, true, false, false)},
{OpenGL::InternalFormat::RGBA, InternalFormatData(OpenGL::FormatDataType::Unknown, 4, 1, 1, 1, 1, 0, 0, 0, true, false, false)},
/* Sized internal formats */
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::R11F_G11F_B10F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 11, 11, 10, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R3_G3_B2, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 3, 3, 2, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R32I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::R8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG32I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RG8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB10, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 10, 10, 10, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB10_A2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB10_A2UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB12, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 12, 12, 12, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB32I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB4, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 4, 4, 4, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB5, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 5, 5, 5, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB5_A1, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 5, 5, 5, 1, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGB9_E5, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 9, 9, 9, 0, 0, 0, 5, false, false, true)},
{OpenGL::InternalFormat::RGBA12, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 12, 12, 12, 12, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 2, 2, 2, 2, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA32I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA4, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 4, 4, 4, 4, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::RGBA8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::SRGB8, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)},
{OpenGL::InternalFormat::SRGB8_Alpha8, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)},
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::Depth_Component16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 16, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth_Component24, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 24, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth_Component32, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth_Component32_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) },
{OpenGL::InternalFormat::Depth24_Stencil8, InternalFormatData(OpenGL::FormatDataType::UNorm_UInt, 2, 0, 0, 0, 0, 24, 8, 0, false, false, true) },
{OpenGL::InternalFormat::Depth32_Float_Stencil8, InternalFormatData(OpenGL::FormatDataType::UFloat_UInt, 2, 0, 0, 0, 0, 32, 8, 0, false, false, true) },
/* Compressed internal formats */
/* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */
{OpenGL::InternalFormat::Compressed_Red, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RG, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGB, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGB_BPTC_Signed_Float, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGB_BPTC_Unsigned_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGBA, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_RGBA_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_Signed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_Signed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_SRGB, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_SRGB_Alpha, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
{OpenGL::InternalFormat::Compressed_SRGB_Alpha_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)},
};
static const std::vector<OpenGL::InternalFormat> g_color_sized_internalformats =
{
OpenGL::InternalFormat::R11F_G11F_B10F,
OpenGL::InternalFormat::R16,
OpenGL::InternalFormat::R16_SNorm,
OpenGL::InternalFormat::R16F,
OpenGL::InternalFormat::R16I,
OpenGL::InternalFormat::R16UI,
OpenGL::InternalFormat::R3_G3_B2,
OpenGL::InternalFormat::R32F,
OpenGL::InternalFormat::R32I,
OpenGL::InternalFormat::R32UI,
OpenGL::InternalFormat::R8,
OpenGL::InternalFormat::R8_SNorm,
OpenGL::InternalFormat::R8I,
OpenGL::InternalFormat::R8UI,
OpenGL::InternalFormat::RG16,
OpenGL::InternalFormat::RG16_SNorm,
OpenGL::InternalFormat::RG16F,
OpenGL::InternalFormat::RG16I,
OpenGL::InternalFormat::RG16UI,
OpenGL::InternalFormat::RG32F,
OpenGL::InternalFormat::RG32I,
OpenGL::InternalFormat::RG32UI,
OpenGL::InternalFormat::RG8,
OpenGL::InternalFormat::RG8_SNorm,
OpenGL::InternalFormat::RG8I,
OpenGL::InternalFormat::RG8UI,
OpenGL::InternalFormat::RGB10,
OpenGL::InternalFormat::RGB10_A2,
OpenGL::InternalFormat::RGB10_A2UI,
OpenGL::InternalFormat::RGB12,
OpenGL::InternalFormat::RGB16_SNorm,
OpenGL::InternalFormat::RGB16F,
OpenGL::InternalFormat::RGB16I,
OpenGL::InternalFormat::RGB16UI,
OpenGL::InternalFormat::RGB32F,
OpenGL::InternalFormat::RGB32I,
OpenGL::InternalFormat::RGB32UI,
OpenGL::InternalFormat::RGB4,
OpenGL::InternalFormat::RGB5,
OpenGL::InternalFormat::RGB5_A1,
OpenGL::InternalFormat::RGB8,
OpenGL::InternalFormat::RGB8_SNorm,
OpenGL::InternalFormat::RGB8I,
OpenGL::InternalFormat::RGB8UI,
OpenGL::InternalFormat::RGB9_E5,
OpenGL::InternalFormat::RGBA12,
OpenGL::InternalFormat::RGBA16,
OpenGL::InternalFormat::RGBA16F,
OpenGL::InternalFormat::RGBA16I,
OpenGL::InternalFormat::RGBA16UI,
OpenGL::InternalFormat::RGBA2,
OpenGL::InternalFormat::RGBA32F,
OpenGL::InternalFormat::RGBA32I,
OpenGL::InternalFormat::RGBA32UI,
OpenGL::InternalFormat::RGBA4,
OpenGL::InternalFormat::RGBA8,
OpenGL::InternalFormat::RGBA8_SNorm,
OpenGL::InternalFormat::RGBA8I,
OpenGL::InternalFormat::RGBA8UI,
OpenGL::InternalFormat::SRGB8,
OpenGL::InternalFormat::SRGB8_Alpha8,
};
static const std::vector<OpenGL::InternalFormat> g_ds_sized_internalformats =
{
OpenGL::InternalFormat::Depth_Component16,
OpenGL::InternalFormat::Depth_Component24,
OpenGL::InternalFormat::Depth_Component32,
OpenGL::InternalFormat::Depth_Component32_Float,
OpenGL::InternalFormat::Depth24_Stencil8,
OpenGL::InternalFormat::Depth32_Float_Stencil8,
};
OpenGL::InternalFormat OpenGL::GLFormats::get_best_fit_ds_internal_format(const uint32_t& in_depth_bits,
const uint32_t& in_stencil_bits)
{
OpenGL::InternalFormat result = OpenGL::InternalFormat::Unknown;
uint32_t result_n_depth_bits = 0;
uint32_t result_n_stencil_bits = 0;
vkgl_assert(in_depth_bits != 0 ||
in_stencil_bits != 0);
for (const auto& current_internalformat : g_ds_sized_internalformats)
{
const auto& internalformat_data_iterator = g_gl_internalformat_data.find(current_internalformat);
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
const auto& internalformat_data = internalformat_data_iterator->second;
if ((in_depth_bits == 0 && internalformat_data.component_size_depth != 0) ||
(in_stencil_bits == 0 && internalformat_data.component_size_stencil != 0) )
{
continue;
}
if ((in_depth_bits != 0 && internalformat_data.component_size_depth == 0) ||
(in_stencil_bits != 0 && internalformat_data.component_size_stencil == 0) )
{
continue;
}
if (result == OpenGL::InternalFormat::Unknown)
{
result = current_internalformat;
result_n_depth_bits = internalformat_data.component_size_depth;
result_n_stencil_bits = internalformat_data.component_size_stencil;
}
else
{
const auto current_depth_diff = abs(static_cast<int32_t>(internalformat_data.component_size_depth) - static_cast<int32_t>(in_depth_bits) );
const auto current_stencil_diff = abs(static_cast<int32_t>(internalformat_data.component_size_stencil) - static_cast<int32_t>(in_stencil_bits) );
const auto result_depth_diff = abs(static_cast<int32_t>(result_n_depth_bits) - static_cast<int32_t>(in_depth_bits) );
const auto result_stencil_diff = abs(static_cast<int32_t>(result_n_stencil_bits) - static_cast<int32_t>(in_stencil_bits) );
if (current_depth_diff + current_stencil_diff < result_depth_diff + result_stencil_diff)
{
result = current_internalformat;
result_n_depth_bits = internalformat_data.component_size_depth;
result_n_stencil_bits = internalformat_data.component_size_stencil;
}
}
}
vkgl_assert(result != OpenGL::InternalFormat::Unknown);
return result;
}
OpenGL::FormatDataType OpenGL::GLFormats::get_format_data_type_for_non_base_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
OpenGL::FormatDataType result = OpenGL::FormatDataType::Unknown;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.data_type;
}
return result;
}
uint32_t OpenGL::GLFormats::get_n_components_for_sized_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
uint32_t result = 0;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.n_components;
}
return result;
}
bool OpenGL::GLFormats::get_per_component_bit_size_for_sized_internal_format(const OpenGL::InternalFormat& in_format,
uint32_t* out_rgba_bit_size_ptr,
uint32_t* out_ds_size_ptr,
uint32_t* out_shared_size_ptr)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
out_rgba_bit_size_ptr[0] = internalformat_data_iterator->second.component_size_r;
out_rgba_bit_size_ptr[1] = internalformat_data_iterator->second.component_size_g;
out_rgba_bit_size_ptr[2] = internalformat_data_iterator->second.component_size_b;
out_rgba_bit_size_ptr[3] = internalformat_data_iterator->second.component_size_a;
out_ds_size_ptr [0] = internalformat_data_iterator->second.component_size_depth;
out_ds_size_ptr [1] = internalformat_data_iterator->second.component_size_stencil;
*out_shared_size_ptr = internalformat_data_iterator->second.component_size_shared;
result = true;
}
return result;
}
bool OpenGL::GLFormats::is_base_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.is_base_internal_format;
}
return result;
}
bool OpenGL::GLFormats::is_compressed_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.is_compressed_internal_format;
}
return result;
}
bool OpenGL::GLFormats::is_sized_internal_format(const OpenGL::InternalFormat& in_format)
{
const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format);
bool result = false;
vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() );
if (internalformat_data_iterator != g_gl_internalformat_data.end() )
{
result = internalformat_data_iterator->second.is_sized_internal_format;
}
return result;
}
| true |
5fc596fdd10eae2f1c6730095673bcbd54b0a01a | C++ | dh434/leetcode | /tree/938. 二叉搜索树的范围和.cpp | UTF-8 | 901 | 3.703125 | 4 | [] | no_license | /*
给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例 1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
提示:
树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。
*/
// 都为闭区间
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root == NULL)
return 0;
int root_val = root->val;
int sum = 0;
if(root->val >= L && root->val <= R)
sum += root_val;
if(root_val >= L) sum += rangeSumBST(root->left, L, R);
if(root_val <= R ) sum += rangeSumBST(root->right, L, R);
return sum;
}
}; | true |
15c95b9787eee18a2731f01e704de527381d7963 | C++ | MultivacX/leetcode2020 | /algorithms/hard/1793. Maximum Score of a Good Subarray.h | UTF-8 | 2,052 | 3.15625 | 3 | [
"MIT"
] | permissive | // 1793. Maximum Score of a Good Subarray
// https://leetcode.com/problems/maximum-score-of-a-good-subarray/
// Runtime: 296 ms, faster than 100.00% of C++ online submissions for Maximum Score of a Good Subarray.
// Memory Usage: 179.1 MB, less than 100.00% of C++ online submissions for Maximum Score of a Good Subarray.
class Solution {
public:
int maximumScore(vector<int>& nums, int k) {
const int n = nums.size();
if (n == 1) return nums[0];
// [i, ..., x, ..., j]
// nums[x] = min(nums[i ... j])
// nums[i - 1] < nums[x] > nums[j + 1]
// score[i, j] = nums[x] * (j - i + 1)
vector<int> left_less(n, -1);
deque<int> left_bound; left_bound.push_front(0);
for (int i = 1; i < n; ++i) {
if (nums[left_bound.front()] >= nums[i]) {
left_less[i] = -1;
left_bound.clear();
left_bound.push_front(i);
} else {
while (nums[left_bound.back()] >= nums[i])
left_bound.pop_back();
left_less[i] = left_bound.back();
left_bound.push_back(i);
}
}
int ans = left_less[n - 1] + 1 <= k ? nums[n - 1] * (n - left_less[n - 1] - 1) : 0;
deque<int> right_bound; right_bound.push_front(n - 1);
for (int i = n - 2; i >= 0; --i) {
int right_less = n;
if (nums[right_bound.front()] >= nums[i]) {
right_bound.clear();
right_bound.push_front(i);
} else {
while (nums[right_bound.back()] >= nums[i])
right_bound.pop_back();
right_less = right_bound.back();
right_bound.push_back(i);
}
if (left_less[i] + 1 <= k && k <= right_less - 1) {
int score = nums[i] * (right_less - left_less[i] - 1);
if (ans < score) ans = score;
}
}
return ans;
}
}; | true |
d280576e1ce4b2f5c8b0912736dbe4965d126ca4 | C++ | gstonge/spreading_CR | /src/io_data.cpp | UTF-8 | 2,132 | 3.40625 | 3 | [
"MIT"
] | permissive | /**
* \file io_data.cpp
* \brief functions definition for input/output data for networks
* \author Guillaume St-Onge
* \version 1.0
* \date 07/02/2018
*/
#include <io_data.hpp>
using namespace std;
namespace net
{//start of namespace net
/**
* \brief Output edge list to a file
* \param[in] path path name to the file
* \param[in] edge_list vector of pair representing the edge list
*/
void output_edge_list(string path, vector<pair<NodeLabel, NodeLabel> >
edge_list)
{
ofstream outStream;
outStream.open(path, ios::out);
for (int i = 0; i < edge_list.size(); i++)
{
outStream << edge_list[i].first << " " << edge_list[i].second << endl;
}
outStream.close();
}
/**
* \brief Input the edge list from file
* \param[in] path path name to the file
*/
vector<pair<NodeLabel, NodeLabel> > input_edge_list(string path)
{
ifstream in_stream;
in_stream.open(path, ios::in);
string line;
vector<pair<NodeLabel, NodeLabel> > edge_list;
while(getline(in_stream,line))
{
pair<NodeLabel, NodeLabel> edge;
stringstream line_stream(line);
line_stream >> edge.first >> edge.second;
edge_list.push_back(edge);
}
in_stream.close();
return edge_list;
}
/**
* \brief Input the degree distribution
*
* \param[in] path path name to the file
*/
vector<double> input_degree_distribution(string path)
{
ifstream in_stream;
in_stream.open(path, ios::in);
string line;
vector<double> degree_distribution;
while(getline(in_stream,line))
{
double pk;
stringstream line_stream(line);
line_stream >> pk;
degree_distribution.push_back(pk);
}
in_stream.close();
return degree_distribution;
}
/**
* \fn vector<unsigned int> input_degree_sequence(string path)
* \brief Input the degree sequence
*
* \param[in] path path name to the file
*/
vector<size_t> input_degree_sequence(string path)
{
ifstream in_stream;
in_stream.open(path, ios::in);
string line;
vector<size_t> degree_sequence;
while(getline(in_stream,line))
{
size_t k;
stringstream line_stream(line);
line_stream >> k;
degree_sequence.push_back(k);
}
in_stream.close();
return degree_sequence;
}
}//end of namespace net | true |
49df26d32db5ea0bf26a38614ebb040682f01eb1 | C++ | StandNotAlone/ACM | /王子超的codeforce/2020.1.22Codeforces Round #615(Div.3)E(思维).cpp | UTF-8 | 4,283 | 2.59375 | 3 | [] | no_license | #include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<fstream>
#include<string>
#include<vector>
#include<cmath>
#include<queue>
#include<map>
#include<set>
//#include<bits/stdc++.h>
#define INF 0x7f7f7f7f //2139062143
#define INF1 0x3f3f3f3f //1061109567
#define INF2 2147483647
#define llINF 9223372036854775807
#define pi 3.141592653589793//23846264338327950254
#define pb push_back
#define ll long long
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
//ifstream f1(".txt");
//ofstream f2(".txt");
//ios::sync_with_stdio(false);
using namespace std;
#define local
#ifdef local
#endif
const int maxn=2e5+10;
//比赛的时候还是思维过于死板
//好吧思路确实挺难想的..
//题意为给定一个n*m的数字矩阵,要求你通过多少次操作后使得这个矩阵按照从1到n*m的自然顺序,从左到右,从上到下在矩阵内排列好
//你能进行的操作一是将某一列整体上移一位,操作二是将任意一个数改变成为你希望变成的任意一个数
//每一列是独立的,对每一列计算最少需要进行的操作数,累加便是ans
//而针对每一列怎么计算最少需要的操作数呢
//当时想到的就是很朴素的做法,对该列作0到n-1次的整体上移操作,分别计算每次上移操作后位置符合的数的个数x,再进行n-x次变换数字操作即可
//但是这种朴素做法的时间复杂度是O(n*n*m)明显是超时的,当时怎么都跳不出对整列进行上移操作后再计算的惯性思维
//这里其实一个思考的关键点在于要认识到对于某一列,进行相同次数操作一的方案,操作一和操作二的先后执行顺序对最后的效果是没有影响的,也就是最后操作次数是相等的
//认识到了这一点之后,我们就可以先通过找寻这一列的n个数字,它们如果经过一定次数的操作一后可以到达一个它符合排列条件的位置的话,我们记录下这个数字需要经过几次操作一可以达到这个位置
//这样的话经过O(n)的复杂度我们便计算出了对于这一列,进行0--n-1次(i)操作一后有多少个(x)数字是已经满足要求练度,那么还要对这一列的n-x个数字进行操作二
//这一列的总操作次数便是n-x+i次
//然后这个方案的最后一个关键点就是如何确定某个数字能否在经过一定次数操作一后能到达符合的位置,并且进行操作一的次数又是多少
//可以观察到,对于第j列来说,每一个数字减去j后都可以被m整除,并且商+1便是这个数应该在的位置,通过这一点我们就可以进行判断和计算了
vector<int>field[maxn];//这里要用vector不然开maxn^2爆内存,题目说了n*m不会超过2*10^5
int sum[maxn]; //sum[i]存储对于这一列,进行i次上移操作后有几个数字已经符合条件
int main()
{
ios::sync_with_stdio(false);
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
field[i].pb(0);
for(int j=1;j<=m;j++)
{
int x;
cin>>x;
field[i].pb(x);
}
}
int ans=0;
for(int j=1;j<=m;j++)
{
int now=INF; //now存储当前列所需最小操作数
for(int i=0;i<n;i++) //对sum数组清零操作,注意这里不可以用memset
sum[i]=0; //sum数组大小是maxn,而m的最大情况也是maxn,最糟糕的情况会变成10^10级
for(int i=1;i<=n;i++)
{
if((field[i][j]-j)%m==0&&field[i][j]<=n*m)//前半部分判断fidld[i][j]能否在一定次数上移操作后达到一个满足的位置,后半部分判断它的值是否满足在n*m内这个条件
{
sum[(i-(field[i][j]-j)/m-1+n)%n]++;//(field[i][j]-j)/m+1为field[i][j]应该在的位置的行数,与原来的行数相减便是需要进行的上移次数
} //由于可能会计算出负数,所以加一个n后再对n取模
}
for(int i=0;i<n;i++)
now=min(now,i+n-sum[i]); //得到从0次到n-1次上移操作所需次数中最小的次数,加到最后的ans上
ans+=now;
}
cout<<ans<<endl;
}
| true |
3f46b8aec62f58a2781e343beb9295080413e87e | C++ | tyrowang/CC | /lru-cache.cc | UTF-8 | 1,364 | 3.359375 | 3 | [
"MIT"
] | permissive | struct Node{
int key;
int value;
Node(int k,int v){key=k;value=v;}
};
class LRUCache{
public:
// the list.remove is O(n), so the map is neccessary to store the point to the list.
map<int,list<Node*>::iterator> cache_map;
list<Node*> cache_list;
int c;
LRUCache(int capacity) {
c=capacity;
}
int get(int key) {
map<int,list<Node*>::iterator>::iterator it=cache_map.find(key);
if(it==cache_map.end()){
return -1;
}else{
cache_list.push_front(*(it->second));
cache_list.erase(it->second);
it->second=cache_list.begin();
return (*(it->second))->value;
}
}
void set(int key, int value) {
map<int,list<Node*>::iterator>::iterator it=cache_map.find(key);
if(it!=cache_map.end()){
cache_list.push_front(*(it->second));
cache_list.erase(it->second);
it->second=cache_list.begin();
(*(it->second))->value=value;
}else{
if(cache_map.size()>=c){
cache_map.erase(cache_list.back()->key);
delete cache_list.back();
cache_list.pop_back();
}
Node* n=new Node(key, value);
cache_list.push_front(n);
cache_map[key]=cache_list.begin();
}
}
}; | true |
92af78eafa66d878e6a65c6cb14a2569a840c353 | C++ | Franco1010/ACM-ICPC | /COJ/1136.cpp | UTF-8 | 1,157 | 2.65625 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | #include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <stack>
using namespace std;
vector<long long int>primos;
long long l;
vector<bool> p(1000000,true);
void criba(){
for (int i=2; i<1000000; i++) {
if (p[i]) {
for (int j=i+i; j<1000000; j+=i) {
p[j]=false;
}
}
}
for (int i=2; i<1000000; i++) {
if (p[i]) {
primos.push_back(i);
}
}
}
bool isPrime(long long int x){
if(x==1)return false;
long int r= sqrt(x);
if (x>1000000) {
for (int i=0; i<l; i++) {
if (primos[i]>r) {
return true;
}
while (x%primos[i]==0) {
return false;
}
}
}else return p[x];
return true;
}
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
criba();
l=primos.size();
long long int c,a,b,i;
cin>>c;
while (c--) {
cin>>a>>b;
for (i=a;i<=b; i++) {
if (isPrime(i)) {
cout<<i<<'\n';
}
}cout<<'\n';
}
return 0;
}
| true |
03973bcae7a654c516a88f71a77cc94952cb1758 | C++ | hy-eom/Algorithm | /BOJ/11022.cpp | UTF-8 | 352 | 3.15625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int input;
cin >> input;
int* a = new int[input];
int* b = new int[input];
for (int i = 0; i < input; i++) {
cin >> a[i] >> b[i];
}
for (int i = 0; i < input; i++)
{
cout << "Case #" << i + 1 << ": " << a[i] << " + " << b[i] << " = " << a[i] + b[i] << endl;;
}
return 0;
} | true |
dcede4a4ebfd9dca96fb315dd6dcc3ec12d8c138 | C++ | paperjuice/Cpp---References | /const_usage.cpp | UTF-8 | 796 | 3.625 | 4 | [] | no_license |
class Test{
public:
void function_1() const
{
//because the function is const, memeber variables can't
//m_number += 1;
}
int function_1(const int& a)
{
//the reference is constant and therefore it cannot be changed
//a += 2;
return a;
}
private:
int m_number = 1;
};
int main()
{
const int a = 2; //we promise the compiler the value won't be changed after initialisation
const int b = 5;
const int* ptr_a = &a; //address can change but value cannot
ptr_a = &b;
int x = 4;
int y = 2;
int* const ptr_b = &x; //address cannot change but the value can
*ptr_b = y;
const int* const ptr_c = &x; //address and value cannot changes
return 0;
}
| true |
81fa68d09304c338a04da3a867f2a865d46dafcd | C++ | hitwlh/leetcode | /301_Remove_Invalid_Parentheses/solution1.cpp | UTF-8 | 889 | 3.28125 | 3 | [] | no_license | class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
dfs(s, 0, ')');
return ret;
}
private:
void dfs(string s, int last, char c){
int ch = 0;
for(int i = 0; i < s.length(); i++){
if(s[i] != '(' && s[i] != ')') continue;
s[i] == c ? ch++ : ch--;
if(ch <= 0) continue;
for(int j = last; j <= i; j++){
if(s[j] == c && (j == last || s[j-1] != c)){
dfs(s.substr(0, j) + s.substr(j+1), j, c);
}
}
return;//这个return容易自己写的时候漏掉了!!!
}
reverse(s.begin(), s.end());
if(c == ')'){
dfs(s, 0, '(');
return;//这个return容易自己写的时候漏掉了!!!
}
ret.push_back(s);
}
vector<string> ret;
}; | true |
ef1e4ff735dab4ea57388a5fb2d63f86ebab014f | C++ | HimanshuGunjal10/CPP-Programs | /Trees/MaxWidthOfTree.cpp | UTF-8 | 1,332 | 3.875 | 4 | [] | no_license | /*
* Program to get the max width of a Binary Tree
*/
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *left, *right;
Node(int val)
{
this->data = val;
this->left = nullptr;
this->right = nullptr;
}
};
int getHeight(Node* node)
{
if(node == nullptr)
return 0;
Node* curr = node;
int lheight, rheight;
if(curr)
{
lheight = 1+ getHeight(curr->left);
rheight = 1+ getHeight(curr->right);
}
return (lheight<rheight)? lheight : rheight;
}
int getWidth(Node* node, int i)
{
if(node == nullptr)
return 0;
if(i == 1)
return 1;
else
return getWidth(node->left, i-1) + getWidth(node->right,i-1);
}
int getMaxWidth(Node* node)
{
if(node == nullptr)
return 0;
int height = getHeight(node);
//cout << "height = " << height;
int maxWidth = 0;
int width = 0;
for(int i=1; i<=height; i++)
{
width = getWidth(node, i);
if(width>maxWidth)
maxWidth = width;
}
return maxWidth;
}
int main()
{
Node *node = new Node(5);
node->left = new Node(3);
node->left->left = new Node(1);
node->left->right = new Node(2);
node->right = new Node(6);
node->right->right = new Node(8);
node->right->left = new Node(7);
node->right->right->right=new Node(9);
cout << "Width of the tree is: " << getMaxWidth(node);
printf("\nLa fin");
return 0;
}
| true |
a97c46a2e3da35115e6e819e8960960c46316200 | C++ | intellhave/geocam | /Deprecated/unix/topology/triangulation.cpp | UTF-8 | 5,801 | 3.421875 | 3 | [] | no_license | /**************************************************************
Class: Triangulation
Author: Alex Henniges, Tom Williams, Mitch Wilson
Version: July 16, 2008
**************************************************************/
#include "triangulation/triangulation.h" // class's header file
#include <cstdlib>
#include <map>
#include <algorithm>
#include <vector>
#include <iostream>
map<int, Vertex> Triangulation::vertexTable;
map<int, Edge> Triangulation::edgeTable;
map<int, Face> Triangulation::faceTable;
map<int, Tetra> Triangulation::tetraTable;
// class constructor
Triangulation::Triangulation(){}
// class destructor
Triangulation::~Triangulation(){}
void Triangulation::putVertex(int key, Vertex v){
vertexTable.insert(pair<int, Vertex>(key, v));
}
void Triangulation::putEdge(int key, Edge v){
edgeTable.insert(pair<int, Edge>(key, v));
}
void Triangulation::putFace(int key, Face v){
faceTable.insert(pair<int, Face>(key, v));
}
void Triangulation::putTetra(int key, Tetra v){
tetraTable.insert(pair<int, Tetra>(key, v));
}
bool Triangulation::containsVertex(int key){
map<int, Vertex>::iterator vit;
for(vit = vertexTable.begin(); vit != vertexTable.end(); vit++){
if(vit->first == key)
return true;
}
return false;
}
bool Triangulation::containsEdge(int key)
{
map<int, Edge>::iterator eit;
for(eit = edgeTable.begin(); eit != edgeTable.end(); eit++)
{
if(eit->first == key)
return true;
}
return false;
}
bool Triangulation::containsFace(int key)
{
map<int, Face>::iterator fit;
for(fit = faceTable.begin(); fit != faceTable.end(); fit++)
{
if(fit->first == key)
return true;
}
return false;
}
bool Triangulation::containsTetra(int key)
{
map<int, Tetra>::iterator tit;
for(tit = tetraTable.begin(); tit != tetraTable.end(); tit++)
{
if(tit->first == key)
return true;
}
return false;
}
int Triangulation::greatestVertex()
{
int greatest = 0;
map<int, Vertex>::iterator vit;
for(vit = vertexTable.begin(); vit != vertexTable.end(); vit++)
{
if(vit->first > greatest)
greatest = vit->first;
}
return greatest;
}
int Triangulation::greatestEdge()
{
int greatest = 0;
map<int, Edge>::iterator eit;
for(eit = edgeTable.begin(); eit != edgeTable.end(); eit++)
{
if(eit->first > greatest)
greatest = eit->first;
}
return greatest;
}
int Triangulation::greatestFace()
{
int greatest = 0;
map<int, Face>::iterator fit;
for(fit = faceTable.begin(); fit != faceTable.end(); fit++)
{
if(fit->first > greatest)
greatest = fit->first;
}
return greatest;
}
int Triangulation::greatestTetra()
{
int greatest = 0;
map<int, Tetra>::iterator tit;
for(tit = tetraTable.begin(); tit != tetraTable.end(); tit++)
{
if(tit->first > greatest)
greatest = tit->first;
}
return greatest;
}
void Triangulation::eraseVertex(int key)
{
map<int, Vertex>::iterator vit;
for(vit = vertexTable.begin(); vit != vertexTable.end(); vit++)
{
vit->second.removeVertex(key);
}
map<int, Edge>::iterator eit;
for(eit = edgeTable.begin(); eit != edgeTable.end(); eit++)
{
eit->second.removeVertex(key);
}
map<int, Face>::iterator fit;
for(fit = faceTable.begin(); fit != faceTable.end(); fit++)
{
fit->second.removeVertex(key);
}
map<int, Tetra>::iterator tit;
for(tit = tetraTable.begin(); tit != tetraTable.end(); tit++)
{
tit->second.removeVertex(key);
}
vertexTable.erase(key);
}
void Triangulation::eraseEdge(int key)
{
map<int, Vertex>::iterator vit;
for(vit = vertexTable.begin(); vit != vertexTable.end(); vit++)
{
vit->second.removeEdge(key);
}
map<int, Edge>::iterator eit;
for(eit = edgeTable.begin(); eit != edgeTable.end(); eit++)
{
eit->second.removeEdge(key);
}
map<int, Face>::iterator fit;
for(fit = faceTable.begin(); fit != faceTable.end(); fit++)
{
fit->second.removeEdge(key);
}
map<int, Tetra>::iterator tit;
for(tit = tetraTable.begin(); tit != tetraTable.end(); tit++)
{
tit->second.removeEdge(key);
}
edgeTable.erase(key);
}
void Triangulation::eraseFace(int key)
{
map<int, Vertex>::iterator vit;
for(vit = vertexTable.begin(); vit != vertexTable.end(); vit++)
{
vit->second.removeFace(key);
}
map<int, Edge>::iterator eit;
for(eit = edgeTable.begin(); eit != edgeTable.end(); eit++)
{
eit->second.removeFace(key);
}
map<int, Face>::iterator fit;
for(fit = faceTable.begin(); fit != faceTable.end(); fit++)
{
fit->second.removeFace(key);
}
map<int, Tetra>::iterator tit;
for(tit = tetraTable.begin(); tit != tetraTable.end(); tit++)
{
tit->second.removeFace(key);
}
faceTable.erase(key);
}
void Triangulation::eraseTetra(int key)
{
map<int, Vertex>::iterator vit;
for(vit = vertexTable.begin(); vit != vertexTable.end(); vit++)
{
vit->second.removeTetra(key);
}
map<int, Edge>::iterator eit;
for(eit = edgeTable.begin(); eit != edgeTable.end(); eit++)
{
eit->second.removeTetra(key);
}
map<int, Face>::iterator fit;
for(fit = faceTable.begin(); fit != faceTable.end(); fit++)
{
fit->second.removeTetra(key);
}
map<int, Tetra>::iterator tit;
for(tit = tetraTable.begin(); tit != tetraTable.end(); tit++)
{
tit->second.removeTetra(key);
}
tetraTable.erase(key);
}
void Triangulation::resetTriangulation()
{
vertexTable.clear();
edgeTable.clear();
faceTable.clear();
tetraTable.clear();
}
| true |
a9d91c77af9f7799f3beda8af7d155d874ef23a8 | C++ | atrin-hojjat/CompetetiveProgramingCodes | /ICPC/AUT2018_pre3/K.cpp | UTF-8 | 470 | 2.625 | 3 | [] | no_license | #include <iostream>
#define int long long
using namespace std;
int32_t main(){
int n,k;
int cnt = 0;
while(cin >> n){
cnt++;
cin >> k;
k -= n + 1;
cout << "Case #" << cnt << ": ";
if (k <= n){
cout << k << endl;
continue;
}
int md = k % (n - 1);
if (md != n - 2) cout << md + 1 << endl;
else {
int di = k / (n - 1);
if (di % 2) cout << n << endl;
else cout << n - 1 << endl;
}
}
}
| true |
8e901b4f432ab135903ae7f7db2c450576f350b2 | C++ | morymobile/algos | /stl/stl_sort_compare.cpp | UTF-8 | 411 | 3.328125 | 3 | [] | no_license | #include <algorithm>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
bool comparator(const int &a, const int&b) {
return a < b;
}
int main() {
vector<int> nums;
nums.push_back(3);
nums.push_back(7);
nums.push_back(-1);
nums.push_back(-4);
sort(nums.begin(), nums.end(), comparator);
cout << "sorted: " << is_sorted(nums.begin(), nums.end());
}
| true |
3b51e783a1bd5cdc79d4e6e3eb499320bb77f655 | C++ | CoderDXQ/Brush-Algorithm-problem | /合法括号序列判断1.cpp | UTF-8 | 511 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
string A;
int n;
// write code here
stack<char> st;
for(int i=0;i<A.length();i++){
if(A[i]!='(' && A[i]!=')') return false;
else{
if(A[i]=='(')st.push(A[i]);
if(A[i]==')'){
if(st.empty()) return false;
else st.pop();
}
}
}
if(!st.empty()) return false;
return true;
}
| true |
4de31e4ceb4b72cf9ca1a9c7cf1cafa8f9c4c585 | C++ | Sudhir-yadav1999/Array_cpp | /pair_sum.cpp | UTF-8 | 2,071 | 4.125 | 4 | [] | no_license | --------------------------------------------------------------------------
Given a sorted and rotated array, find if there is a pair with a given sum
---------------------------------------------------------------------------
Given an array that is sorted and then rotated around an unknown point.
Find if the array has a pair with a given sum ‘x’.
It may be assumed that all elements in the array are distinct.
Examples :
Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16
Output: true
There is a pair (6, 10) with sum 16
Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 35
Output: true
There is a pair (26, 9) with sum 35
Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 45
Output: false
There is no pair with sum 45.
#include<bits/stdc++.h>
#include <stdio.h>
using namespace std;
int pairsum(int arr[],int n,int sum)
{
int i;
for(i=0;i<n;i++)
{
if(arr[i+1]<arr[i])
{
break;
}
}
int smaller=(i+1)%n; //mod is used go check that next element is not the end of array ,to continue program if its so to adjust it to starting of array again
int larger=i;
while(larger!=smaller)
{
if(arr[larger]+arr[smaller]== sum)
{
cout<<"Pair are : ("<<arr[smaller]<<","<<arr[larger]<<")"<<endl;
return sum;
}
if(arr[larger]+arr[smaller] < sum)
{
smaller=(smaller+1)%n;
}
else
{
larger=(n+larger-1)%n;
}
}
return -1;
}
int main()
{
int sum=16;
int arr[]={11,15,6,8,9,10};
int size=sizeof(arr)/sizeof(arr[0]);
cout<<"The pair sum of the sorted and rotated array"<<" sum is "<<sum<<endl;
int val=pairsum(arr,size,sum);
if(val!=-1)
{
cout<<"Two values are there with pair sum ::"<<sum<<endl;
}
else
{
cout<<"Pair sum is not present in the array ::"<<endl;
}
return 0;
}
------------------------------------------------------------------------------------------------------
| true |
b5e2ea08cb96a4771b881570defa44c4459c01f2 | C++ | rahul799/leetcode_problems | /Trees/Tricky Important/Maximum Path Sum between 2 Leaf Nodes .cpp | UTF-8 | 3,129 | 3.84375 | 4 | [] | no_license |
Maximum Path Sum between 2 Leaf Nodes
Hard Accuracy: 49.92% Submissions: 57229 Points: 8
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.
Example 1:
Input :
3
/ \
4 5
/ \
-10 4
Output: 16
Explanation :
Maximum Sum lies between leaf node 4 and 5.
4 + 4 + 3 + 5 = 16.
Example 2:
Input :
-15
/ \
5 6
/ \ / \
-8 1 3 9
/ \ \
2 -3 0
/ \
4 -1
/
10
Output : 27
Explanation:
The maximum possible sum from one leaf node
to another is (3 + 6 + 9 + 0 + -1 + 10 = 27)
Your Task:
You dont need to read input or print anything. Complete the function maxPathSum() which takes root node as input parameter and returns the maximum sum between 2 leaf nodes.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(Height of Tree)
// C/C++ program to find maximum path sum in Binary Tree
#include<bits/stdc++.h>
using namespace std;
// A binary tree node
struct Node
{
int data;
struct Node* left, *right;
};
// A utility function to allocate a new node
struct Node* newNode(int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}
// This function returns overall maximum path sum in 'res'
// And returns max path sum going through root.
int findMaxUtil(Node* root, int &res)
{
//Base Case
if (root == NULL)
return 0;
// l and r store maximum path sum going through left and
// right child of root respectively
int l = findMaxUtil(root->left,res);
int r = findMaxUtil(root->right,res);
// Max path for parent call of root. This path must
// include at-most one child of root
int max_single = max(max(l, r) + root->data, root->data);
// Max Top represents the sum when the Node under
// consideration is the root of the maxsum path and no
// ancestors of root are there in max sum path
int max_top = max(max_single, l + r + root->data);
res = max(res, max_top); // Store the Maximum Result.
return max_single;
}
// Returns maximum path sum in tree with given root
int findMaxSum(Node *root)
{
// Initialize result
int res = INT_MIN;
// Compute and return result
findMaxUtil(root, res);
return res;
}
// Driver program
int main(void)
{
struct Node *root = newNode(10);
root->left = newNode(2);
root->right = newNode(10);
root->left->left = newNode(20);
root->left->right = newNode(1);
root->right->right = newNode(-25);
root->right->right->left = newNode(3);
root->right->right->right = newNode(4);
cout << "Max path sum is " << findMaxSum(root);
return 0;
}
| true |
b65591193a1248202d34e1d7f3060bd3ba8fb29a | C++ | hdt80/Augmentum | /lib/include/game/Map.h | UTF-8 | 4,040 | 3 | 3 | [
"MIT"
] | permissive | #pragma once
#include "game/Object.h"
#include <Box2D/Box2D.h>
#include <vector>
#include <string>
class Ship;
class ContactListener;
class Object;
class Map {
public:
// Ctor and dtor ///////////////////////////////////////////////////////////
// ctor
Map();
// dtor
~Map();
// Methods /////////////////////////////////////////////////////////////////
// Simulate the Map
// diff - Microseconds to simulate the Map for
void update(int diff);
// Simulate the Box2D world
// diff - Microseconds to simulate Box2D for
void updateBox2D(int diff);
// Reset the map to the default state
void reset();
// Check if the player has been killed
// returns: _gameOver
inline bool isGameOver() const { return _gameOver; }
// Set if the game is over and we should go back to the main menu
// b - Game over or not
inline void setGameOver(bool b) { _gameOver = b; }
// Get the Ship the player is using
// returns: Pointer to the ship the player controls
inline Ship* getSelected() { return _selected; }
// Get the Box2D world used by this Map
// returns: Point to the b2World used for the physics simulations
inline b2World* getWorld() { return &_world; }
// Get all Objects within a radius of a point //////////////////////////////
// Get all the Objects within a radius of a point
// t - Point to find the Objects of
// range - Radius to look around
// returns: A vector of all objects within the range of the target
std::vector<Object*> getObjectsInRange(Target* t, float range);
// Get all the Objects within a radius of a point
// x - X coord of the world
// y - Y coord of the world
// range - Radius to look around
// returns: A vector of all objects within the range of (x, y)
std::vector<Object*> getObjectsInRange(float x, float y, float range);
// Check if a collision at the point (x, y), ignoring Object o
// o - Object to ignore during checks
// x - X coord to check for a collision
// y - Y coord to check for a collision
// returns: If a collision exists at the point (x, y)
bool collisionAtPlace(Object* o, float x, float y);
// Return the Object at (x, y), ignoring Object o
// o - Object to ignore, nullptr means all objects
// x - X coord of the map
// y - Y coord of the map
// returns: Object at the point (x, y)
Object* objectAt(Object* o, float x, float y);
// Add an Object to this Map
// o - Object to add
void addObject(Object* o);
// Spawn a new Enemy of the type at the map coords (x, y)
// x - X coord of the map to spawn at
// y - Y coord of the map to spawn at
// id - What type the Enemy should be
// level - What level to spawn the Enemy at, -1 means use the distance from
// the map's origin as the level
void spawnEnemy(float x, float y, const std::string& id, int level = -1);
// Spawn a new Asteroid at the map coords (x, y)
// x - X coord of the map to spawn at
// y - Y coord of the map to spawn at
// radius - Radius of the Asteroid, in map units, not Box2D units
void spawnAsteroid(float x, float y, float radius);
// Debug methods. These are usually called thru the Console
// Print a list of all the object points and their types
void dumpObjects();
// Vars ////////////////////////////////////////////////////////////////////
// All the Objects that exist in the world
std::vector<Object*> objects;
// Object marked for removal
std::vector<Object*> toRemove;
protected:
Vector2 _origin; // (0, 0), used to calculate the distance from the middle
Ship* _selected; // Ship the player is controlling
b2World _world; // b2World used for simulations
ContactListener* _contactListener; // Contact listener for Box2D collisions
// How many times to iterate the world
int velocityIterations = 6;
int positionIterations = 2;
float b2UpdateCounter; // Ensure that the b2 world is only updated 60/sec
bool _gameOver; // If the game is over and the player has been killed
};
| true |
1dd7fbb475c6722c32a728e68132a733c62da1e7 | C++ | dodorun/Babel | /src/common/network/DataPacket.cpp | UTF-8 | 1,937 | 2.609375 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** CPP_babel_2018
** File description:
** DataPacket class
*/
#include "DataPacket.hpp"
babel::common::DataPacket::DataPacket(CommandName commandId,
const std::vector<std::string> &args) :
_commandId(commandId), _args(args)
{
}
babel::common::CommandName
babel::common::DataPacket::getCommandId() const
{
return _commandId;
}
size_t babel::common::DataPacket::getNbArgs() const
{
return _args.size();
}
void babel::common::DataPacket::setCommandId(
babel::common::CommandName commandId)
{
_commandId = commandId;
}
void babel::common::DataPacket::addArg(std::string arg)
{
_args.push_back(arg);
}
void babel::common::DataPacket::removeArg(std::string)
{
}
const std::vector<std::string> &babel::common::DataPacket::getArgs() const
{
return _args;
}
void
babel::common::DataPacket::setArgs(const std::vector<std::string> &_args)
{
DataPacket::_args = _args;
}
const std::string babel::common::DataPacket::serialize() const
{
std::string serialization;
std::string argSerialization = serializeArgs();
serialization += std::to_string(_commandId) + ARG_SEPARATOR +
argSerialization;
return serialization;
}
const std::string babel::common::DataPacket::serializeArgs() const
{
std::ostringstream vts;
if (!_args.empty()) {
std::copy(_args.begin(), _args.end() - 1,
std::ostream_iterator<std::string>(vts,
ARG_SEPARATOR));
vts << _args.back();
}
return vts.str();
}
babel::common::DataPacket
babel::common::DataPacket::deserialize(std::string serialized)
{
babel::common::DataPacket dataPacket;
std::vector<std::string> argVec;
boost::split(argVec, serialized, boost::is_any_of(ARG_SEPARATOR));
if (argVec.empty())
return dataPacket;
try {
dataPacket.setCommandId(
(babel::common::CommandName) std::stoi(argVec[0]));
} catch (std::invalid_argument &) {
return dataPacket;
}
argVec.erase(argVec.begin());
dataPacket.setArgs(argVec);
return dataPacket;
} | true |
805c6d2f110eefe7b7db0246f25da6e22cfcda63 | C++ | imanuglypanda/Programming-Class-s-Project | /main.cpp | UTF-8 | 1,053 | 3.421875 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<iomanip>
using namespace std;
void func_input(string name[5], float product[5][3], float);
void func_output(string name[5], float product[5][3]);
int main() {
string name[5];
float product[5][3], rate = 0.07f;
func_input(name, product, rate);
func_output(name, product);
return 0;
}
void func_input(string name[5], float product[5][3], float rate) {
for (int i = 0; i < 5; i++) {
cout << "Enter Product Name : ";
cin >> name[i];
cout << " price : ";
cin >> product[i][0];
product[i][1] = product[i][0] * rate;
product[i][2] = product[i][0] + product[i][1];
}
}
void func_output(string name[5], float product[5][3]) {
cout << left << setw(5) << "No." << setw(15) << "Product" << setw(15) << "price" << setw(15) << "Vat 7%" << "Net" << endl;
for (int i = 0; i < 5; i++) {
cout << fixed << setprecision(2) << left << setw(5) << i + 1 << setw(15) << name[i] << setw(15) << product[i][0] << setw(15) << product[i][1] << product[i][2] << endl;
}
} | true |
06006880857fa1f3e820e61096a2ae4e7d165c67 | C++ | ImperishableMe/codeforces-submissions | /codeforces/992/D.cpp | UTF-8 | 2,591 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef pair<int,int> PII;
typedef long long int ll;
typedef pair< ll,ll> PLL;
PLL operator+(PLL a,PLL b){ return {a.first + b.first, a.second + b.second}; }
PLL operator-(PLL a,PLL b){ return {a.first - b.first, a.second - b.second}; }
PLL operator*(PLL a,PLL b){ return {a.first * b.first, a.second * b.second}; }
PLL operator/(PLL a,PLL b){ return {a.first / b.first, a.second / b.second}; }
PLL operator%(PLL a,PLL b){ return {( b.first + a.first) % b.first, (b.second + a.second) % b.second}; }
PLL operator%(PLL a,ll b){ return {a.first % b, a.second % b} ;}
PLL operator+(PLL a,ll b){ return {a.first + b, a.second + b} ;}
PLL operator-(PLL a,ll b){ return {a.first - b, a.second - b} ;}
PLL operator*(PLL a,ll b){ return {a.first * b, a.second * b} ;}
ostream& operator<<(ostream &out,PLL a)
{
out << "( " << a.first << ", " << a.second << " )" ;
return out;
}
/*
Order Statistics Tree ( OST )
find_by_order()
takes an integer k and returns an iterator to the k'th largest element counting from zero
order_of_key()
takes an element, here an integer and returns the number of elements strictly smaller than input
*/
typedef tree<
PLL,
null_type,
less<PLL>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;
int const MOD = 1e9 + 7;
int const N = 1e5 + 10;
bool check(ll a,ll b)
{
double aa = a;
return aa * b < (double)8e18;
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
ll n,k;
cin >> n >> k;
vector < ll > v(n+1,0),ran(n+1);
for(int i = 1; i <= n; i++){
cin >> v[i] ;
ran[i] = i;
if(v[i] == 1){
if(v[i-1] == 1){
ran[i] = ran[i-1];
}
}
}
ll ans = 0;
for(int i = 1; i <= n; i++){
ll pp = 1, sum = 0;
for(int j = i; j > 0; ){
if(v[j] == 1) {
int len = (j-ran[j]+1);
if(pp % k == 0 and (pp / k - sum > 0) and (pp/k - sum) <= len)
ans++;
pp *= 1;
sum += len;
j = ran[j] - 1;
continue;
}
if(!check(pp,v[j])){
break;
}
pp *= v[j] , sum += v[j] ;
if(pp % sum == 0 and pp / sum == k) ans++;
j--;
}
}
cout << ans << endl;
return 0;
}
| true |
049b763c8d91f9a5d0502b486721dd66e8bc83dd | C++ | bhavanarj9/cpp-algorithms | /binary search(iterative).cpp | UTF-8 | 708 | 3.75 | 4 | [] | no_license | #include<iostream>
using namespace std;
int binarysearch(int a[], int n, int x){
int l = 0;
int h = n-1;
while(l<=h){
int mid = (l+h)/2;
if(a[mid] == x){
return mid;
}
else if(a[mid] < x){
l = mid + 1;
}
else{
h = mid - 1;
}
}
return -1;
}
int main(){
int a[] = {1,3,4,5,6,8,9};
int x;
int n = sizeof(a)/sizeof(a[0]);
cout<<"Enter element to be searched"<<"\n";
cin>>x;
int r = binarysearch(a, n, x);
if(r != -1){
cout<<"The element is found at index "<<r<<"\n";
}
else{
cout<<"Element not found "<<"\n";
}
return 0;
}
| true |
a3a8472c6e01ca5388c846e3fc7d6fb38bb4f120 | C++ | mateushcp/Fila-Encadeada-FIFO | /tp/src/Fila.cc | UTF-8 | 1,368 | 3.28125 | 3 | [] | no_license | #include "Fila.h"
#include <string>
using namespace std;
Fila::Fila()
{
cabeca = new No();
cauda = cabeca;
tamanho = 0;
}
Fila::~Fila()
{
if (!vazia())
{
desenfileirarElemento();
}
}
No* Fila::getCabeca()
{
return this->cabeca;
}
void Fila::setCabeca(No* aux)
{
this->cabeca = aux;
}
int Fila::obtemTamanho()
{
return tamanho;
}
void Fila::limparFila()
{
No *novo = cabeca->prox;
while (novo != NULL)
{
cabeca->prox = novo->prox;
novo = cabeca->prox;
}
cauda = cabeca;
tamanho = 0;
}
bool Fila::vazia()
{
return tamanho == 0;
}
void Fila::enfileirarElemento(string v)
{
No *novoNo = new No(v);
if (vazia())
{
cabeca = novoNo;
cauda = novoNo;
}
else
{
cauda->setProx(novoNo);
cauda = novoNo;
}
tamanho++;
}
string Fila::desenfileirarElemento()
{
string aux;
if (!vazia())
{
aux = cabeca->v;
cabeca = cabeca->obtemProx();
if (cabeca == NULL)
{
cauda = NULL;
}
}
tamanho--;
return aux;
}
void Fila::ImprimeHistorico()
{
if (tamanho > 0)
{
No *celula;
celula = cabeca;
while (celula != NULL)
{
cout << celula->obtemValor() << endl;
celula = celula->prox;
}
}
}
| true |
e22c1c8014d5d53f8dc66af0e01471d8fdda917c | C++ | KFlaga/FlagRTS | /Core/WavSound.cpp | UTF-8 | 3,495 | 2.546875 | 3 | [] | no_license | #include "WavSound.h"
#include "Array.h"
#include "Exception.h"
#define BUFFER_SIZE 4096*8
namespace FlagRTS
{
using namespace Media;
WavSound::WavSound() :
Sound()
{
_extension = Wav;
}
WavSound::WavSound(const char* name, const char* pack, const char* file) :
Sound(name, pack, file)
{
_extension = Wav;
}
WavSound::~WavSound()
{
if( _state != Unloaded )
UnloadSound();
}
void WavSound::LoadSound()
{
unsigned char* soundBuffer;
FILE* file;
if(!(file = fopen(_filename.c_str(), "rb")))
{
CastException_d((string("Could not open Wav file: ") + _filename).c_str());
return;
}
// Read file contents
char xbuffer[5];
xbuffer[4] = '\0';
char buffer32[5];
buffer32[4] = '\0';
char buffer16[3];
buffer16[2] = '\0';
// 1) Header checks
if (fread(xbuffer, sizeof(char), 4, file) != 4 || strcmp(xbuffer, "RIFF") != 0)
{
CastException_d((string("Bad format Wav file: ") + _filename).c_str());
return;
}
fread(xbuffer, sizeof(char), 4, file); // Skip 4 bytes ( size )
if (fread(xbuffer, sizeof(char), 4, file) != 4 || strcmp(xbuffer, "WAVE") != 0)
{
CastException_d((string("Bad format Wav file: ") + _filename).c_str());
return;
}
if (fread(xbuffer, sizeof(char), 4, file) != 4 || strcmp(xbuffer, "fmt ") != 0)
{
CastException_d((string("Bad format Wav file: ") + _filename).c_str());
return;
}
fread(xbuffer, sizeof(char), 4, file); // Skip 4 bytes
// Read format info
fread(buffer16, sizeof(char), 2, file);
unsigned short audioFormat;
sscanf(buffer16, "%i", &audioFormat);
// Read channels num
fread(buffer16, sizeof(char), 2, file);
unsigned short channels;
sscanf(buffer16, "%i", &channels);
// Read sample rate
fread(buffer32, sizeof(char), 4, file);
unsigned int sampleRate;
sscanf(buffer32, "%i", &sampleRate);
// Read byterate
fread(buffer32, sizeof(char), 4, file);
unsigned int byteRate;
sscanf(buffer32, "%i", &byteRate);
// Skip 2 bytes
fread(xbuffer, sizeof(char), 2, file);
// Read bits per sample
fread(buffer16, sizeof(char), 2, file);
unsigned short bitsPerSample;
sscanf(buffer16, "%i", &bitsPerSample);
// Read next 4 bytes
if (fread(xbuffer, sizeof(char), 4, file) != 4 )
{
CastException_d((string("Bad format Wav file: ") + _filename).c_str());
return;
}
if(strcmp(xbuffer,"fact") == 0) // Optional arguments to omit
{
// SKip 8 bytes and read next 4
fread(xbuffer, sizeof(char), 4, file);
fread(xbuffer, sizeof(char), 4, file);
fread(xbuffer, sizeof(char), 4, file);
}
if (strcmp(xbuffer, "data") != 0)
{
CastException_d((string("Bad format Wav file: ") + _filename).c_str());
return;
}
if(channels == 1)
_alFormat = AL_FORMAT_MONO16;
else
_alFormat = AL_FORMAT_STEREO16;
// Read remainig size of actual data
fread(buffer32, sizeof(char), 4, file);
int size;
sscanf(buffer32, "%i", &size);
// generate AL buffer
alGenBuffers(1, &_alBufferId);
CheckALError(__FUNCTION__);
// Alloc memory for sound buffer and read data
soundBuffer = (unsigned char*)std::malloc(size);
fread(soundBuffer, sizeof(char), size, file);
alBufferData(_alBufferId, _alFormat, soundBuffer, size, sampleRate);
free(soundBuffer);
fclose(file);
UpdateLength();
_state = SoundState::Loaded;
}
void WavSound::UnloadSound()
{
// Reset and delete buffer
alDeleteBuffers(1, &_alBufferId);
CheckALError(__FUNCTION__);
_state = SoundState::Unloaded;
}
} | true |
bb26fdddf15cb55dc419299b88ca284e6c23bd44 | C++ | jiry17/MaxFlash | /src/solver/solver.h | UTF-8 | 2,838 | 2.8125 | 3 | [] | no_license | #ifndef L2S_SOLVER_H
#define L2S_SOLVER_H
#include <config.h>
#include "context_maintainer.h"
#include "specification.h"
#include "minimal_context_graph.h"
typedef std::vector<DataList> StateValue;
// The main solver. It does not use any domain knowledge, and thus this part remains unchanged for different domains.
class SynthesisTask {
public:
struct VSANode;
struct VSAEdge {
Semantics* semantics;
std::vector<VSANode*> v;
double w, rule_w;
VSAEdge(const std::vector<VSANode*>& _v, Semantics* _semantics, double _rule_w): semantics(_semantics), rule_w(_rule_w), v(_v) {
updateW();
}
double updateW() {
w = rule_w;
for (auto* sub_node: v) {
w += sub_node->p;
}
return w;
}
void print();
};
struct VSANode {
std::vector<VSAEdge*> edge_list;
int state;
StateValue value;
Program* best_program;
VSANode *l, *r;
double p;
bool is_build_edge;
VSANode(int _state, const StateValue& _value, double _p):
state(_state), value(_value), best_program(nullptr), p(_p), is_build_edge(false), l(nullptr), r(nullptr) {}
VSANode(int _state, const StateValue& _value, VSANode* _l, VSANode* _r, double _p):
state(_state), value(_value), best_program(nullptr), p(_p), is_build_edge(false), l(_l), r(_r) {}
double updateP() {
if (!is_build_edge) {
return p = std::min(l->p, r->p);
}
p = -1e100;
for (auto *edge: edge_list) p = std::max(p, edge->updateW());
if (l) {
p = std::min(std::min(l->p, r->p), p);
}
return p;
}
void print();
};
private:
std::vector<Example*> example_list;
std::vector<ParamInfo*> param_info_list;
std::unordered_map<std::string, VSANode*> combined_node_map;
std::vector<std::unordered_map<std::string, VSANode*>> single_node_map;
Program* synthesisProgramFromExample();
Program* getBestProgramWithoutOup(int state);
void verifyResult(int start_state, VSANode *result);
void verifyExampleResult(VSANode* node, int example_id);
bool getBestProgramWithOup(VSANode* node, int example_id, double limit);
VSANode* initNode(int state, const StateValue& value, int example_id);
void addNewExample(Example* example);
void buildEdge(VSANode* node, int example_id);
public:
MinimalContextGraph* graph;
Specification* spec;
double value_limit;
double calculateProbability(int state, Program* program);
SynthesisTask(MinimalContextGraph* _graph, Specification* _spec): graph(_graph), spec(_spec), value_limit(-5) {
}
Program* solve();
};
#endif //L2S_SOLVER_H
| true |
64ac647045dfb1096a0571639b76bd8a5f670668 | C++ | eskerda/arduines | /sketches/gamepad_test/gamepad_test.ino | UTF-8 | 1,130 | 3.015625 | 3 | [] | no_license | /* Based on Arduino USB Joystick HID demo
* Author: Darran Hunt
*
* https://github.com/harlequin-tech/arduino-usb
*/
int PADS[][2] = {
{0,0},
{0,1},
{1,1},
{1,0},
{1,-1},
{0,-1},
{-1,-1},
{-1,0},
{-1,1},
{0,1},
{0,0}
};
int AXIS_VAL = 1;
int N_PADS = sizeof(PADS) / (sizeof(int)*2);
struct {
int8_t x;
int8_t y;
uint8_t buttons;
} joyReport;
void setup();
void loop();
void setup()
{
Serial.begin(115200);
delay(5000);
}
void loop()
{
joyReport.buttons = 0;
joyReport.x = 0;
joyReport.y = 0;
/* Make the pad do a clockwise barrel roll */
for (int i = 0; i < N_PADS; i++){
joyReport.x = PADS[i][0] * AXIS_VAL;
joyReport.y = PADS[i][1] * - AXIS_VAL;
Serial.write((uint8_t *)&joyReport, 4);
delay(250);
}
/* Press every combination ever of buttons
* That is.. button per bit, everything from
* 0x00 to 0x0F
*/
for (int i = 0; i <= 0x0F; i++){
joyReport.buttons = i;
Serial.write((uint8_t *)&joyReport, 4);
delay(250);
}
delay(1000);
}
| true |
630a432a93decd3f13d6cc536d5df8e175b46b30 | C++ | MilanFIN/TrainGame | /TrainGame/TrainGame/obstaclelogic.h | UTF-8 | 3,906 | 2.875 | 3 | [] | no_license | #ifndef OBSTACLELOGIC_H
#define OBSTACLELOGIC_H
#include <QGraphicsScene>
#include <QObject>
#include <memory>
#include <vector>
#include "obstacleinterface.h"
#include "boulder.h"
#include "traininterface.h"
#include "playertrain.h"
/**
* @brief The ObstacleLogic is responsible for handling obstacles
*/
class ObstacleLogic: public QObject
{
Q_OBJECT
public:
/**
* @brief constructor
* @param qgraphicsscene that obstacles are added into
*/
ObstacleLogic(std::shared_ptr<QGraphicsScene> scene);
/**
* @brief moves obstacles
* @param double multiplier: train specific speed multiplier
* @pre -
* @post obstacle has been moved
*/
void move(double multiplier);
/**
* @brief sets the new goalspeed for moving obstacles
* @param int newSpeed: new goalspeed
* @pre -
* @post goalspeed has been changed
*/
void setSpeed(int newSpeed);
/**
* @brief changes the direction that obstacles are moved
* @pre -
* @post goaldirection is the opposite of the previous state
*/
void changeDirection();
/**
* @brief creates a new obstacle with obstaclefactory
* @param stations: the two stations the obstacle will
* appear between, trackcode: track obstacle will appear on,
* stationNames: names of the two stations, bool harmful:
* information on if the obstacle is in danger of aitraincollision
* @pre -
* @post new obstacle has been created
*/
void spawnObstacle(QList<QString> stations, QString trackCode,
QList<QString> stationNames, bool harmful);
/**
* @brief removes obstacles nearby the player
* @param location: player's location in y axis
* @pre -
* @post nearby obstacles have been removed
*/
void removeNearbyObjects(int location);
/**
* @brief checks collision between player's train and the obstacle
* @param player's active train as a shared_ptr
* @pre player's train is in the scene
* @post colliding obstacles have been removed
* @return damage dealt to the player
*/
int checkCollision(std::shared_ptr<PlayerTrain> train); //returns amount of damage
/**
* @brief defines the maximum amount of distance in
* stations that the next obstacle should be created on
* @post maximum distance has been grown by 0.1 for the next call
* @return goal distance for the new obstacle
*/
int getNextDistance();
/**
* @brief adds the obstacle to the scene, if it should be visible
* @post next, previous: location of the player, track: track the player is on
*/
void addObstacleToScene(QString next, QString previous, QString track);
/**
* @brief returns obstacle's location and danger level as new
* values to the parameters
* @post info returned
* @param prev, next: stations the obstacle is between, harmful: danger
* level of the obstacle
*/
void getObstacleLocation(QString &prev, QString &next, bool &harmful);
/**
* @brief deals with the situation, where player has collided with an obstacle
* @pre ui has to be initialized
* @post ui informed on an update
*/
void crash();
signals:
void obstacleRemoved(int fameReward, int moneyReward);
void obstacleCreated(QString stations, QString track, QString threatLevel);
private:
//movement related
float speed_ = 0;
float goalSpeed_;
bool forward_ = true;
float previousSpeed_;
float accel_ = 0.1;
//other
std::shared_ptr<QGraphicsScene> scene_;
std::shared_ptr<ObstacleInterface> obstacle_;
bool inScene_ = false;
//stationcode
QString obstacleStartStation_;
QString obstacleEndStation_;
QString ObstacleTrackCode_;
int nextObstacleDistance_ = 20;
bool harmful_ = false;
};
#endif // OBSTACLELOGIC_H
| true |
459acd10ab48fa73dd7ec2901c0862dc1cbb7c7f | C++ | 2bjake/ds | /trie.cpp | UTF-8 | 2,667 | 3.28125 | 3 | [] | no_license | #include "trie.h"
#include <algorithm>
void Trie::insertStringInternal(std::shared_ptr<Node> node, std::string s, std::size_t strIdx){
if(strIdx < s.length()) {
std::shared_ptr<Node> &child = node->children[s[strIdx]];
if(!child) {
child.reset(new Node());
}
insertStringInternal(child, s, ++strIdx);
} else {
node->value = true;
}
}
void Trie::insertString(const std::string &s) {
if(s.empty()) return;
std::string str = s;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
insertStringInternal(root, str, 0);
}
bool Trie::hasStringInternal(std::shared_ptr<Node> node, std::string s, std::size_t strIdx) const {
std::shared_ptr<Node> matchingNode = getMatchingNode(node, s, strIdx);
return matchingNode != NULL && matchingNode->value;
}
std::shared_ptr<Trie::Node> Trie::getMatchingNode(std::shared_ptr<Node> node, std::string s, std::size_t strIdx) const {
if(strIdx < s.length()) {
auto it = node->children.find(s[strIdx]);
if(it == node->children.end()) {
return std::shared_ptr<Node>();
} else {
return getMatchingNode(it->second, s, ++strIdx);
}
} else {
return node;
}
}
bool Trie::hasString(const std::string &s) const {
if(s.empty()) return false;
std::string str = s;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return hasStringInternal(root, str, 0);
}
void Trie::getStringsInternal(std::shared_ptr<Node> node, std::vector<char> &trail, std::vector<std::string> &results) const {
if(node->value) {
results.push_back(std::string(trail.begin(), trail.end()));
}
for(auto kv : node->children) {
trail.push_back(kv.first);
getStringsInternal(kv.second, trail, results);
trail.pop_back();
}
}
std::vector<std::string> Trie::getStrings() const {
return getStrings("");
}
std::vector<std::string> Trie::getStrings(const std::string &startsWith) const {
std::string startsWithLower = startsWith;
std::transform(startsWithLower.begin(), startsWithLower.end(), startsWithLower.begin(), ::tolower);
std::shared_ptr<Node> matchingNode = getMatchingNode(root, startsWithLower, 0);
std::vector<std::string> results;
if(matchingNode == NULL) {
return results;
}
std::vector<char> trail;
getStringsInternal(matchingNode, trail, results);
if(!startsWithLower.empty()) {
std::transform(results.begin(), results.end(), results.begin(), [startsWithLower] (std::string &str) { return str.insert(0, startsWithLower); });
}
return results;
}
| true |
dfa027e9a5bc7f35bd069d98f758ded4cf6bdd44 | C++ | ddl-hust/ExerciseInBooks | /Cpp_Primer/CH13/13_27.h | UTF-8 | 624 | 3.28125 | 3 | [] | no_license | //引用计数版本 指针行为的hasptr
#include<vector>
#include<string>
using std::string;
class HasPtr{
public:
HasPtr():p(new string()),id(0),count(new size_t(1)){}
HasPtr(const HasPtr& rval)
{
p = rval.p;
id=rval.id;
++*count;
}
HasPtr& operator= (const HasPtr& rval ){
**rval.count;
if(--count==0) {delete p; delete count;}
id=rval.id;
p=rval.p;
count=rval.count;
return *this;
}
~HasPtr()
{
if(--*count)
{
delete p;
delete count;}
}
private:
string* p;
int id;
size_t* count;
}; | true |
bb890d22f1d57184e2b6c078ef2b516961a8a46c | C++ | aliemir99/Shinobi-Ketto | /ShinobiKetto/Application.cpp | UTF-8 | 4,079 | 2.5625 | 3 | [] | no_license | #include "Application.h"
#include "State.h"
#include "StateIdentifiers.h"
#include "GameState.h"
#include "TitleState.h"
#include "PauseState.h"
#include "MenuState.h"
#include "GameOverState.h"
#include "CharacterSelectionState.h"
#include "MapSelectionState.h"
#include "OptionsState.h"
#include "HowToPlayState.h"
#include "RoundOverState.h"
const sf::Time Application::TimePerFrame = sf::seconds(1.f / 60.f);
Application::Application()
: window(sf::VideoMode(1920, 1080), "Shinobi Ketto")
, textures()
, fonts()
, player()
, music()
, sounds()
, stateStack(State::Context(window, textures, fonts, player, music, sounds, p1Char, p2Char, backGroundFilePath, platformFilePath, hudLeftFilePath, hudRightFilePath))
, statsText()
, statsUpdateTime()
, statsNumFrames(0)
, skicon()
{
window.setKeyRepeatEnabled(false);
fonts.load(FontID::Main, "Media/GROBOLD.ttf");
textures.load(TextureID::TitleScreen, "Media/Textures/Fight/shinobiKettoTitle.png");
textures.load(TextureID::MenuScreen, "Media/Textures/Fight/menu.png");
textures.load(TextureID::CharacterSelectionScreen, "Media/Textures/Fight/characterSelection.png");
textures.load(TextureID::MapSelectionScreen, "Media/Textures/Fight/mapSelection.png");
textures.load(TextureID::OptionsScreen, "Media/Textures/Fight/options.png");
textures.load(TextureID::HowToPlayScreen, "Media/Textures/Fight/howtoplay.jpg");
textures.load(TextureID::p1Controls, "Media/Textures/Fight/p1Controls.png");
textures.load(TextureID::p2Controls, "Media/Textures/Fight/p2Controls.png");
statsText.setFont(fonts.get(FontID::Main));
statsText.setPosition(5.f, 5.f);
statsText.setCharacterSize(10u);
registerStates();
stateStack.pushState(StateID::Title);
skicon.loadFromFile("Media/Textures/Fight/skicon64x64.png");
window.setIcon(64, 64, skicon.getPixelsPtr());
music.setVolume(25.f);
}
void Application::run()
{
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (window.isOpen()) {
sf::Time elapsedTime = clock.restart();
timeSinceLastUpdate += elapsedTime;
while (timeSinceLastUpdate > TimePerFrame) {
timeSinceLastUpdate -= TimePerFrame;
processInput();
update(TimePerFrame);
if (stateStack.isEmpty())
window.close();
}
updateStatistics(elapsedTime);
render();
}
}
void Application::processInput()
{
sf::Event event;
while (window.pollEvent(event))
{
stateStack.handleEvent(event);
if (event.type == sf::Event::Closed) {
window.close();
}
}
}
void Application::update(sf::Time dt)
{
stateStack.update(dt);
}
void Application::render()
{
window.clear();
stateStack.draw();
window.setView(window.getDefaultView());
window.draw(statsText);
window.display();
}
void Application::updateStatistics(sf::Time et)
{
statsUpdateTime += et;
statsNumFrames += 1;
if (statsUpdateTime >= sf::seconds(1.0f)) {
statsText.setString(
"Frames/ Second = " + std::to_string(statsNumFrames) + "\n" +
"Time/ Update = " + std::to_string(statsUpdateTime.asMicroseconds() / statsNumFrames) + "us"
);
statsUpdateTime -= sf::seconds(1.0f);
statsNumFrames = 0;
}
}
void Application::registerStates()
{
stateStack.registerState<TitleState>(StateID::Title);
stateStack.registerState<MenuState>(StateID::Menu);
stateStack.registerState<OptionsState>(StateID::Options);
stateStack.registerState<HowToPlayState>(StateID::HowToPlay);
stateStack.registerState<CharacterSelectionState>(StateID::CharacterSelection);
stateStack.registerState<MapSelectionState>(StateID::MapSelection);
stateStack.registerState<GameState>(StateID::Game);
stateStack.registerState<PauseState>(StateID::Pause);
stateStack.registerState<RoundOverState>(StateID::RoundOver);
stateStack.registerState<GameOverState>(StateID::GameOver);
}
| true |
cd6d9294575ba79413c677039c5173a14621bd8e | C++ | hilleri123/OOP_cpp_shapkin | /2lab/3lab.cpp | UTF-8 | 1,743 | 3.5 | 4 | [] | no_license |
#include <iostream>
class Collection
{
public:
explicit Collection(std::size_t i = 1) : _buf(new int[i]), _size(i)
{}
virtual void put(int ) = 0;
virtual int take() = 0;
virtual ~Collection()
{
delete[] _buf;
}
int get(std::size_t i) const
{
if (i >= _size)
return _buf[_size-1];
return _buf[i];
}
protected:
int* _buf;
std::size_t _size;
};
class Stack : public Collection
{
public:
explicit Stack(std::size_t i) : Collection(i), _pos(0)
{}
virtual void put(int el) override
{
if (_pos >= _size)
return ;
_buf[_pos++] = el;
}
virtual int take() override
{
if (_pos > 0)
return _buf[_pos--];
return _buf[0];
}
protected:
std::size_t _pos;
};
class Queue : public Collection
{
public:
explicit Queue(std::size_t i) : Collection(i), _pos(0), _queue_size(0)
{}
virtual void put(int el) override
{
if (_queue_size+1 >= _size)
return ;
_buf[(_pos+_queue_size++)%_size] = el;
}
virtual int take() override
{
if (_queue_size-- > 0)
return _buf[_pos++];
return _buf[0];
}
protected:
std::size_t _pos;
std::size_t _queue_size;
};
int main(int argc, char** argv)
{
const std::size_t N = 2;
const std::size_t M = 6;
Collection** array = new Collection*[N];
for (int i = 0; i < N; ++i) {
if (i < N/2)
array[i] = new Stack(M);
else
array[i] = new Queue(M);
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < 2*M; ++j) {
if (j < 2*M/3 || j > 4*M/3 || j % 3 == 1)
array[i]->put(j);
else
array[i]->take();
}
}
for (int i = 0; i < N; ++i) {
std::cout << "Collection " << i << std::endl;
for (int j = 0; j < M; ++j)
std::cout << array[i]->get(j) << " ";
std::cout << std::endl;
delete array[i];
}
delete[] array;
}
| true |
139e98d5b8447b272a21cb949fe1be3053248c83 | C++ | Rayzapper/Evolution | /Evolution/Evolution/Button.h | UTF-8 | 645 | 2.75 | 3 | [] | no_license | #ifndef RAYZAPPER_BUTTON_H
#define RAYZAPPER_BUTTON_H
#include "Entity.h"
class Button : public Entity
{
public:
Button(sf::String buttonString, sf::Font *buttonFont, short ID);
~Button();
virtual void Update(float dt, sf::Vector2i mousePosition);
virtual void Render(sf::RenderWindow *window);
virtual void SetPosition(sf::Vector2f position);
void SetID(short ID);
void SetString(sf::String newString);
bool GetMouseover();
short GetID() const;
protected:
sf::RectangleShape m_Shape;
sf::IntRect m_Hitbox;
sf::Text m_ButtonText;
sf::Font *m_Font;
sf::Vector2i m_MousePosition;
short m_ID;
bool m_Mouseover = false;
};
#endif | true |
ebee34bb2e2433601fb0d1044549fdffb089c946 | C++ | PartisanQQ/CPSC-120 | /nguyen_hw01.cpp | UTF-8 | 273 | 3.375 | 3 | [] | no_license | // Anthony Nguyen
// CPSC 120-19
// HW 01
// Bonus: Yes
// Desc: Outputs my name and age.
#include <stdio.h>
int main()
{
//Variables
int myAge = 25;
//Statement that outputs variables.
printf("Hi, I'm Anthony. I am %d years old.\n", myAge);
return 0;
} | true |
417d48accb6df63aae33bdd2571554e3eed020da | C++ | mvngr/joddy | /way.cpp | UTF-8 | 468 | 2.5625 | 3 | [] | no_license | #include "way.h"
Way::Way(){
poly_ = * new QList<QLineF>;
}
Way::Way(QList<QPointF> points):Object(points, Object::Materials::stone){
poly_ = * new QList<QLineF>;
}
QList<QLineF> *Way::getPathLine(){
return &poly_;
}
void Way::setPathLine(QList<QPointF> polygon){
for(int i = 0; i < polygon.length() - 1; i++)
poly_.push_back(QLineF(polygon[i], polygon[i+1]));
return;
}
QList<QPointF> Way::getPoints(){
return Object::getPoints();
}
| true |
cf3bd5884c75c5953cb6a48359c9093101a16a98 | C++ | zanzaney/CPP-Data-Structures | /CPP_Apna college/Untitled1.cpp | WINDOWS-1250 | 343 | 2.890625 | 3 | [] | no_license | #include<iostream>
using namespace std;
class test {
int code;
static int count;
public:
void setcode(void) {
code=++count; }
void showcode(void) {
cout<<object number:<<code<<\n;
}
};
int test::count;
int main() {
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
| true |
66dbc14dcb5cbf28054704a12fb29152d4e09f38 | C++ | hyracinth/CPPBrushUp | /RomanNumeralToInt.cpp | UTF-8 | 2,600 | 3.84375 | 4 | [] | no_license | /*
Jonah Lou
06-28-2014
Small program to convert roman numerals.
Error checking checks to make sure nothing above three repetitions.
Largest Roman Numeral accepted is C
*/
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
void printError(string myError);
int main() {
string userInput;
int userInputLen, i;
int currNum = 0, prevNum = 0, counter = 0;
int finalSum = 0;
bool errorFlag = false;
printf("This program will convert roman numerals to integers.\n");
printf("For example: VII\n");
printf("Input 'quit' to quit program\n");
//Infinite loop to allow multiple conversions
while (1) {
printf("\nPlease enter your roman numerals: ");
getline(cin, userInput);
//If desired, quit program
if(userInput == "quit")
return 0;
//Stores length to decrease run time
userInputLen = userInput.length();
//Could try enumeration but this seems simpler
for(i = 0; i < userInputLen; i++) {
switch(userInput[i]) {
case 'I': case 'i':
currNum = 1;
break;
case 'V': case 'v':
currNum = 5;
break;
case 'X': case 'x':
currNum = 10;
break;
case 'L': case 'l':
currNum = 50;
break;
case 'C': case 'c':
currNum = 100;
break;
//If there is an invalid letter here, I want to
//print an error and get a new number.
default:
errorFlag = true;
finalSum = 0;
break;
}
//If there is an error, bypass this entire section
if(!errorFlag) {
//Keep running counter to count repetition
if(prevNum == currNum)
++counter;
else
counter = 0;
//Once it hits three, print error and break out
if(counter == 3) {
printError(userInput);
break;
}
//Logic is as follows:
//If the previous number is larger than the current, then
// the prevoius addition was incorrect and needs to be undone.
// As a result, subtract it from currNum to find the correct
// number to be added.
//If the previous number is smaller, a simple add will work.
if(prevNum < currNum) {
finalSum -= prevNum;
finalSum += (currNum - prevNum);
}
else {
finalSum += currNum;
}
prevNum = currNum;
}
}
//I set finalSum to be zero if there is an error while parsing
if(finalSum == 0)
printError(userInput);
else
printf("%s is %d.\n", userInput.c_str(), finalSum);
//Reset all variables
errorFlag = false;
currNum = 0;
prevNum = 0;
finalSum = 0;
}
return 0;
}
void printError(string myError) {
printf("%s is an invalid roman numeral.", myError.c_str());
}
| true |
ba7c6a81447c61c4d0fb7078e3d12db019de9fbc | C++ | VanshikaSingh10/DataStructures-Algorithms | /DSA Crack Sheet/solutions/Merge Without Extra Space.cpp | UTF-8 | 1,969 | 4.3125 | 4 | [
"MIT"
] | permissive | /*
Merge Without Extra Space
=========================
Given two sorted arrays arr1[] of size N and arr2[] of size M. Each array is sorted in non-decreasing order. Merge the two arrays into one sorted array in non-decreasing order without using any extra space.
Example 1:
Input:
N = 4, M = 5
arr1[] = {1, 3, 5, 7}
arr2[] = {0, 2, 6, 8, 9}
Output: 0 1 2 3 5 6 7 8 9
Explanation: Since you can't use any
extra space, modify the given arrays
to form
arr1[] = {0, 1, 2, 3}
arr2[] = {5, 6, 7, 8, 9}
Example 2:
Input:
N = 2, M = 3
arr1[] = {10, 12}
arr2[] = {5, 18, 20}
Output: 5 10 12 18 20
Explanation: Since you can't use any
extra space, modify the given arrays
to form
arr1[] = {5, 10}
arr2[] = {12, 18, 20}
Your Task:
You don't need to read input or print anything. Complete the function merge() which takes the two arrays arr1[], arr2[] and their sizes n and m, as input parameters. The function does not return anything. Use the given arrays to sort and merge arr1[] and arr2[] in-place.
Note: The generated output will print all the elements of arr1[] followed by all the elements of arr[2].
Expected Time Complexity: O((n+m)*log(n+m))
Expected Auxiliary Space: O(1)
Constraints:
1 <= N, M <= 5*104
0 <= arr1i, arr2i <= 106
*/
int nextGap(int gap)
{
if (gap <= 1)
return 0;
return (gap / 2) + (gap % 2);
}
void merge(int arr1[], int arr2[], int n, int m)
{
int i, j, gap = n + m;
for (gap = nextGap(gap); gap > 0; gap = nextGap(gap))
{
// comparing elements in the first array.
for (i = 0; i + gap < n; i++)
if (arr1[i] > arr1[i + gap])
swap(arr1[i], arr1[i + gap]);
// comparing elements in both arrays.
for (j = gap > n ? gap - n : 0; i < n && j < m; i++, j++)
if (arr1[i] > arr2[j])
swap(arr1[i], arr2[j]);
if (j < m)
// comparing elements in the second array.
for (j = 0; j + gap < m; j++)
if (arr2[j] > arr2[j + gap])
swap(arr2[j], arr2[j + gap]);
}
}
| true |
1817915ec763b5eb197eab085120ee3175e1f482 | C++ | deping/OSGStretch | /Line.cpp | UTF-8 | 2,949 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
#undef max
#undef min
#include <limits>
#include "Line.h"
#include "Utility.h"
Line::Line()
: _color(0.8f, 0.8f, 0.8f, 1.f)
, _colors(new osg::Vec4Array(osg::Array::BIND_OVERALL))
, _primitiveSet(new osg::DrawArrays)
{
_colors->push_back(_color);
_colors->dirty();
setColorArray(_colors);
addPrimitiveSet(_primitiveSet);
setUseVertexBufferObjects(true);
}
Line::Line(const Line & pg, const osg::CopyOp & copyop)
: Geometry(pg, copyop)
, _color(pg._color)
, _colors(dynamic_cast<osg::Vec4Array*>(copyop(pg._colors)))
, _points(dynamic_cast<osg::Vec2Array*>(copyop(pg._points)))
, _primitiveSet(dynamic_cast<osg::DrawArrays*>(copyop(pg._primitiveSet)))
{
if (!_points->empty() && _points != pg._points)
{
_points->dirty();
}
if (!_colors->empty() && _colors != pg._colors)
{
_colors->dirty();
}
setVertexArray(_points);
setColorArray(_colors);
addPrimitiveSet(_primitiveSet);
setUseVertexBufferObjects(true);
}
Line::~Line()
{
}
bool Line::nearest(const osg::Vec2d & localPt, osg::Vec2d& nearest) const
{
if (!_points.valid() || _points->size() < 2)
return false;
double dist_2 = std::numeric_limits<double>::max();
osg::Vec2d localPt2(localPt.x(), localPt.y());
osg::Vec2d tmp;
for (size_t i = 0; i < _points->size()-1; ++i)
{
tmp = Nearest(localPt2, (*_points)[i], (*_points)[i + 1]);
auto tmp_dist_2 = (tmp - localPt2).length2();
if (tmp_dist_2 < dist_2)
{
nearest = tmp;
dist_2 = tmp_dist_2;
}
}
return true;
}
void Line::getControlPoints(std::vector<GripPoint>& points) const
{
if (!_points.valid() || _points->empty())
return;
points.resize(_points->size());
for (size_t i = 0; i < _points->size(); ++i)
{
points[i].point = (*_points)[i];
points[i].type = GripType::End;
}
}
void Line::stretch(int index, const osg::Vec2d & pos, const osgGA::GUIEventAdapter& ea)
{
(*_points)[index] = pos;
_points->dirty();
}
void Line::setPoints(osg::Vec2Array * points)
{
if (points != _points.get())
{
_points = points;
if (_points.valid())
{
setVertexArray(_points);
_points->dirty();
_primitiveSet->set(GL_LINE_STRIP, 0, _points->size());
}
}
}
void Line::setColor(const osg::Vec4 & color)
{
if (_color != color)
{
_color = color;
_colors->dirty();
}
}
osg::BoundingBox Line::computeBoundingBox() const
{
osg::BoundingBox bbox;
for (size_t i = 0; i < _points->size(); ++i)
{
bbox.expandBy(osg::Vec3((*_points)[i], 0));
}
return bbox;
}
void Line::drawImplementation(osg::RenderInfo& renderInfo) const
{
if (!_points.valid() || _points->size() < 2)
return;
osg::Geometry::drawImplementation(renderInfo);
}
| true |
5490245d7422fbc1ecfce488f081ddbfaae27ad6 | C++ | NguyenTheAn/Algorithm | /Sinh_nhi_phan.cpp | UTF-8 | 773 | 2.96875 | 3 | [] | no_license | /* thuat toan sinh nhi phan
chay tu cuoi ve dau tim phan tu bang 0 dau tien.
doi 0 thanh 1
nhung phan tu phia sau vi tri do doi thanh 0
neu khong thay so 0 nao thi ket thuc thuat toan */
#include <iostream>
using namespace std;
bool check(int a[], int n){
for (int i=0; i<n; i++){
if (a[i]==0) return false;
}
return true;
}
void in_mang(int a[], int n){
for (int i=0; i<n; i++){
cout<<a[i];
}
cout<<endl;
}
void sinhnhiphan(int a[], int n){
int i=n-1;
while(i>=0){
if (a[i]==1) i--;
if(a[i]==0) {
a[i]=1;
for (int j=i+1; j<n; j++){
a[j]=0;
}
in_mang(a, n);
i=n-1;
}
}
}
main()
{
int n;
cin>>n;
int bin[n];
for (int i=0; i<n; i++) bin[i]=0;
in_mang(bin, n);
sinhnhiphan(bin, n);
}
| true |
229723214838f41a06b0f45ed8f7cb61dee97963 | C++ | wovo/hwlib | /attic/demo/arduino-due/due-#0110-matrix-switches/main.cpp | UTF-8 | 1,833 | 2.765625 | 3 | [
"BSL-1.0"
] | permissive | #include "hwlib.hpp"
void test_dump1( hwlib::matrix_of_switches & kbd ){
for(;;){
for( int_fast8_t x = 0; x < kbd.size.x; ++x ){
for( int_fast8_t y = 0; y < kbd.size.y; ++y ){
if( kbd.switch_is_closed_at( hwlib::xy( x, y ) ) ){
hwlib::cout
<< x << "," << y
<< "\n" << hwlib::flush;
}
while( kbd.switch_is_closed_at( hwlib::xy( x, y ))) {}
}
}
}
}
void test_dump2( hwlib::matrix_of_switches & kbd ){
for(;;){
for( auto coordinates : hwlib::all( kbd.size ) ){
if( kbd.switch_is_closed_at( coordinates ) ){
hwlib::cout
<< "closed @ " << coordinates
<< "\n" << hwlib::flush;
}
while( kbd.switch_is_closed_at( coordinates ) ){}
}
}
}
int main( void ){
namespace target = hwlib::target;
// wait for the terminal emulator to start up
hwlib::wait_ms( 1'000 );
hwlib::cout << "matrix of switches demo " << "\n";
auto out0 = target::pin_oc( target::pins::a4 );
auto out1 = target::pin_oc( target::pins::a5 );
auto out2 = target::pin_oc( target::pins::a6 );
auto out3 = target::pin_oc( target::pins::a7 );
auto in0 = target::pin_in( target::pins::a0 );
auto in1 = target::pin_in( target::pins::a1 );
auto in2 = target::pin_in( target::pins::a2 );
auto in3 = target::pin_in( target::pins::a3 );
in0.pullup_enable();
in1.pullup_enable();
in2.pullup_enable();
in3.pullup_enable();
auto out_port = hwlib::port_oc_from( out0, out1, out2, out3 );
auto in_port = hwlib::port_in_from( in0, in1, in2, in3 );
auto matrix = hwlib::matrix_of_switches( out_port, in_port );
test_dump2( matrix );
} | true |
efa9e0ab8c3164e44cfd933572519c67ebe99dc2 | C++ | metrumresearchgroup/Torsten | /cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/pmx_check.hpp | UTF-8 | 5,616 | 2.609375 | 3 | [
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only"
] | permissive | #ifndef STAN_MATH_TORSTEN_PKMODEL_PMETRICSCHECK_HPP
#define STAN_MATH_TORSTEN_PKMODEL_PMETRICSCHECK_HPP
#include <stan/math/prim/err/check_greater.hpp>
#include <stan/math/prim/err/check_greater_or_equal.hpp>
#include <stan/math/prim/err/check_finite.hpp>
#include <stan/math/prim/err/check_not_nan.hpp>
#include <stan/math/prim/err/check_nonnegative.hpp>
#include <stan/math/prim/err/check_consistent_sizes.hpp>
#include <stan/math/prim/err/check_nonzero_size.hpp>
#include <stan/math/torsten/PKModel/pmxModel.hpp>
#include <stan/math/prim/err/invalid_argument.hpp>
#include <Eigen/Dense>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
namespace torsten {
/**
* Checks that the arguments the user inputs in the Torsten
* functions are valid.
*
* @tparam T0 type of scalar for time of events.
* @tparam T1 type of scalar for amount at each event.
* @tparam T2 type of scalar for rate at each event.
* @tparam T3 type of scalar for inter-dose inteveral at each event.
* @tparam T4 type of scalar for model parameters
* @tparam T5 type of scalar for bio-variability
* @tparam T6 type of scalar for lag times
* @param[in] time times of events
* @param[in] amt amount at each event
* @param[in] rate rate at each event
* @param[in] ii inter-dose interval at each event
* @param[in] evid event identity:
* (0) observation
* (1) dosing
* (2) other
* (3) reset
* (4) reset AND dosing
* @param[in] cmt compartment number at each event
* @param[in] addl additional dosing at each event
* @param[in] ss steady state approximation at each event (0: no, 1: yes)
* @param[in] pMatrix parameters at each event
* @param[in] bio-variability at each event
* @param[in] lag times at each event
* @param[in] function The name of the function for which the check is being
* performed.
* @param[in] model object that contains basic structural information about
* a compartment model.
* @return void
*
*/
template <typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6>
void pmx_check(const std::vector<T0>& time,
const std::vector<T1>& amt,
const std::vector<T2>& rate,
const std::vector<T3>& ii,
const std::vector<int>& evid,
const std::vector<int>& cmt,
const std::vector<int>& addl,
const std::vector<int>& ss,
const std::vector<std::vector<T4> >& pMatrix,
const std::vector<std::vector<T5> >& biovar,
const std::vector<std::vector<T6> >& tlag,
const char* function) {
using std::vector;
using std::string;
using Eigen::Dynamic;
using stan::math::invalid_argument;
using stan::math::check_greater_or_equal;
using stan::math::check_consistent_sizes;
using stan::math::check_finite;
using stan::math::check_not_nan;
using stan::math::check_nonnegative;
check_greater_or_equal(function, "time size", time.size(), size_t(1));
check_consistent_sizes(function, "amt", amt , "time", time);
check_consistent_sizes(function, "rate", rate , "time", time);
check_consistent_sizes(function, "evid", evid , "time", time);
check_consistent_sizes(function, "cmt", cmt , "time", time);
check_consistent_sizes(function, "ii", ii , "time", time);
check_consistent_sizes(function, "addl", addl , "time", time);
check_consistent_sizes(function, "ss", ss , "time", time);
stan::math::check_nonzero_size(function, "times", time);
check_finite(function, "time", time);
check_finite(function, "amt", amt );
check_finite(function, "rate", rate);
check_finite(function, "ii", ii );
check_not_nan(function, "time", time);
check_not_nan(function, "amt", amt );
check_not_nan(function, "rate", rate);
check_not_nan(function, "ii", ii );
check_nonnegative(function, "amt", amt );
check_nonnegative(function, "rate", rate);
check_nonnegative(function, "ii", ii );
std::string message2 = ", but must be either 1 or the same as the length of the time array: " // NOLINT
+ boost::lexical_cast<string>(time.size()) + "!";
const char* length_error2 = message2.c_str();
// TEST ARGUMENTS FOR PARAMETERS
static const char* noCheck("pmx_solve_linode");
if (strcmp(function, noCheck) != 0) {
if (!((pMatrix.size() == time.size()) || (pMatrix.size() == 1)))
invalid_argument(function, "length of the parameter (2d) array,",
pMatrix.size(), "", length_error2);
if (!(pMatrix[0].size() > 0)) invalid_argument(function,
"the number of parameters per event is", pMatrix[0].size(),
"", " but must be greater than 0!");
}
if (!((biovar.size() == time.size()) || (biovar.size() == 1)))
invalid_argument(function, "length of the biovariability parameter (2d) array,", // NOLINT
biovar.size(), "", length_error2);
if (!(biovar[0].size() > 0)) invalid_argument(function,
"the number of biovariability parameters per event is", biovar[0].size(),
"", " but must be greater than 0!");
if (!((tlag.size() == time.size()) || (tlag.size() == 1)))
invalid_argument(function, "length of the lag times (2d) array,", // NOLINT
tlag.size(), "", length_error2);
if (!(tlag[0].size() > 0)) invalid_argument(function,
"the number of lagtimes parameters per event is", tlag[0].size(),
"", " but must be greater than 0!");
}
} // torsten namespace
#endif
| true |
a56f5fe9ed825af1b2318febcc98bd63f844a908 | C++ | GrinPlusPlus/GrinPlusPlus | /src/Wallet/WalletDB/Sqlite/SqliteTransaction.h | UTF-8 | 1,031 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "SqliteDB.h"
#include <Common/Util/StringUtil.h>
#include <Wallet/WalletDB/WalletStoreException.h>
#include <Common/Logger.h>
class SqliteTransaction
{
public:
SqliteTransaction(const SqliteDB::Ptr& pDatabase)
: m_pDatabase(pDatabase), m_open(false) { }
~SqliteTransaction()
{
if (m_open) {
Rollback();
}
}
void Begin()
{
if (m_open) {
WALLET_ERROR("Tried to begin a transaction twice");
throw WALLET_STORE_EXCEPTION("Tried to begin a transaction twice.");
}
m_pDatabase->Execute("BEGIN;");
m_open = true;
}
void Commit()
{
if (!m_open) {
WALLET_ERROR("Tried to commit a closed transaction");
throw WALLET_STORE_EXCEPTION("Tried to commit a closed transaction.");
}
m_open = false;
m_pDatabase->Execute("COMMIT;");
}
void Rollback() noexcept
{
if (!m_open) {
WALLET_ERROR("Tried to rollback a closed transaction");
return;
}
m_open = false;
m_pDatabase->Execute("ROLLBACK;");
}
private:
SqliteDB::Ptr m_pDatabase;
bool m_open;
}; | true |
08078e3a192e83794673ed3e07efe35e07792c42 | C++ | Jveras0924/NYU-Bridge-HWs | /jv1558_hw10_q3.cpp | UTF-8 | 2,548 | 3.6875 | 4 | [] | no_license |
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> vector_Create_Array();
void search_Num2(vector<int> num_Vec, int num);
int main2();
int* no_Vector_Create_Array(int& arrSize);
void search_Num(int arr[], int num, int arrSize);
int main1();
int main(){
cout << "Main 1: " << endl;
//main1();
cout << "Main 2: " << endl;
main2();
}
int main2(){
vector<int> sequence;
int num;
cout << "Please enter a sequence of positive integers, each in a separate line." << endl;
cout << "End you input by typing -1: " << endl;
sequence = vector_Create_Array();
cout << "Please enter the number you would like to search: " << endl;
cin >> num;
search_Num2(sequence, num);
}
int main1(){
int *arrPtr, num, arrSize = 0;
cout << "Please enter a sequence of positive integers, each in a separate line." << endl;
cout << "End you input by typing -1: " << endl;
arrPtr = no_Vector_Create_Array(arrSize);
cout << "Please enter the number you would like to search: " << endl;
cin >> num;
search_Num(arrPtr,num, arrSize);
}
void search_Num2(vector<int> num_Vec, int num){
cout << num << " shows in lines ";
for(int i = 0; i < num_Vec.size(); i += 1){
if(num_Vec[i] == num){
cout << i + 1 << ' ';
}
}
}
vector<int> vector_Create_Array(){
vector<int> store_Sec;
int num;
bool seen_Negative_One = false;
while(seen_Negative_One == false){
cin >> num;
store_Sec.push_back(num);
if(num <= -1){
seen_Negative_One = true;
}
}
return store_Sec;
}
void search_Num(int arr[], int num, int arrSize){
cout << num << " shows in lines ";
for(int i = 0; i < arrSize -1; i += 1){
if(arr[i] == num) {
cout << i + 1;
}
}
}
int* no_Vector_Create_Array(int& arrSize){
int *newArrPtr, currentSize, currentTotalSize, num;
newArrPtr = new int[1];
currentTotalSize = 1;
currentSize = 0;
for(int i = 0; num >= 0; i += 1){
cin >> num;
newArrPtr[i] = num;
currentSize += 1;
if(currentTotalSize == currentSize){
int *tempArr;
tempArr = new int[2 * currentTotalSize];
currentTotalSize *= 2;
for(int j = 0; j < currentSize; j += 1){
tempArr[j] = newArrPtr[j];
}
delete [] newArrPtr;
newArrPtr = tempArr;
}
}
arrSize = currentSize;
return newArrPtr;
}
| true |
db5b917546ee0b9755cbad5c3c3585da39621095 | C++ | paritosh-in/mdp | /MarketDataPublisher.cpp | UTF-8 | 1,945 | 3.0625 | 3 | [] | no_license | #include "MarketDataPublisher.h"
#include <algorithm>
#include <iostream>
#include <list>
MarketDataPublisher::MarketDataPublisher(Broadcaster& broadcaster,
int maxIntervalSeconds,
int maxPriceMove,
int maxSymbolsAtTime) {
this->broadcaster = broadcaster;
this->maxIntervalSeconds = maxIntervalSeconds;
this->maxPriceMove = maxPriceMove;
this->maxSymbolsAtTime = maxSymbolsAtTime;
}
void MarketDataPublisher::updatePrice(int symbolId, double price, uint64_t secondSinceEpoch) {
#if DEBUG
std::cout << "MarketDataPublisher::updatePrice()" << std::endl;
std::cout << symbolId << " | " << price << " | " << secondSinceEpoch << std::endl;
#endif
bool shouldPublish = false;
MarketData md = mdStore.get(symbolId);
if(md.getSymbol() != -1) {
if(price >= md.getPrice() + maxPriceMove)
shouldPublish = true;
md.setPrice(price);
md.setLastUpdateTime(secondSinceEpoch);
} else {
shouldPublish = true;
md = MarketData(symbolId, price, secondSinceEpoch);
}
mdStore.put(md);
if(shouldPublish)
publish(md, secondSinceEpoch);
}
void MarketDataPublisher::onTimer(uint64_t secondSinceEpoch) {
#if DEBUG
std::cout << "MarketDataPublisher::onTimer()" << std::endl;
std::cout << secondSinceEpoch << std::endl;
#endif
std::list<MarketData> mdList = mdStore.getFirst(maxSymbolsAtTime);
std::for_each(mdList.begin(), mdList.end(), [this, secondSinceEpoch](MarketData md) {
// std::cout << md.getSymbol() << " | " << md.getLastPublishedTime() + maxIntervalSeconds << " | " << secondSinceEpoch << std::endl;
if(secondSinceEpoch >= md.getLastPublishedTime() + maxIntervalSeconds)
publish(md, secondSinceEpoch);
});
}
void MarketDataPublisher::publish(MarketData md, uint64_t currentTime) {
md.setLastPublishedTime(currentTime);
md.setLastPublishedPrice(md.getPrice());
broadcaster.broadcast(md.getSymbol(), md.getPrice());
mdStore.put(md);
mdStore.moveToLast(md.getSymbol());
}
| true |
1693600361a7de6acdadb66460bca2a68c5f4540 | C++ | Karstack-overflow/Pacman | /Pacman/Pacman.cpp | ISO-8859-1 | 2,838 | 2.71875 | 3 | [] | no_license | #include "Pacman.h"
extern Game* game;
Pacman::Pacman(QGraphicsRectItem* parent) : QGraphicsRectItem(parent) {
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(Qt::darkCyan);
setBrush(brush);
timer = new QTimer(this);
timer->setInterval(20);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(move()));
timer->start();
}
void Pacman::move() {
// Begrenzung ist noch verbesserungswrdig, da der Player nicht 100% gesteuert werden kann
QList<QGraphicsItem*> colliding_items = collidingItems();
for (int i = 0, n = colliding_items.size(); i < n; ++i) {
//Kollisionsprfung mit Wand
if (typeid(*(colliding_items[i])) == typeid(Wand)) {
if (r_Player == Left && r_Player == r_lastmove) {
return;
}
if (r_Player == Right && r_Player == r_lastmove) {
return;
}
if (r_Player == Up && r_Player == r_lastmove) {
return;
}
if (r_Player == Down && r_Player == r_lastmove) {
return;
}
if (r_Player != r_lastmove && r_lastmove == Left) {
setPos(x() + Player_speed, y());
xPos += 1;
}
if (r_Player != r_lastmove && r_lastmove == Right) {
setPos(x() - Player_speed, y());
xPos -= 1;
}
if (r_Player != r_lastmove && r_lastmove == Up) {
setPos(x(), y()+ Player_speed);
yPos += 1;
}
if (r_Player != r_lastmove && r_lastmove == Down) {
setPos(x(), y() - Player_speed);
yPos -= 1;
}
}
//Kollisionsprfung mit Gehweg mit Punkt
if (typeid(*(colliding_items[i])) == typeid(G_mP)) {
delete colliding_items[i];
game->score->erhoeen(1);
}
}
if (r_Player == Left) {
setPos(x() - Player_speed, y());
xPos -= Player_speed;
r_lastmove = Left;
}
else if (r_Player == Right) {
setPos(x() + Player_speed, y());
xPos += Player_speed;
r_lastmove = Right;
}
else if (r_Player == Up) {
setPos(x(), y() - Player_speed);
yPos -= Player_speed;
r_lastmove = Up;
}
else if (r_Player == Down) {
setPos(x(), y() + Player_speed);
yPos += Player_speed;
r_lastmove = Down;
}
}
void Pacman::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Left) {
r_Player = Left;
}
else if (event->key() == Qt::Key_Right) {
r_Player = Right;
}
else if (event->key() == Qt::Key_Up) {
r_Player = Up;
}
else if (event->key() == Qt::Key_Down) {
r_Player = Down;
}
}
| true |
31631254290c6c64c898d3833d126311dc23dcf6 | C++ | ldematte/beppe | /src/Logger.h | UTF-8 | 1,481 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | /*******************************************************************\
* Bezier Patch Editor --- Logger *
* *
* Il Log Manager serve principalmente per effettuare debug. *
* Registra i messaggi inviati con le funzioni add(..) ed addf(..) *
* in un file e li visualizza in una finestra apposita (LogWindow) *
\*******************************************************************/
#if defined (_MSC_VER) && (_MSC_VER >= 1000)
#pragma once
#endif
#ifndef _INC_LOGGER_3CB6F27A038E_INCLUDED
#define _INC_LOGGER_3CB6F27A038E_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include "LogWindow.h" // per la finestra di log
class Logger
{
public:
// Construction / destruction
// Il Logger e' un singleton
virtual ~Logger();
static inline Logger* Logger::getInstance()
{
if (!Instance) Instance = new Logger();
return Instance;
}
// Aggancia il logger a una finestra per la visualizzazione
// in tempo reale
void setLogWindow(LogWindow *l);
// Aggiunge una stringa al log
void add(const char *txt);
// Aggiunge una stringa formattata alla printf al log
void addf(const char *format, ...);
private:
// L'istanza singleton del Logger.
static Logger* Instance;
LogWindow *logWin;
FILE *out;
// Il Logger e' un singleton, non permettiamo la creazione
// diretta di istanze
Logger();
};
#endif /* _INC_LOGGER_3CB6F27A038E_INCLUDED */
| true |
a2c044904103eca581fa4ed58df23a1dd2e1c4c3 | C++ | imdew1990/algotester | /0417.cpp | UTF-8 | 1,043 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
long n, i, l;
cin >> n;
vector<long>a;
vector<long> minus;
vector<long> zero;
vector<long> plus;
for (long i = 0; i < n; i++)
{
int k; cin >> k;
a.push_back(k);
}
sort(a.begin(), a.end());
vector<long>b = a;
i = 0;
while (a.size() > 0)
{
l = a[i];
if (a[i] < 0) { a.erase(a.begin()); minus.push_back(l); }
else
if (a[i] == 0) { a.erase(a.begin()); zero.push_back(l); }
else
if (a[i] > 0) { a.erase(a.begin()); plus.push_back(l); }
}
if (zero.size() == 0 && minus.size() == 0) { cout << plus.front(); }
else if (zero.size() > 1 && minus.size() == 0) { cout << zero.front(); }
else if (zero.size() == 0)
{
if (minus.size() % 2 == 0) { if (zero.size() == 0 && plus.size() == 0) { cout << minus.front(); } else { cout << plus.front(); } }
else cout << minus.back();
}
else
if (zero.size() == 1)
{
if (minus.size() % 2 == 0) { cout << zero.front(); }
else cout << minus.front();
}
else { cout << b[0]; }
system("pause");
}
| true |
49c95f4402aa6344f7723ef099a82466ae2cb88b | C++ | GaspardQin/positionning-circle-from-stereocam | /include/circle_model.h | UTF-8 | 1,811 | 3.125 | 3 | [] | no_license | #ifndef __CIRCLE_MODEL_H__
#define __CIRCLE_MODEL_H__
#include <Eigen/Dense>
class Circle3D{
public:
Eigen::Vector4d center; //circle's center
Eigen::Vector4d plane; // circle's plane (plane * x = 0)
double radius; //radius of the circle
double score; // the quality of the detected circle
Circle3D(){
radius = 0;
score = 0;
}
Circle3D(Eigen::Vector4d& circle_center, Eigen::Vector4d& circle_plane, double circle_radius){
center = circle_center;
plane = circle_plane;
radius = circle_radius;
}
void getTransformMatrixToOrigin(Eigen::Matrix4d& transform) const{
/** get transform matrix (4x4) from circle to origin xy plane
* X_in_origin_coord = transform * X_in_circles_coord
* Attention: the rotation about z-axis is not controlled, thus the transform matrix is not unique.
* @ param transform : the 4x4 transform matrix from circle plane to x-o-y plane.
* This function implements a method proposed by https://math.stackexchange.com/questions/1956699/getting-a-transformation-matrix-from-a-normal-vector
*/
Eigen::Vector3d normal;
normal = plane.head<3>().normalized();
Eigen::Matrix3d R;
double nx_ny_norm = std::sqrt(normal(0) * normal(0) + normal(1) * normal(1));
R(0,0) = normal(1) / nx_ny_norm;
R(0,1) = -normal(0) / nx_ny_norm;
R(0,2) = 0.0;
R(1,0) = normal(0) * normal(2) / nx_ny_norm;
R(1,1) = normal(1) * normal(2) / nx_ny_norm;
R(1,2) = - nx_ny_norm;
R(2,0) = normal(0);
R(2,1) = normal(1);
R(2,2) = normal(2);
transform.setIdentity();
transform.block<3,3>(0,0) = R;
transform.block<3,1>(0,3) = -center.head(3);
}
};
#endif | true |
14fd50130ca68989fd399964c105c1a03009a108 | C++ | SmritiVashisth/spoj | /willitst.cpp | UTF-8 | 340 | 2.734375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
unsigned long long number;
cin>>number;
while(number>1){
if(number%2!=0){
break;
}
else{
number=number/2;
}
}
if(number==1){
cout<<"TAK"<<endl;
}
else{
cout<<"NIE"<<endl;
}
}
| true |
10bfb135521e560a56b95a0f2e31a71cc550e3a4 | C++ | igorternyuk/TeQtSnake | /digitaltable.h | UTF-8 | 570 | 2.5625 | 3 | [] | no_license | #ifndef DIGITALTABLE_H
#define DIGITALTABLE_H
#include <QLCDNumber>
class digitalTable : public QLCDNumber
{
Q_OBJECT
public:
static const int DEFAULT_DISPLAY_WIDTH = 120;
static const int DEFAULT_DISPLAY_HEIGHT = 120;
static const int NUM_DIGITS = 120;
digitalTable(int width = DEFAULT_DISPLAY_WIDTH, int height = DEFAULT_DISPLAY_HEIGHT,
int numDigits = NUM_DIGITS, QColor color = Qt::darkGreen,
QWidget *parent = nullptr);
public slots:
void reset();
void update(int value);
};
#endif // DIGITALTABLE_H
| true |
40df0a54979ce3311aea5fafa2c9e48f48584be5 | C++ | Sondro/Acid | /Sources/Helpers/Delegate.hpp | UTF-8 | 5,248 | 2.671875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <algorithm>
#include <functional>
#include <memory>
#include <mutex>
#include "ConstExpr.hpp"
#include "NonCopyable.hpp"
namespace acid {
template<typename>
class Delegate;
class ACID_EXPORT Observer {
public:
Observer() :
m_valid(std::make_shared<bool>(true)) {
}
virtual ~Observer() = default;
std::shared_ptr<bool> m_valid;
};
template<typename TReturnType, typename ...TArgs>
class Invoker {
public:
using ReturnType = std::vector<TReturnType>;
static ReturnType Invoke(Delegate<TReturnType(TArgs ...)> &delegate, TArgs ... params) {
std::lock_guard<std::mutex> lock(delegate.m_mutex);
ReturnType returnValues;
for (auto it = delegate.m_functions.begin(); it != delegate.m_functions.end();) {
if (it->IsExpired()) {
it = delegate.m_functions.erase(it);
continue;
}
returnValues.emplace_back((*it->m_function)(params...));
++it;
}
return returnValues;
}
};
template<typename... TArgs>
class Invoker<void, TArgs...> {
public:
using ReturnType = void;
static void Invoke(Delegate<void(TArgs ...)> &delegate, TArgs ... params) {
std::lock_guard<std::mutex> lock(delegate.m_mutex);
if (delegate.m_functions.empty()) {
return;
}
for (auto it = delegate.m_functions.begin(); it != delegate.m_functions.end();) {
if (it->IsExpired()) {
it = delegate.m_functions.erase(it);
continue;
}
it->m_function(params...);
++it;
}
}
};
template<typename TReturnType, typename ...TArgs>
class Delegate<TReturnType(TArgs ...)> {
public:
using Invoker = acid::Invoker<TReturnType, TArgs...>;
using FunctionType = std::function<TReturnType(TArgs ...)>;
using ObserversType = std::vector<std::weak_ptr<bool>>;
struct FunctionPair {
FunctionType m_function;
ObserversType m_observers;
bool IsExpired() {
for (const auto &observer : m_observers) {
if (observer.expired()) {
return true;
}
}
return false;
}
};
Delegate() = default;
virtual ~Delegate() = default;
template<typename ...KArgs>
void Add(FunctionType &&function, KArgs ...args) {
std::lock_guard<std::mutex> lock(m_mutex);
ObserversType observers;
if constexpr (sizeof...(args) != 0) {
for (const auto &arg : {args...}) {
observers.emplace_back(to_address(arg)->m_valid);
}
}
m_functions.emplace_back(FunctionPair{std::move(function), observers});
}
void Remove(const FunctionType &function) {
std::lock_guard<std::mutex> lock(m_mutex);
m_functions.erase(std::remove_if(m_functions.begin(), m_functions.end(), [function](FunctionPair &f) {
return Hash(f.m_function) == Hash(function);
}), m_functions.end());
}
template<typename ...KArgs>
void RemoveObservers(KArgs ...args) {
ObserversType removes;
if constexpr (sizeof...(args) != 0) {
for (const auto &arg : {args...}) {
removes.emplace_back(to_address(arg)->m_valid);
}
}
for (auto it = m_functions.begin(); it != m_functions.end();) {
for (auto it1 = it->m_observers.begin(); it1 != it->m_observers.end();) {
bool erase = false;
auto opt = it1->lock();
for (const auto &remove : removes) {
auto ept = remove.lock();
if (opt.get() == ept.get())
erase = true;
}
if (erase)
it1 = it->m_observers.erase(it1);
else
++it1;
}
if (it->m_observers.empty())
it = m_functions.erase(it);
else
++it;
}
}
void MoveFunctions(Delegate &from, const ObserversType &exclude = {}) {
for (auto it = from.m_functions.begin(); it < from.m_functions.end();) {
bool move = true;
for (const auto &excluded : exclude) {
auto ept = excluded.lock();
for (const auto &observer : it->m_observers) {
auto opt = observer.lock();
if (opt.get() == ept.get())
move = false;
}
}
if (move) {
std::move(from.m_functions.begin(), it, std::back_inserter(m_functions));
it = from.m_functions.erase(from.m_functions.begin(), it);
} else {
++it;
}
}
}
void Clear() {
std::lock_guard<std::mutex> lock(m_mutex);
m_functions.clear();
}
typename Invoker::ReturnType Invoke(TArgs ... args) {
return Invoker::Invoke(*this, args...);
}
Delegate &operator+=(FunctionType &&function) {
return Add(std::move(function));
}
Delegate &operator-=(const FunctionType function) {
return Remove(function);
}
typename Invoker::ReturnType operator()(TArgs ... args) {
return Invoker::Invoke(*this, args...);
}
private:
friend Invoker;
static constexpr size_t Hash(const FunctionType &function) {
return function.target_type().hash_code();
}
std::mutex m_mutex;
std::vector<FunctionPair> m_functions;
};
template<typename T>
class DelegateValue : public Delegate<void(T)>, NonCopyable {
public:
template<typename ...Args>
DelegateValue(Args ...args) :
m_value(std::forward<Args>(args)...) {
}
virtual ~DelegateValue() = default;
DelegateValue &operator=(T value) {
m_value = value;
Invoke(m_value);
return *this;
}
/**
* Access the stored value.
* @return The value.
*/
operator const T &() const noexcept { return m_value; }
const T &get() const { return m_value; }
const T &operator*() const { return m_value; }
const T *operator->() const { return &m_value; }
protected:
T m_value;
};
}
| true |
a58625b34d5d030ee0b1fb7b7f1416b4a9cf030c | C++ | gzhu-team-509/GZHU-OJ | /10/1077.cpp | UTF-8 | 498 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int n, t;
long num[3001];
bool cmp(int, int);
int main()
{
while (cin >> n)
{
for (int i = 0; i < n; i++)
{
cin >> num[i];
}
sort(&num[0], &num[n], cmp);
for (int i = 0; i < n; i++)
{
if (i) cout << " ";
cout << num[i];
}
cout << endl;
}
}
bool cmp(int a, int b)
{
return a < b;
}
| true |
a308c17c490ab600f5a45cbabc8d04ce3e94b1bf | C++ | ghostincircuit/leetcode | /combinations.cpp | UTF-8 | 500 | 2.734375 | 3 | [
"BSD-2-Clause"
] | permissive | class Solution {
public:
vector<int> tmp;
vector<vector<int> > ret;
void helper(int start, int end, int k) {
if (k == 0) {
ret.push_back(tmp);
return;
}
for (auto i = start; i <= end-k; i++) {
tmp.push_back(i+1);
helper(i+1, end, k-1);
tmp.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
helper(0, n, k);
return ret;
}
};
| true |
8f06fe072a917f1e716cf10705184e2ac8711817 | C++ | levanlinh1995/competitive_programming | /04. stack and queue/01. compiler and parser.cpp | UTF-8 | 1,477 | 3.453125 | 3 | [] | no_license | // Problem: Compilers and parsers
// Link: https://www.codechef.com/MAY14/problems/COMPILER
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <limits>
using namespace std;
int getLongPrefix(string expression) {
stack<char> S; // to save '<' character
int len = expression.size();
if (len == 0) {
return 0;
}
int lenOfLongPrefix = 0;
for (int i = 0; i < len; i++)
{
if (expression[i] == '<') {
S.push('<');
} else if (expression[i] == '>') {
if (!S.empty()) {
S.pop();
if (S.empty()) {
lenOfLongPrefix = i + 1;
}
} else {
return lenOfLongPrefix;
}
}
}
return lenOfLongPrefix;
}
int main()
{
int T;
vector<string> expressions;
// read the input
cin >> T;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // clear buffer
string line;
for (int i = 0; i < T; i++) {
getline(cin, line);
expressions.push_back(line);
}
// process
if (T == 0) {
cout << 0;
return 0;
}
vector<int> result;
for (int i = 0; i < T; i++)
{
int len = getLongPrefix(expressions[i]);
result.push_back(len);
}
// print the output
for (int i = 0; i < T; i++)
{
cout << result[i] << endl;
}
cout << endl;
return 0;
}
| true |
d678ec0866c3fbe30b40e7cad8514703aa45b6bb | C++ | engineksoftware/CS-Project | /CS-Project/CS-Project.ino | UTF-8 | 4,141 | 3.65625 | 4 | [] | no_license | #include <SoftwareSerial.h>
/*
* Converts a base-10 number into binary form, and lights the correct LEDs starting from the right.
* Used with an Arudino UNO, and 8 LEDs.
*/
/*
* Can change these to different pins.
*
* NOTE: The pins in the array is equal to the LED configuration from left to right.
* Pin 6 LED is farthest to the left, and Pin 13 LED is farthest to the right.
*/
int pins[] = {6, 7, 8, 9, 10, 11, 12, 13};
int pinIndex = 7; /* Used to select last index of pins. The pins array will never exceed 8 unless more LEDs are added. */
int pinCount = 8;
char data;
String message = "";
SoftwareSerial bt(0,1);
void setup() {
for (int x = 0; x < pinCount; x++) {
pinMode(pins[x], OUTPUT);
}
Serial.begin(9600);
bt.begin(9600);
}
void loop() {
/*
* This checks if anything has been received from the App. It reads the data, concats it into a String,
* and then stops once it reaches a '*'.
*/
if(bt.available()){
data = bt.read();
message.concat(data);
if(data == '*'){
checkMessage(message);
message = "";
bt.read();
}
}
}
/*
* Takes the message received from the App, decides which function it will need to call,
* and then passes in the data from the App.
*/
void checkMessage(String message){
if(message.substring(0,1) = '1'){
message = message.substring(1,message.length() - 1);
convert(message.toInt());
}
}
/*
* Converts num to a array of 1s and 0s.
*
* If num is greater than or equal to 2^exponent, that value can be taken from num and a 1
* can be added to the array. If not, that value can't be taken from num which means a 0
* needs to be added to the array.
*
* 1 will then be taken from exponent, so on the next iteration the next proper value
* will be compared.
*/
void convert(int num) {
int exponentMax = findExponent(num);
int exponent = exponentMax;
int arraySize = exponentMax + 1;
int binaryArray[arraySize];
/*
* Cuts the lights back off.
*/
for(int x = 0; x < pinCount; x++){
digitalWrite(pins[x], LOW);
}
for (int x = 0; x <= exponentMax; x++) {
if (num >= pow(2, exponent)) {
binaryArray[x] = 1;
num -= pow(2, exponent);
}
else {
binaryArray[x] = 0;
}
exponent -= 1;
}
light(binaryArray, arraySize);
}
/*
* Finds the highest exponent value that can be taken out of num.
*
* That same value can be used as the condition for the loop that
* assigns 1s and 0s to the binaryArray.
*/
int findExponent(int num) {
int exponent = 0;
boolean found = false;
while (found == false) {
if (pow(2, exponent) > num) {
exponent -= 1;
found = true;
} else {
exponent++;
}
}
return exponent;
}
/*
* Iterates through the binary array backwards, so that the LEDs can be lit starting from the right.
* If the value at the index of the binaryArray equals 1, a HIGH bit will be sent to the correct
* pin which will turn that LED on. If the value equals 0, a LOW bit will be sent to the correct
* pin whcih will turn that LED off.
*
* 1 will then be taken from pinIndex, so that you can move left through the array of pins.
*/
void light(int *binArray, int arraySize){
for (int x = (arraySize - 1); x >= 0; x--) {
Serial.print(binArray[x]);
if (binArray[x] == 1) {
digitalWrite(pins[pinIndex], HIGH);
} else {
digitalWrite(pins[pinIndex], LOW);
}
pinIndex -= 1;
}
pinIndex = 7;
Serial.println();
}
void twosComplement(int *binArray, int arraySize){
int newArray[8];
int index = arraySize -1;
boolean hitOne = false;
for(int x = 7; x >= 0; x--){
if(index < 0){
newArray[x] = 1;
}else
if(binArray[index] == 0 && hitOne == false){
newArray[x] = binArray[index];
}else
if(binArray[index] == 1 && hitOne == false){
newArray[x] = binArray[index];
hitOne = true;
}else
if(binArray[index] == 0 && hitOne == true){
newArray[x] = 1;
}else{
newArray[x] = 0;
}
index -= 1;
}
light(newArray, 8);
}
| true |
7170860ee5290189471c75983f3164f54bfcac7a | C++ | JayGitH/839C-language-and-data-structure | /839数据结构/c语言/839代码(来自一位2018届考研学长)/HDS/bsearch源代码.cpp | UTF-8 | 430 | 2.796875 | 3 | [] | no_license | int compare(const void *a,const void *b}{
return strcmp((char*)a,(char *b));
}
void *bsearch(void *key,void *base,size_t num,size_t width,
int (*compare)(const void *elem1,const void *elem2)){
int result;
size_t low=0,high=num,mid;
while(low<high){
mid=low+(high-low)/2;
result=compare(key,base+mid*width);
if(result<0) high=mid
else if(result>0) low=mid+1;
else return (void*)base+width*mid;
}
return NULL;
}
| true |
9eb463c2ee97a72c812e0b2e868f5715cc5d82e2 | C++ | thiagofigcosta/LS- | /ls_soma/main.cpp | UTF-8 | 2,036 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define mainID 1
#define def_n_words 10
#define def_string 100
using namespace std;
char words[def_string][def_n_words];
float args[def_n_words],result;
int id;
int idx_words=0;
char str_process[def_string];
void read(){//le as entradas
FILE *in_file;
char buf[1000];
in_file =fopen("in.txt","r");
if (!in_file)
return;
while (fgets(buf,1000, in_file)!=NULL){
strcpy(words[idx_words],buf);
idx_words++;
}
fclose(in_file);
}
void write(int arg){//escreve o resultado
switch(arg){
case -1:
//escreve erro no arquivo out
FILE *out_file;
out_file =fopen("out.txt", "w");
if (!out_file)
return;
fprintf(out_file,"%d\n",-1);
fprintf(out_file,"%s\n","error";
fclose(out_file);
break;
case 1:
//escreve o resultado
FILE *out_file;
out_file =fopen("out.txt", "w");
if (!out_file)
return;
fprintf(out_file,"%d\n",id);
fprintf(out_file,"%f\n",result);
fclose(out_file);
break;
}
}
void process(int step){//cria o arquivo do processo
memset(str_process, 0, def_string);
switch(step){
case 1:
for(int i=0;i<=idx_words;i++)
//str_process+=words[i]+"+";
//str_process[strlen(str_process)-1]='=';
//str_process+=; // resultado
break;
}
}
void calc(){//calc
result=0;
for(int i=0;i<=idx_words;i++)
result+=args[i];
process(1);
write(1);
}
void wrt_process(int step){
switch(step){
case 1:
//escreve um passo
break;
}
}
void decrypt(){//converte words para int e float
id=atoi(words[0]);
for(int i=0;i<=idx_words;i++)
args[i]=atof(words[i]);
if(id==1){
calc();
}else{
write(-1);
}
}
int main()
{
read();
return 0;
}
| true |