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
e49c1d5d419a6fa0ac43a0ae4bf97bb2acf635d8
C++
borelaknti/LOST-AND-FOUND
/hotel/reservation.cpp
UTF-8
7,777
2.59375
3
[]
no_license
#include "reservation.h" #include <QDebug> reservation::reservation() { id_client=0; num_chambre=0; prix=0; type_chambre=""; evenement=""; nombre_nuitee=0; } reservation::reservation(int a,QString b,QString c,int d,int e,QDate f,int g,QString k) { this->id_client=a; this->evenement=b; this->type_chambre=c; this->num_chambre=d; this->prix=e; this->date_a=f; this->nombre_nuitee=g; this->evenement=k; } bool reservation::supprimer(int id) { QSqlQuery query; QString res= QString::number(id); query.prepare("Delete from reservation where ID_RESERVATION = :id "); query.bindValue(":id", res); return query.exec(); } int reservation::stat(){ return 100; } int reservation::get_id_client(){return id_client;} QString reservation::get_evenement(){return evenement;} QString reservation::get_type_chambre(){return type_chambre;} QDate reservation::get_date_a(){return date_a;} int reservation::get_nombre_nuitee(){return nombre_nuitee;} int reservation::get_prix(){return prix;} int reservation::get_num_chambre(){return num_chambre;} bool reservation::ajouter() { QSqlQuery query; QSqlQuery query1,query2; QString res= QString::number(num_chambre); QString res1= QString::number(id_client); QString res2; int prixt; int prix1; int prix2; query2.prepare("select * from evenement where NOM_EVENT=:event"); query2.bindValue(":event", evenement); if (query2.exec()) { while (query2.next()) { prix2= query2.value(1).toInt(); } } query1.prepare("select * from chambre where NUM_CHAMBRE=:num_chambre"); query1.bindValue(":num_chambre", res); if (query1.exec()) { while (query1.next()) { prix1= query1.value(5).toInt(); prixt=(prix1*nombre_nuitee)+prix2; res2= QString::number(prixt); } } query.prepare("INSERT INTO reservation (ID_CLIENT,NUM_CHAMBRE, TYPE_CHAMBRE, EVENEMENT, DATE_A,NOMBRE_NUITEE,PRIX) " "VALUES (:id_client,:num_chambre, :type_chambre, :evenement,:date_a,:nbr_n,:prix)"); query.bindValue(":num_chambre", res); query.bindValue(":id_client", res1); query.bindValue(":prix", res2); query.bindValue(":type_chambre", type_chambre); query.bindValue(":evenement", evenement); query.bindValue(":date_a", date_a); query.bindValue(":nbr_n", nombre_nuitee); return query.exec(); } QSqlQueryModel * reservation::afficher1( ) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; query.prepare("select ID from client "); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("num_chambre")); return model; } QSqlQueryModel * reservation::afficher6( ) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; query.prepare("select ID_RESERVATION from reservation "); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("num_chambre")); return model; } QSqlQueryModel * reservation::afficher7( ) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; query.prepare("select NOM_EVENT from evenement "); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("nom")); return model; } QSqlQueryModel * reservation::afficher5( ) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; query.prepare("select ID_RESERVATION from reservation "); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("num_chambre")); return model; } QSqlQueryModel * reservation::afficher3(QString type) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; QString libre="LIBRE"; query.prepare("select NUM_CHAMBRE from chambre where TYPE_CHAMBRE=:type AND DISPONIBILITE=:lib"); query.bindValue(":type", type); query.bindValue(":lib", libre); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("num_chambre")); return model; } QSqlQueryModel * reservation::afficher() {QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * from reservation"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("id_reservation")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("id_client")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("date_arrivée")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("evenement")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("prix")); model->setHeaderData(5, Qt::Horizontal, QObject::tr("type_chambre")); model->setHeaderData(6, Qt::Horizontal, QObject::tr("num_chambre")); model->setHeaderData(7, Qt::Horizontal, QObject::tr("nombre de nuitée")); return model; } QSqlQueryModel * reservation::afficher2(QString tri) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; QString res= tri; if(tri=="prix_croissant") query.prepare("select * from reservation order by PRIX desc"); if(tri=="prix_decroissant") query.prepare("select * from reservation order by PRIX asc"); query.bindValue(":id", res); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("id_reservation")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("id_client")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("date_arrivée")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("evenement")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("prix")); model->setHeaderData(5, Qt::Horizontal, QObject::tr("type_chambre")); model->setHeaderData(6, Qt::Horizontal, QObject::tr("num_chambre")); model->setHeaderData(7, Qt::Horizontal, QObject::tr("nombre de nuitée")); return model; } QSqlQueryModel * reservation::afficher4(int id ) {QSqlQueryModel * model= new QSqlQueryModel(); QSqlQuery query; QString res= QString::number(id); query.prepare("select * from reservation where id_reservation = :num"); query.bindValue(":num", res); query.exec(); model->setQuery(query); model->setHeaderData(0, Qt::Horizontal, QObject::tr("id_reservation")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("id_client")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("date_arrivée")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("evenement")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("prix")); model->setHeaderData(5, Qt::Horizontal, QObject::tr("type_chambre")); model->setHeaderData(6, Qt::Horizontal, QObject::tr("num_chambre")); model->setHeaderData(7, Qt::Horizontal, QObject::tr("nombre de nuitée")); return model; } bool reservation::modifier(int num) { QSqlQuery query,query1; QString res= QString::number(num); QString res1= QString::number(num_chambre); QString res2; int prixt; int prix1; query1.prepare("select * from chambre where NUM_CHAMBRE=:num_chambre"); query1.bindValue(":num_chambre", res1); if (query1.exec()) { while (query1.next()) { prix1= query1.value(5).toInt(); prixt=prix1*nombre_nuitee; res2= QString::number(prixt); } } query.prepare("UPDATE reservation SET ID_CLIENT= :id ,DATE_A=:date,EVENEMENT=:event," "NOMBRE_NUITEE=:nb,PRIX=:prix ,NUM_CHAMBRE = :num,TYPE_CHAMBRE=:type WHERE ID_RESERVATION=:id_r ") ; query.bindValue(":id_r", res); query.bindValue(":type", type_chambre); query.bindValue(":id", id_client); query.bindValue(":date", date_a); query.bindValue(":event", evenement); query.bindValue(":prix", res2); query.bindValue(":nb", nombre_nuitee); query.bindValue(":num", num_chambre); return query.exec(); }
true
6bebc77d5ed49753c4251f95018bf37268dab2b2
C++
ammarhakim/miniwarpx
/src/lib/wxrange.cc
UTF-8
2,234
2.875
3
[]
no_license
#include "wxrange.h" WxRange::WxRange() : _rank(1), _start(new int[1]), _end(new int[1]) { _start[0] = 0; _end[0] = 0; } WxRange::WxRange(unsigned rank) : _rank(rank), _start(new int[rank]), _end(new int[rank]) { for(unsigned i=0; i<rank; ++i) { _start[i] = 0; _end[i] = 0; } } WxRange::WxRange(unsigned rank, int *shape) : _rank(rank), _start(new int[rank]), _end(new int[rank]) { for(unsigned i=0; i<rank; ++i) { _start[i] = 0; _end[i] = shape[i]-1; } } WxRange::WxRange(unsigned rank, int *start, int *end) : _rank(rank), _start(new int[rank]), _end(new int[rank]) { for(unsigned i=0; i<rank; ++i) { _start[i] = start[i]; _end[i] = end[i]; } } WxRange::WxRange(int s1, int e1) : _rank(1), _start(new int[1]), _end(new int[1]) { _start[0] = s1; _end[0] = e1; } WxRange::WxRange(int s1, int e1, int s2, int e2) : _rank(2), _start(new int[2]), _end(new int[2]) { _start[0] = s1; _end[0] = e1; _start[1] = s2; _end[1] = e2; } WxRange::WxRange(int s1, int e1, int s2, int e2, int s3, int e3) : _rank(3), _start(new int[3]), _end(new int[3]) { _start[0] = s1; _end[0] = e1; _start[1] = s2; _end[1] = e2; _start[2] = s3; _end[2] = e3; } WxRange::WxRange(int s1, int e1, int s2, int e2, int s3, int e3, int s4, int e4) : _rank(4), _start(new int[4]), _end(new int[4]) { _start[0] = s1; _end[0] = e1; _start[1] = s2; _end[1] = e2; _start[2] = s3; _end[2] = e3; _start[3] = s4; _end[3] = e4; } WxRange::WxRange(const WxRange& r) { _rank = r._rank; _start = new int[_rank]; _end = new int[_rank]; for(unsigned i=0; i<_rank; ++i) { _start[i] = r._start[i]; _end[i] = r._end[i]; } } WxRange& WxRange::operator=(const WxRange& r) { if(this==&r) return *this; delete [] _start; delete [] _end; _rank = r._rank; _start = new int[_rank]; _end = new int[_rank]; for(unsigned i=0; i<_rank; ++i) { _start[i] = r._start[i]; _end[i] = r._end[i]; } return *this; } WxRange::~WxRange() { delete [] _start; delete [] _end; }
true
29319168e5ec1555a257d14f7a15eca279106092
C++
DevMaggio/ganash2
/src/library/extension/thread-manager.cpp
UTF-8
1,965
2.953125
3
[]
no_license
#include "extension/thread-manager.h" #include <iostream> Ganash::Extension::ThreadManager::ThreadManager() : m_threads (5) { try { for (std::vector<Ganash::Extension::ThreadAbstract*>::size_type i = 0; i < m_threads.size(); ++i) { Ganash::Extension::ThreadAbstract *const progress = new Ganash::Extension::ThreadAbstract(i + 1); m_threads[i] = progress; progress->signal_finished().connect( sigc::bind<1>(sigc::mem_fun(*this, &Ganash::Extension::ThreadManager::on_progress_finished), progress)); } } catch (...) { // In your own code, you should preferably use a smart pointer // to ensure exception safety. //std::for_each(m_threads.begin(), m_threads.end(), //DeletePtr<ThreadProgress*>()); throw; } } Ganash::Extension::ThreadManager::~ThreadManager() { //std::for_each(m_threads.begin(), m_threads.end(), //DeletePtr<Ganash::Extension::ThreadAbstract*>()); } void Ganash::Extension::ThreadManager::run() { // Install a one-shot idle handler to launch the threads. Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Ganash::Extension::ThreadManager::launch_threads)); //main_loop_->run(); } void Ganash::Extension::ThreadManager::launch_threads() { std::cout << "Launching " << m_threads.size() << " threads:" << std::endl; std::for_each(m_threads.begin(), m_threads.end(), std::mem_fun(&Ganash::Extension::ThreadAbstract::launch)); } void Ganash::Extension::ThreadManager::on_progress_finished(Ganash::Extension::ThreadAbstract* thread) { thread->join(); std::cout << "Thread " << thread->id() << ": finished." << std::endl; // Quit if it was the last thread to be joined. //if (std::find_if(m_threads.begin(), m_threads.end(), //std::mem_fun(&Ganash::Extension::ThreadAbstract::unfinished)) == m_threads.end()) //{ // //main_loop_->quit(); //} }
true
7470b9e9f611f5d43a7693ac86e4975b84e4ead2
C++
kapoorp99/c-programs
/remdupl2.cpp
UTF-8
1,161
2.640625
3
[]
no_license
#include <iostream> #include <string> #include <bits/stdc++.h> #include <cstdio> using namespace std; int main(void) { int n = 0; cin>>n; for(int i = 0;i < n; i++) { string str,str1; cin>>str; cin>>str1; int len = str.length(); int len1 = str1.length(); char arr[len],arr1[len1]; strcpy(arr,str.c_str()); strcpy(arr1,str1.c_str()); for(int j = 0; j < len1;j++) { int flag = 0; for(int k = 0;k < len;k++) { if(arr1[j] == arr[k]) { flag = 1; arr[k] = '0'; } } if(flag == 1) { arr1[j] = '0'; } } for(int j = 0;j<len;j++) { if(arr[j] != '0') { cout<<arr[j]; } } for(int j = 0; j < len1;j++) { if(arr1[j] != '0') { cout<<arr1[j]; } } cout<<endl; } }
true
a9da28b9b960b53b4e1a2e715378e829e537c87b
C++
ellery85/sparselizard
/src/geometry/geotools.h
UTF-8
3,263
2.890625
3
[ "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "GPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-generic-exception", "LGPL-2.0-or-later" ]
permissive
// sparselizard - Copyright (C) 2017- A. Halbach // // See the LICENSE file for license information. Please report all // bugs and problems to <alexandre.halbach at gmail.com>. // This namespace provides tools for the geometry operations. #ifndef GEOTOOLS_H #define GEOTOOLS_H #include <vector> #include <iostream> #include <numeric> #include <cmath> #include <algorithm> #include <memory> #include "shape.h" #include "rawshape.h" #include "rawpoint.h" namespace geotools { // An implementation of acos that is safe with respect to roundoff noise on the argument: double acos(double arg); // Convert a list of point coordinates into point objects: std::vector<std::shared_ptr<rawshape>> coordstopoints(std::vector<double> coords); // Get the distance between two points: double getdistance(std::vector<double> pt1coords, std::vector<double> pt2coords); // Get the angle (in degrees) which rotates the plane defined by the 3 input points // around the x (or y) axis to bring it parallel to the y axis (or x axis). // Get the angle around the x axis with "xrot" and around the y axis with "yrot" double getplanerotation(std::string xy, std::vector<double> p1, std::vector<double> p2, std::vector<double> p3); // Rotate a vector of coordinates by alphax, alphay and alphaz degrees around the x, y and z axis respectively: void rotate(double alphax, double alphay, double alphaz, std::vector<double>* coords); // Flip the nodes in a coordinate vector (3 coordinates per node): std::vector<double> flipcoords(std::vector<double>& input); // Orient a list of line shapes to have them all pointing to the next one: std::vector<std::shared_ptr<rawshape>> orient(std::vector<std::shared_ptr<rawshape>> input); // Transform a vector of shapes into a vector of rawshapes: std::vector< std::shared_ptr<rawshape> > getrawshapes(std::vector<shape> shapes); // Transform a vector of rawshapes into a vector of shapes: std::vector<shape> getshapes(std::vector< std::shared_ptr<rawshape> > rawshapes); // Transform a vector of rawshape shared pointers to a vector of rawshape pointers: std::vector<rawshape*> getpointers(std::vector< std::shared_ptr<rawshape> > sharedptrs); // Flip the rawshape vector direction: std::vector< std::shared_ptr<rawshape> > flip(std::vector< std::shared_ptr<rawshape> > input); // Unique a list of rawshape pointers: std::vector<rawshape*> unique(std::vector<rawshape*> ptrs); // Duplicate a list of rawshapes: std::vector<std::shared_ptr<rawshape>> duplicate(std::vector<std::shared_ptr<rawshape>> input); // Concatenate lists of rawshapes: std::vector<std::shared_ptr<rawshape>> concatenate(std::vector<std::vector<std::shared_ptr<rawshape>>> input); // Get an int vector to sort a vector of rawshape pointers: void sortrawshapepointers(std::vector<rawshape*>& tosort, std::vector<int>& reorderingvector); // Append the coordinate of multiple rawshapes: std::vector<double> appendcoords(std::vector<std::shared_ptr<rawshape>> rawshapes); // Append the elements of multiple rawshapes: std::vector<std::vector<int>> appendelems(std::vector<std::shared_ptr<rawshape>> rawshapes); }; #endif
true
99374cec7cd7cb48e3be57de79e10e1a4dc2f053
C++
ArinaKhrom/practice
/2_21/2_21.cpp
UTF-8
316
2.875
3
[]
no_license
#include <iostream> using namespace std; int main() { int x, t; bool flag1 = false; bool flag2 = true; cin >> x; if (x == 0) flag1 = true; while (!flag1) { cin >> t; if (t == 0) flag1 = true; if (t < x && t != 0) flag2 = false; x = t; } if (flag2) cout << "Yes"; else cout << "No"; return 0; }
true
2fbabb11643db1346c0ed769314f69484bddc490
C++
ShivaniKaripe/cdac-ncr-work
/dsassignments/linked_lists/singleLinkedList/singleLinkedList.cpp
UTF-8
4,471
3.859375
4
[]
no_license
/*single linked list implementation*/ #include<iostream> using namespace std; struct node { int data; struct node *next; }; class SingleLL { struct node* start; public: SingleLL(); void insertFirst(int); void insertLast(int); void insertAfter(int,int ); void insertBefore(int, int); int deleteFirst(); int deleteLast(); void deleteSpecific(int); void display(); //~SingleLL(); }; SingleLL::SingleLL() { start = NULL; } void SingleLL::insertFirst(int x) { cout << "entered" << endl; struct node* temp; temp = new node; temp->data = x; if (start != NULL) { temp->next = start; start = temp; } else { temp->next = NULL; start = temp; } cout << "exit"; } void SingleLL::insertLast(int x) { struct node*temp, *cur; temp = new node; temp->data = x; temp->next = NULL; if (start != NULL) { cur = start; while (cur != NULL&&cur->next != NULL) cur = cur->next; if (cur != NULL) cur->next = temp; } else { start = temp; } } void SingleLL::insertAfter(int x, int a) { if (start != NULL) { { struct node*cur; cur = start; while (cur != NULL&&cur->data != a) cur = cur->next; if (cur != NULL) { struct node*temp; temp = new node; temp->data = x; temp->next = cur->next; cur->next = temp; } else cout << "the elemnet " << a << " not found in the list"; } } else cout << "list is empty"; } void SingleLL::insertBefore(int x, int a) { if (start != NULL) { if (start->data == a) { struct node*temp; temp = new node; temp->data = x; temp->next = start; start = temp; } else { struct node *cur; cur = start; while (cur != NULL&&cur->next != NULL&&cur->next->data != a) { cur = cur->next; } if (cur != NULL&&cur->next != NULL) { struct node *temp; temp = new node; temp->data = x; temp->next = cur->next; cur->next = temp; } else cout << "the element does not exist"; } } else cout << "list is empty"; } void SingleLL::display() { struct node *cur; cur = start; while (cur != NULL) { cout << cur->data<<endl; cur = cur->next; } } int SingleLL::deleteFirst() { int x = -999; if (start != NULL) { if (start->next == NULL) { delete start; start = NULL; } else { struct node *temp; temp = start; start = temp->next; x = temp->data; delete temp; } } else cout << "no elements present"<<endl; return x; } int SingleLL::deleteLast() { int x=-999; if (start != NULL) { if (start->next == NULL) { x = start->data; delete start; start = NULL; } else { struct node *cur; cur = start; while (cur != NULL&&cur->next != NULL&&cur->next->next != NULL) { cur = cur->next; } if (cur != NULL&&cur->next != NULL) { struct node *temp; temp = cur->next; cur->next = NULL; x = temp->data; delete temp; } else cout << "the elemnet does not exist" << endl; } } else cout << "list is empty"; return x; } int main() { SingleLL sll; int choice=0; int x, temp; while (choice < 11) { cout << "choose the desired option" << endl; cout << "1.insert at the begining" << endl; cout << "2.insert at the end" << endl; cout << "3.insert after the element" << endl; cout << "4.insert at before the element" << endl; cout << "5.delete the first element" << endl; cout << "6.delete the last element" << endl; cout << "7.delete the specific element" << endl; cout << "8.display the linked list" << endl; cout << "9.traverse backwards" << endl; cout << "10.reverse the linked list" << endl; cin >> choice; switch (choice) { case 1: cout << "enter the element to be inserted" << endl; cin >> x; sll.insertFirst(x); break; case 2: cout << "enter the element to be inserted" << endl; cin >> x; sll.insertLast(x); break; case 3: cout << "enter the element to be inserted" << endl; cin >> x; cout << "enter the element after which you want to insert" << endl; cin >> temp; sll.insertAfter(x, temp); break; case 4: cout << "enter the element to be inserted" << endl; cin >> x; cout << "enter the element before which you want to insert" << endl; cin >> temp; sll.insertBefore(x, temp); break; case 5: break; case 6: break; case 7: break; case 8: sll.display(); break; case 9: break; case 10: break; default: break; } } cout << "" << endl; }
true
6e189feba864e5ab13f8e6fc056d1380d98f45ab
C++
hsunami10/Project-Euler
/Problem 10/problem10.cpp
UTF-8
632
3.4375
3
[]
no_license
#include <iostream> #include <cmath> #include <math.h> // Problem 10 (Project Euler) using namespace std; bool IsPrime(long value) { bool prime = false; for(long i = 2; i <= ceil(sqrt(value)); i++) { if(value % i == 0) { prime = false; break; } else prime = true; } return prime; } int main() { long max = 2000000; // Starts off at 5 because of 2 and 3 is an expection long sum = 5; bool isPrime; for(long i = 5; i < max; i+=2) { // Check if prime isPrime = IsPrime(i); if(isPrime) sum += i; } cout << "Answer: " << sum << '\n'; return 0; }
true
bbeb1f11c4608e24452ddc39e76fea2e5d3c84ba
C++
donghyun3363/datastructure_project
/Assignment3/Assignment3/Mechanic.cpp
UHC
1,360
3.25
3
[]
no_license
#include "Mechanic.h" #include <iostream>// Mechanic::Mechanic(void)// { Gu = NULL; Name = NULL; pNext = NULL; dis = 0; } Mechanic::~Mechanic(void)//Ҹ { delete []Gu; delete []Name; } void Mechanic::SetMechanicGu(char *gu)// { int i=0; while(gu[i]!=NULL)//Է¹ ̸ ش i++; Gu = new char[i+1];//Ŭ ̸ŭ ޸ Ҵ Ѵ memset(Gu,NULL,i+1);//迭 ʱȭ Ѵ strcpy(Gu,gu);// Ѵ } char *Mechanic::GetMechanicGu()// ȯ { return Gu; } void Mechanic::SetMechanicName(char *name)// ̸ { int i=0; while(name[i]!=NULL)//Է¹ ̸ ش i++; Name = new char[i+1];//Ŭ ̸ŭ ޸ Ҵ Ѵ memset(Name,NULL,i+1);//迭 ʱȭ Ѵ strcpy(Name,name);// Ѵ } char *Mechanic::GetMechanicName()// ̸ ȯ { return Name; } void Mechanic::SetMechanicNext(Mechanic *node)// 縦 Ų { pNext = node; } Mechanic *Mechanic::GetMechanicNext()// 縦 ȯѴ { return pNext; } void Mechanic::SetDistence(int num)// Ÿ Ѵ { dis = num; } int Mechanic::GetDistence()// Ÿ ȯѴ { return dis; }
true
c465eb82794bcc8ad718fb0c3a1c6beb94cf7c91
C++
AmateurECE/Networking
/source/Networking/NetworkAddress.cpp
UTF-8
2,835
2.90625
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// // NAME: NetworkAddress.cpp // // AUTHOR: Ethan D. Twardy <edtwardy@mtu.edu> // // DESCRIPTION: Implementation of the NetworkAddress class. // // CREATED: 04/17/2020 // // LAST EDITED: 05/01/2020 //// #include <Networking/NetworkAddress.h> #include <arpa/inet.h> #include <system_error> #define str(x) _str(x) #define _str(x) #x Networking::NetworkAddress::NetworkAddress(struct sockaddr_in address) : m_address{address} {} Networking::NetworkAddress::NetworkAddress(unsigned int ipHostOrder, unsigned short portHostOrder) { m_address = {}; m_address.sin_family = AF_INET; m_address.sin_port = htons(portHostOrder); m_address.sin_addr.s_addr = htonl(ipHostOrder); } Networking::NetworkAddress ::NetworkAddress(const std::string& ipAddress, unsigned short portHostOrder) { m_address = {}; m_address.sin_family = AF_INET; m_address.sin_port = htons(portHostOrder); int result = inet_pton(AF_INET, ipAddress.c_str(), &(m_address.sin_addr)); if (1 != result) { throw std::invalid_argument{"Value \"" + ipAddress + "\" is not a valid IP address."}; } } unsigned int Networking::NetworkAddress::getIPHostOrder() const { return ntohl(m_address.sin_addr.s_addr); } std::string Networking::NetworkAddress::getIPDotNotation() const { char nameBuffer[INET_ADDRSTRLEN]; memset(nameBuffer, 0, sizeof(nameBuffer)); // TODO: Allow instantiation with IPv6 String. if (nameBuffer != inet_ntop(PF_INET, &(m_address.sin_addr.s_addr), nameBuffer, sizeof(nameBuffer))) { throw std::system_error{errno, std::generic_category(), __FILE__":" str(__LINE__) ": Call to inet_ntop failed"}; } return std::string{const_cast<const char*>(nameBuffer)}; } unsigned short Networking::NetworkAddress::getPortHostOrder() const { return ntohs(m_address.sin_port); } const struct sockaddr_in& Networking::NetworkAddress::getSockAddr() const { return const_cast<const sockaddr_in&>(m_address); } std::string Networking::NetworkAddress::string() const { return "(" + getIPDotNotation() + ", " + std::to_string(getPortHostOrder()) + ")"; } bool Networking::NetworkAddress ::operator==(const Networking::NetworkAddress& that) const { return m_address.sin_family == that.m_address.sin_family && m_address.sin_port == that.m_address.sin_port && m_address.sin_addr.s_addr == that.m_address.sin_addr.s_addr; } bool Networking::NetworkAddress ::operator!=(const Networking::NetworkAddress& that) const { return !operator==(that); } ///////////////////////////////////////////////////////////////////////////////
true
24a259af44bd40b260eb4d4f6b92b4261c8bbb6f
C++
sraihan73/Lucene-
/queries/src/java/org/apache/lucene/queries/function/valuesource/MaxFloatFunction.cpp
UTF-8
1,011
2.578125
3
[]
no_license
using namespace std; #include "MaxFloatFunction.h" namespace org::apache::lucene::queries::function::valuesource { using FunctionValues = org::apache::lucene::queries::function::FunctionValues; using ValueSource = org::apache::lucene::queries::function::ValueSource; MaxFloatFunction::MaxFloatFunction( std::deque<std::shared_ptr<ValueSource>> &sources) : MultiFloatFunction(sources) { } wstring MaxFloatFunction::name() { return L"max"; } float MaxFloatFunction::func( int doc, std::deque<std::shared_ptr<FunctionValues>> &valsArr) { if (!exists(doc, valsArr)) { return 0.0f; } float val = -numeric_limits<float>::infinity(); for (auto vals : valsArr) { if (vals->exists(doc)) { val = max(vals->floatVal(doc), val); } } return val; } bool MaxFloatFunction::exists( int doc, std::deque<std::shared_ptr<FunctionValues>> &valsArr) { return MultiFunction::anyExists(doc, valsArr); } } // namespace org::apache::lucene::queries::function::valuesource
true
f1acceb3ac3fe343cbeb9cdb598cfc335377255f
C++
warwick-hpsc/CUP-CFD
/include/geometry/shapes/implementation/component/TriPrism.ipp
UTF-8
7,043
3.015625
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
/** * @file * @author University of Warwick * @version 1.0 * * @section LICENSE * * @section DESCRIPTION * * Description * * Header Level Definitions for TriPrism class */ #ifndef CUPCFD_GEOMETRY_SHAPES_TRIPRISM_IPP_H #define CUPCFD_GEOMETRY_SHAPES_TRIPRISM_IPP_H #include "TriPrism.h" #include "EuclideanPlane3D.h" #include "Triangle3D.h" namespace euc = cupcfd::geometry::euclidean; namespace cupcfd { namespace geometry { namespace shapes { // === Constructors/Deconstructors === template <class T> TriPrism<T>::TriPrism(const shapes::Triangle3D<T>& top, const shapes::Triangle3D<T>& bottom) : top(top), bottom(bottom) { // ToDo: ensure that normals of Top and Bottom are parallel. /* // Invert either face if its normal points inwards: T dp = this->top.getNormal().dotProduct(this->top.getCentroid() - this->bottom.getCentroid()); // T dp = this->top.normal.dotProduct(this->top.centroid - this->bottom.centroid); if (dp < T(0.0)) { this->top.reverseVertexOrdering(); } dp = this->bottom.getNormal().dotProduct(this->bottom.getCentroid() - this->top.getCentroid()); // dp = this->bottom.normal.dotProduct(this->bottom.centroid - this->top.centroid); if (dp < T(0.0)) { this->bottom.reverseVertexOrdering(); } */ } template <class T> TriPrism<T>::~TriPrism() { } // === Concrete Methods === template <class T> inline bool TriPrism<T>::isPointInside(euc::EuclideanPoint<T,3>& point) { // ToDo: This algorithm could be moved up to a more general level in Polyhedron. // However, we would need to either (a) find a way to export the vertices (overhead of extra copies) // or (b) store a general vertex member list (such as an array) at the Polyhedron level - however //since the size would be variable, this would be an array pointer, not a fixed size, and so every //Polyhedron object would just point to a different fragmented arbitrary location in memory - would be bad //for creating contiguous arrays of Polyhedrons (not that I would recommend AoS as an approach). // ToDo: Cost/benefit - if this is used frequently may be cheaper to store the faces rather than // reconstruct them - however, this will increase the cost of the constructors.... // Algorithm: Construct a vector from the point to each face // Assuming the normal vector direction is pointing out, if the dot-product of the face normal // vector and the point->face vector is positive, they are both in the same direction, and // thus the point is 'inside' for that face. // Repeat for all faces, and if 'inside' all of them, the point is inside the polygon double dotProd; euc::EuclideanVector<T,3> pointVector; // Build 5 Faces from polygons as planes // Ordering for each should be clockwise from inside, anti-clockwise from outside // This assumes that the vertices for each face are coplanar, but this is a reasonable assumption // since if they are not, then this is not really a triprism (since a Quadrilateral non coplanar = two triangular faces...) euc::EuclideanPlane3D<T> facePlanes[5] = { euc::EuclideanPlane3D<T>(this->top.vertices[0], this->top.vertices[1], this->top.vertices[2]), euc::EuclideanPlane3D<T>(this->bottom.vertices[0], this->bottom.vertices[1], this->bottom.vertices[2]), euc::EuclideanPlane3D<T>(this->top.vertices[0], this->top.vertices[2], this->bottom.vertices[2]), euc::EuclideanPlane3D<T>(this->top.vertices[2], this->top.vertices[1], this->bottom.vertices[1]), euc::EuclideanPlane3D<T>(this->top.vertices[1], this->top.vertices[0], this->bottom.vertices[0]) }; // // Ensure each face plane normal points outwards: // for (int i=0; i<5; i++) { // dotProd = facePlanes[i].getNormal().dotProduct(facePlanes[i].p1 - this->computeCentroid()); // // dotProd = facePlanes[i].normal.dotProduct(facePlanes[i].p1 - this->centroid); // if (dotProd < T(0)) { // facePlanes[i].reverseVertexOrdering(); // } // } // (1) Test against each face for(int i = 0; i < 5; i++) { // ToDo: This is presuming that all type 'P' base objects have a vertices data structure // Could make it so Polygon3D has a pointer to a vertices array, and then leave the // storage implementation to the subclasses and updating the pointer to it. // (2a) Create a vector to the first point on the face (same as plane p1) pointVector = point - facePlanes[i].p1; // (2b) Are we on a face? If so this counts as inside, but the vector will be perpendicular // to the normal/parallel to the plane if(facePlanes[i].isVectorParallelInPlane(pointVector, point)) { return true; } // (2c) Is the point vector and the normal vector facing the same direction? // If not, this point is not inside the polyhedron dotProd = facePlanes[i].getNormal().dotProduct(pointVector); // dotProd = facePlanes[i].normal.dotProduct(pointVector); if(dotProd > T(0)) { return false; } } // If we made it this far then checks were passed for all faces - therefore we are in the shape return true; } template <class T> T TriPrism<T>::getVolume() { if (!this->volumeComputed) { this->volume = this->computeVolume(); this->volumeComputed = true; } return this->volume; } template <class T> euc::EuclideanPoint<T,3> TriPrism<T>::getCentroid() { if (!this->centroidComputed) { this->centroid = this->computeCentroid(); this->centroidComputed = true; } return this->centroid; } template <class T> T TriPrism<T>::computeVolume() { T height = (this->top.getCentroid() - this->bottom.getCentroid()).length(); T volume = height * this->bottom.getArea(); return volume; } template <class T> euc::EuclideanPoint<T,3> TriPrism<T>::computeCentroid() { // https://en.wikipedia.org/wiki/Centroid#Of_a_tetrahedron_and_n-dimensional_simplex return T(1)/T(7) * (this->top.vertices[0] + this->top.vertices[1] + this->top.vertices[2] + this->bottom.vertices[0] + this->bottom.vertices[1] + this->bottom.vertices[2]); } template <class T> inline bool TriPrism<T>::isPointOnEdge(const euc::EuclideanPoint<T,3>& point) { for (int v1=0; v1<3; v1++) { const int v2=(v1+1)%3; if (isPointOnLine(this->top.vertices[v1], this->top.vertices[v2], point)) { return true; } if (isPointOnLine(this->bottom.vertices[v1], this->bottom.vertices[v2], point)) { return true; } } return false; } template <class T> inline bool TriPrism<T>::isPointOnVertex(const euc::EuclideanPoint<T,3>& point) { for (int i=0; i<3; i++) { if ( (this->top.vertices[i] == point) || (this->bottom.vertices[i] == point) ) { return true; } } return false; } } } } #endif
true
cc4a5045e61101e8d4f1083bfce4dd7eb55b6ba3
C++
opendarkeden/server
/src/server/gameserver/skill/EffectObservingEye.h
UTF-8
1,685
2.96875
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Filename : EffectObservingEye.h // Written by : // Description : ////////////////////////////////////////////////////////////////////////////// #ifndef __EFFECT_OBSERVING_EYE__ #define __EFFECT_OBSERVING_EYE__ #include "Effect.h" ////////////////////////////////////////////////////////////////////////////// // class EffectObservingEye ////////////////////////////////////////////////////////////////////////////// class EffectObservingEye : public Effect { public: EffectObservingEye(Creature* pCreature) ; public: EffectClass getEffectClass() const throw() { return EFFECT_CLASS_OBSERVING_EYE; } void affect() {} void affect(Creature* pCreature) ; void affect(Zone* pZone, ZoneCoord_t x, ZoneCoord_t y, Object* pObject) ; void unaffect(Creature* pCreature) ; void unaffect(Zone* pZone, ZoneCoord_t x, ZoneCoord_t y, Object* pObject) ; void unaffect() ; void unaffect(Item* pItem) {} bool canSeeInvisibility( Creature* pTarget ) const ; string toString() const throw(); public: int getDamageBonus(void) const { return m_DamageBonus; } void setDamageBonus(int bonus) { m_DamageBonus = bonus; } int getCriticalHitBonus(void) const { return m_CriticalHitBonus; } void setCriticalHitBonus(int bonus) { m_CriticalHitBonus = bonus; } int getVisionBonus(void) const { return m_VisionBonus; } void setVisionBonus(int bonus) { m_VisionBonus = bonus; } void setSkillLevel( ExpLevel_t level ) throw() { m_SkillLevel = level; } private : int m_DamageBonus; int m_CriticalHitBonus; int m_VisionBonus; ExpLevel_t m_SkillLevel; }; #endif // __EFFECT_OBSERVING_EYE__
true
0c486cc55cc79867afda28c924d2ad1fe8d84bd3
C++
shenchi/sph_cpu
/src/grid.cpp
UTF-8
2,993
2.75
3
[ "MIT" ]
permissive
#include "grid.h" #include "radixsort.h" #include <cstring> namespace SPH{ Grid * CreateGrid(float3 origin, float3 size, float h, int max_particles, int max_neighbours){ Grid* g = new Grid; g->origin = origin; g->f_size = size; g->i_size = make_int3(size * (1 / h)); g->length = g->i_size.x * g->i_size.y * g->i_size.z; g->h = h; g->hash = new int[max_particles]; g->index = new int[max_particles]; g->start = new int[g->length]; g->end = new int[g->length]; g->nb = new int[max_particles * max_neighbours]; g->nb_start = new int[max_particles]; g->nb_end = new int[max_particles]; return g; } void DestroyGrid(Grid *g){ delete [] g->hash; delete [] g->index; delete [] g->start; delete [] g->end; delete [] g->nb; delete [] g->nb_start; delete [] g->nb_end; delete g; } inline int gridHash(Grid *g, float3 &pos){ int3 p = make_int3((pos - g->origin) * ( 1.0f / g->h)); if( p.x < 0 || p.x >= g->i_size.x ) return 0; if( p.y < 0 || p.y >= g->i_size.y ) return 0; if( p.z < 0 || p.z >= g->i_size.z ) return 0; return p.x + p.y * g->i_size.x + p.z * g->i_size.x * g->i_size.y; } inline int gridHash(Grid *g, int3 &p){ return p.x + p.y * g->i_size.x + p.z * g->i_size.x * g->i_size.y; } const int3 int3_zero = make_int3(0, 0, 0); inline int3 gridPos(const float3 &pos, Grid *g){ int3 p = make_int3((pos - g->origin) * ( 1.0f / g->h)); if( p.x < 0 || p.x >= g->i_size.x ) return int3_zero; if( p.y < 0 || p.y >= g->i_size.y ) return int3_zero; if( p.z < 0 || p.z >= g->i_size.z ) return int3_zero; return p; } void UpdateGrid(Grid *g, float3 *new_pos, float3 *new_vel, float3 *old_pos, float3 *old_vel, float smooth, int n_particles){ for(int i = 0; i < n_particles; i++){ g->hash[i] = gridHash(g, old_pos[i]); g->index[i] = i; } RadixSort(g->hash, g->index, n_particles); memset(g->start, 0xff, n_particles * sizeof(int)); g->start[g->hash[0]] = 0; for(int i = 1; i < n_particles; i++){ if(g->hash[i] != g->hash[i - 1]){ g->start[g->hash[i]] = i; g->end[g->hash[i-1]] = i; } } g->end[g->hash[n_particles - 1]] = n_particles; for(int i = 0; i < n_particles; i++){ new_pos[i] = old_pos[g->index[i]]; new_vel[i] = old_vel[g->index[i]]; } int3 posi, posj; int nb_hash, sj, ej; for(int i = 0, k = 0; i < n_particles; i++){ posi = gridPos(new_pos[i], g); g->nb_start[i] = k; for(int z = -1; z <= 1; z++) for(int y = -1; y <= 1; y++) for(int x = -1; x <= 1; x++){ posj = posi + make_int3(x, y, z); nb_hash = gridHash(g, posj); sj = g->start[nb_hash]; if( sj == 0xffffffff ) continue; ej = g->end[nb_hash]; for(int j = sj; j < ej; j++){ if( len(new_pos[j] - new_pos[i]) <= smooth && i != j){ g->nb[k++] = j; } } } g->nb_end[i] = k; } } };
true
5423810b936021bad8bde5c077d6cfcff26124c3
C++
Akemi-Homura/uestc2015ccpp
/Fighters/include/Entity.hpp
UTF-8
819
2.78125
3
[]
no_license
#ifndef __ENTITY_HPP__ #define __ENTITY_HPP__ #include <SFML/Graphics.hpp> #include <string> #include "Stage.hpp" class Stage; class Entity : public sf::Sprite { friend class Stage; public: virtual void setId(int id); virtual int getId(); void setPosition(float x, float y); virtual bool isAlive(); virtual std::string getType() = 0; virtual void hit() = 0; virtual void die() = 0; protected: Stage* m_stage; bool m_isAlive; sf::ConvexShape m_collision; void setOrigin(float x, float y); void setPosition(const sf::Vector2f& position); void move(const sf::Vector2f& offset); void move(float offsetX, float offsetY); void rotate(float angle); private: virtual void animate(sf::Time frameTime) = 0; virtual sf::ConvexShape getCollision(); int m_id; }; #endif // __ENTITY_HPP__
true
710f5d69bfb79941498bd57b0cebc6df64f4d14b
C++
daviddorsey/CS220-Term-Project
/TermProject/TermProject/Game.h
UTF-8
1,847
2.828125
3
[]
no_license
// // Game.h // TermProject // // Created by David Dorsey on 11/17/15. // Copyright (c) 2015 David Dorsey. All rights reserved. // #ifndef __TermProject__Game__ #define __TermProject__Game__ #include <stdio.h> #include <iostream> #include "Item.h" #include "QueueADT.h" // defined(__TermProject__Game__) class Game : public Item{ private: int numInStock; float price; std:: string title; std:: string genre; std:: string rating; bool preorder; QueueADT* waitingList; std:: string publisher; bool preowned; std:: string searchName; std::string searchFormat(std::string s); public: //Constructor Game(int stockIn, float priceIn, std::string titleIn, std::string genreIn, std::string ratingIn, bool preownedIn, std::string publisherIn, bool preorderIn); //Copy constuctor Game(Game* gameToCopy); void buy(int numCopies); //creates a string with all of the contents for the game std::string toString(); //creates a string with all of the contents for the game reordered for file writing std::string fileFormat(); //allows the game to go from preOrder to in stock void comeToStock(); //allows a user to preorder the game int preOrder(std:: string name); //allows a user to cancle their preorder std::string removePreOrder(int idNumber); void sell(int amount); //Getters std:: string getTitle(); std:: string getGenre(); std:: string getRating(); std:: string getPublisher(); std:: string getSearchName(); bool getPreorderStatus(); int getNumInStock(); //Setters void setGenre(std::string genreIn); void setRating(std::string ratingIn); void setPublisher(std::string publisherIn); //Destructor ~Game(); }; #endif
true
5a63541f40dab3a6b1450caa710760f4cff8e707
C++
DennisWandschura/vxEngine
/source/vxEngineLib/Triangle.cpp
UTF-8
2,517
2.53125
3
[ "MIT" ]
permissive
/* The MIT License (MIT) Copyright (c) 2015 Dennis Wandschura Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <vxEngineLib/Triangle.h> f32 Triangle::getArea() const { auto ab = m_points[1] - m_points[0]; auto ac = m_points[2] - m_points[0]; auto t = vx::cross(ab, ac); auto area = vx::length3(t) * 0.5f; return area; } vx::float3 Triangle::getCentroid() const { return (m_points[0] + m_points[1] + m_points[2]) / 3.0f; } bool Triangle::contains(const vx::float3 &point) const { auto a = vx::loadFloat3(&m_points[0]); auto b = vx::loadFloat3(&m_points[1]); auto c = vx::loadFloat3(&m_points[2]); auto p = vx::loadFloat3(&point); a = _mm_sub_ps(a, p); b = _mm_sub_ps(b, p); c = _mm_sub_ps(c, p); auto u = vx::cross3(b, c); auto v = vx::cross3(c, a); vx::float4a uDotV = vx::dot3(u, v); if (uDotV.x < 0.0f) return false; auto w = vx::cross3(a, b); vx::float4a uDotW = vx::dot3(u, w); if (uDotW.x < 0.0f) return false; return true; } bool Triangle::sharesEdge(const Triangle &other) const { u8 sharedCount = 0; for (int i = 0; i < 3; ++i) { auto otherPoint = other.m_points[i]; if (m_points[0].x == otherPoint.x && m_points[0].y == otherPoint.y && m_points[0].z == otherPoint.z) ++sharedCount; else if (m_points[1].x == otherPoint.x && m_points[1].y == otherPoint.y && m_points[1].z == otherPoint.z) ++sharedCount; else if (m_points[2].x == otherPoint.x && m_points[2].y == otherPoint.y && m_points[2].z == otherPoint.z) ++sharedCount; } return sharedCount > 1; }
true
881315790f3a71e75ed2ec22669e75f7d97e4379
C++
hrishi3390/moderncpp
/privatevirtual2/main.cpp
UTF-8
1,520
3.28125
3
[]
no_license
// // main.cpp // privatevirtual2 // // Created by Hrishikesh Chaudhari on 05/02/19. // Copyright © 2019 Hrishikesh Chaudhari. All rights reserved. // //#include <iostream> //using namespace std; // //class A{ // virtual void print(){ // cout<<"This is private virtual method"<<endl; // } // //public: // void print1(){ // cout<<"This is print 1"<<endl; // } // //}; // //class B : public A{ // int a; // //public: // // void print(){ // cout<<"THis is priint in B"<<endl; // } // //}; // //int main(int argc, const char * argv[]) { // // //// A *a = new B; //// B b; //// b.print(); // // A a; // a.print1(); // // a->print(); // return 0; //} // #include <iostream> class Engine { public: void SetState( int var, bool val ) { SetStateBool( var, val ); } void SetState( int var, int val ) { SetStateInt( var, val ); } private: virtual void SetStateBool(int var, bool val ) = 0; virtual void SetStateInt(int var, int val ) = 0; }; class DerivedEngine : public Engine { private: virtual void SetStateBool(int var, bool val ) { std::cout << "DerivedEngine::SetStateBool() called" << std::endl; } virtual void SetStateInt(int var, int val ) { std::cout << "DerivedEngine::SetStateInt() called" << std::endl; } }; int main() { DerivedEngine e; Engine * be = &e; be->SetState(4, true); be->SetState(2, 1000); }
true
2c3f9e5f67a391fdf887106a7f9750621672417f
C++
haijun9/2019_Spring_Algorithm
/김지혜/2300_기지국.cpp
UHC
1,168
3.1875
3
[]
no_license
using namespace std; #include <utility> #include <iostream> #include <algorithm> int main() { int n, x, y; pair<int, int> p[10001]; std::cin >> n; int answer[10001]; for (int i = 0; i<n ; i++) { std::cin >> x; std::cin >> y; p[i].first = x; p[i].second = y; } sort(p, p+n); answer[0] = abs(p[0].second)*2; //ʱⰪ. for (int i = 1; i < n; i++) { //ʱⰪ: i° ǹ ȥ 簢 ִٰ ģ answer[i] = answer[i-1]+abs(p[i].second) * 2; int maxlen = abs(p[i].second); for (int j = i-1; j >=0; j--) { //i° ǹ 簢 j° ǹ maxlen = max(maxlen, abs(p[j].second)); //ó // ̿ , 簢 ̰ int reallen = max(2 * maxlen, p[i].first - p[j].first); if(j==0) answer[i] = min(answer[i], reallen); //j 0̶ answer else answer[i] = min(answer[i], reallen + answer[j - 1]); } //std::cout << i <<"°: "<<answer[i]<<"\n"; } std::cout << answer[n-1]; }
true
2fbf1d317fc59dafaa5338821945ecb502991b55
C++
bdonkey/DataStructures-Algorithms
/DSA Crack Sheet/solutions/108. Bishu and Soldiers.cpp
UTF-8
493
2.75
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<int> powers(n, 0); for (auto &i : powers) cin >> i; int q; cin >> q; while (q--) { int bishu; cin >> bishu; int total_pow = 0, count = 0; for (auto &i : powers) { if (i <= bishu) { total_pow += i; count++; } } cout << count << " " << total_pow << endl; } return 0; }
true
1c1e6642fb18040fdba6e2f08efe97f8d37f4c78
C++
elttaes/Graphics_HW1
/Graphics_HW/main.cpp
UTF-8
8,503
3.109375
3
[]
no_license
/* # Mehmet Mazhar SALIKCI # 21.3.2016 Introduction: --DDA algorithm --Brehensam Algorithm --Benchmark */ #include <math.h> #include <iostream> #include <ctime> #include <cstdlib> #include <gl/glut.h> #define MIN( x, y ) ((x) <= (y) ? (x) : (y)) #define MAX( x, y ) ((x) >= (y) ? (x) : (y)) #define ABS( x ) ((x) >= 0.0 ? (x) : -(x)) #define ROUND(a) ((int) (a + 0.5)) // Rather than specifying RGB values for colors, this trivial // program will simply use an enumerated type, since we only // need four different colors. enum ColorFlag { unset, highlight, picked, rasterized }; // Define some basic parameters that determine the size and // spacing of the pixels, the maximum size of the raster, etc. static const int NUM_PIXELS = 200, WINDOW_X_SIZE = 800, WINDOW_Y_SIZE = 800, PIXEL_SPACING = 8, LINE_NUMBER = 500; static int option = 0; static int MOUSE_CLICK_SIZE = 0; static double timeDDA = 0; static double timeBrehensam = 0; // Declare the global variables that will be used to keep // track of which pixel is highlighted, which pixels have been // chosen as the start and end points, etc. static int curr_i = 0, curr_j = 0, last_i = -1, last_j = -1, pick_i = -1, pick_j = -1, count = 0, first_i = 0, first_j = 0, second_i = 0, second_j = 0; // Define the array that will hold the colors associated with // each pixel in the raster, and also the original color of the // pixel that is currently being highlighted. static ColorFlag last_color = unset, raster[NUM_PIXELS][NUM_PIXELS] = { unset }; // Translate the enumerated type into an actual RGB triple and // tell OpenGL to use this color for drawing subsequent polygons // (which will be used to depict pixels). void SetColor(ColorFlag c) { switch (c) { case unset: glColor3f(0.2, 0.2, 0.2); break; case highlight: glColor3f(0.1, 1.0, 0.1); break; case picked: glColor3f(1.0, 0.0, 0.0); break; case rasterized: glColor3f(0.3, 0.6, 0.6); break; } } void DrawSquare(int x, int y, int temp) { glBegin(GL_QUADS); glVertex2f(x, y); glVertex2f(x + 4, y); glVertex2f(x + 4, y + 4); glVertex2f(x, y + 4); glEnd(); } void SetPixel(int i, int j, ColorFlag color) { if (i < 0 || i >= NUM_PIXELS) return; if (j < 0 || j >= NUM_PIXELS) return; int x = i * PIXEL_SPACING; int y = j * PIXEL_SPACING; SetColor(color); DrawSquare(x,y, 1); raster[i][j] = color; if (i == last_i && j == last_j) last_color = color; } ColorFlag GetPixel(int i, int j) { return raster[i][j]; } void ClearRaster() { count = 0; glClear(GL_COLOR_BUFFER_BIT); // clear frame buffer for (int i = 0; i < NUM_PIXELS; i++) { for (int j = 0; j < NUM_PIXELS; j++) { SetPixel(i, j, unset); } } } void BresenhamAlgorithm(int x0, int y0, int x1, int y1) { int delta_x = x1 - x0; int delta_y = y1 - y0; int steps = MAX(ABS(delta_x), ABS(delta_y)); double c = 1.0 / MAX(1, steps); for (int i = 0; i <= steps; i++) { int x = int(x0 + (i * delta_x * c) + 0.5); int y = int(y0 + (i * delta_y * c) + 0.5); SetPixel(x, y, rasterized); } } void DDAAlgorithm(int x0, int y0, int x1, int y1) { //dont check whether (x1 - x0) is zero double m = (double)(y1 - y0) / (x1 - x0); double y = (double)y0; double x = (double)x0; if (m<1) { while (x <= x1) { SetPixel(x, floor(y + 0.5), rasterized); y = y + m; x++; } } else{ double m1 = 1.0 / m; while (y <= y1) { SetPixel(floor(fabs(x) + 0.5),y, rasterized); y++; x = x + m1; } } } void display() { static int initialized = 0; if (!initialized) { ClearRaster(); initialized = 1; } if (curr_i != last_i || curr_j != last_j) { SetPixel(last_i, last_j, last_color); last_color = GetPixel(curr_i, curr_j); SetPixel(curr_i, curr_j, highlight); last_i = curr_i; last_j = curr_j; } glFlush(); } void mouse_motion(int x, int y) { // Nothing to do while button is pressed. } void mouse_passive_motion(int x, int y) { double space = double(PIXEL_SPACING); curr_i = int(0.5 + x / space); curr_j = int(0.5 + (WINDOW_Y_SIZE - y) / space); glutPostRedisplay(); } // Handle key presses: Q for "Quit", and C for "Clear". void key_press(unsigned char key, int x, int y) { switch (key) { case 'q': case 'Q': return; case 'c': case 'C': ClearRaster(); glutPostRedisplay(); break; } } void PickPixel(int i, int j) { SetPixel(i, j, picked); if (count == 0) { // This is the first pixel of a pair. first_i = i; first_j = j; count = 1; } else if (count == 1) { // This is the second pixel of a pair. second_i = i; second_j = j; count = 0; if (option == 1) { DDAAlgorithm(first_i, first_j, second_i, second_j); } else if (option == 2) { BresenhamAlgorithm(first_i, first_j, second_i, second_j); } else if(option == 3) { if (MOUSE_CLICK_SIZE == 1) { BresenhamAlgorithm(first_i, first_j, second_i, second_j); } else if(MOUSE_CLICK_SIZE == 2) { DDAAlgorithm(first_i, first_j, second_i, second_j); } } } } void mouse_button(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { ++MOUSE_CLICK_SIZE; srand(time(NULL)); if (option == 3) { clock_t tStart = clock(); for (size_t i = 0; i < LINE_NUMBER; i++) { PickPixel(rand() % NUM_PIXELS, rand() % NUM_PIXELS); glutPostRedisplay(); } if (MOUSE_CLICK_SIZE == 1) { std::cout << "Bresenham Algorithm Execution Time:"; timeBrehensam = (double)(clock() - tStart) / CLOCKS_PER_SEC; std::cout << (double)(clock() - tStart) / CLOCKS_PER_SEC << std::endl; } else if (MOUSE_CLICK_SIZE == 2) { std::cout << "DDA Algorithm Execution Time:"; timeDDA = (double)(clock() - tStart) / CLOCKS_PER_SEC; std::cout << (double)(clock() - tStart) / CLOCKS_PER_SEC << std::endl << std::endl; if (timeDDA > timeBrehensam) { std::cout << "Brehensam's Algorithm faster than DDA Algorithm." << std::endl; } else if(timeDDA < timeBrehensam) { std::cout << "DDA Algorithm faster than Brehensam's Algorithm." << std::endl; } else { std::cout << "Same speed" << std::endl << std::endl; } MOUSE_CLICK_SIZE = 0; } } else { PickPixel(curr_i, curr_j); glutPostRedisplay(); } } } void main(int argc, char** argv) { bool loop = true; while (loop) { std::cout << "1.Use DDA Algorithm" << std::endl; std::cout << "2.Use Bresenham Algorithm" << std::endl; std::cout << "3.Start Benchmark" << std::endl; std::cout << "4.Exit" << std::endl; std::cin >> option; if (option == 1) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(WINDOW_X_SIZE, WINDOW_Y_SIZE); glutInitWindowPosition(200, 200); glutCreateWindow("DDA Line Algorithm"); glClearColor(0.0, 0.0, 0.1, 0); // clear window glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, WINDOW_X_SIZE, 0.0, WINDOW_Y_SIZE, -1.0, 1.0); glutDisplayFunc(display); glutMotionFunc(mouse_motion); glutPassiveMotionFunc(mouse_passive_motion); glutMouseFunc(mouse_button); glutKeyboardFunc(key_press); glutMainLoop(); } else if(option == 2) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(WINDOW_X_SIZE, WINDOW_Y_SIZE); glutInitWindowPosition(200, 200); glutCreateWindow("Bresenham's Line Algorithm"); glClearColor(0.0, 0.0, 0.1, 0); // clear window glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, WINDOW_X_SIZE, 0.0, WINDOW_Y_SIZE, -1.0, 1.0); glutDisplayFunc(display); glutMotionFunc(mouse_motion); glutPassiveMotionFunc(mouse_passive_motion); glutMouseFunc(mouse_button); glutKeyboardFunc(key_press); glutMainLoop(); } else if(option == 3) { //when window opened ,if you want to exe DDA algorithm one click, //or to exe Bresenham Algorithm press two click //to clear window,press c or C, glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(WINDOW_X_SIZE, WINDOW_Y_SIZE); glutInitWindowPosition(200, 200); glutCreateWindow("Benchmark"); glClearColor(0.0, 0.0, 0.1, 0); // clear window glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, WINDOW_X_SIZE, 0.0, WINDOW_Y_SIZE, -1.0, 1.0); glutDisplayFunc(display); glutMotionFunc(mouse_motion); glutPassiveMotionFunc(mouse_passive_motion); glutMouseFunc(mouse_button); glutKeyboardFunc(key_press); glutMainLoop(); } else { loop = false; } } }
true
4806c446f869c32b07659fa290d1139160810679
C++
stonelay/Algorithm
/Algorithm/LeetCode/1-10/LeetCode006.cpp
UTF-8
585
2.6875
3
[ "MIT" ]
permissive
// // LeetCode006.cpp // Algorithm // // Created by LayZhang on 2018/2/6. // Copyright © 2018年 Zhanglei. All rights reserved. // #include "LeetCode006.hpp" string convert(string s, int numRows) { int nSize = numRows == 1 ? numRows : numRows * 2 - 2; string r = ""; string tRows[numRows]; for (int i = 0 ; i < s.size(); i++) { int tRow = i % nSize; int row = tRow > (numRows - 1) ? numRows - tRow % (numRows - 1) - 1 : tRow; tRows[row] += s[i]; } for (int j = 0; j < numRows; j++) { r += tRows[j]; } return r; }
true
343b233620356064539ee01d5e9ae6bd9ef6204e
C++
tmhuysen/libwint
/include/AOBasis.hpp
UTF-8
2,271
2.6875
3
[]
no_license
#ifndef LIBWINT_BASIS_HPP #define LIBWINT_BASIS_HPP #include <Eigen/Dense> #include <unsupported/Eigen/CXX11/Tensor> #include "Molecule.hpp" namespace libwint { class AOBasis { private: const std::string basisset_name; const std::vector<libint2::Atom> atoms; // We'd like to keep track if the integrals are calculated already, in order to avoid doing double work bool are_calculated_overlap_integrals = false; bool are_calculated_nuclear_integrals = false; bool are_calculated_kinetic_integrals = false; bool are_calculated_electron_repulsion_integrals = false; Eigen::MatrixXd S; // The overlap integrals matrix for the given basis and molecule Eigen::MatrixXd V; // The nuclear integrals matrix for the given basis and molecule Eigen::MatrixXd T; // The kinetic integrals matrix for the given basis and molecule Eigen::Tensor<double, 4> g; // The two-electron repulsion integrals tensor for the given basis and molecule public: // Constructors /** * Constructor from a @param: molecule and a @param: basisset_name. */ AOBasis(const libwint::Molecule& molecule, std::string basisset_name); // Getters Eigen::MatrixXd get_S() const; Eigen::MatrixXd get_T() const; Eigen::MatrixXd get_V() const; Eigen::Tensor<double, 4> get_g() const; /** * Calculate and return the number of basis functions in the basis */ size_t calculateNumberOfBasisFunctions() const; /** * Calculate and set the overlap integrals, if they haven't been calculated already */ void calculateOverlapIntegrals(); /** * Calculate and set the kinetic integrals, if they haven't been calculated already */ void calculateKineticIntegrals(); /** * Calculate and set the nuclear integrals, if they haven't been calculated already */ void calculateNuclearIntegrals(); /** * Calculate and set the electron repulsion integrals, if they haven't been calculated already */ void calculateElectronRepulsionIntegrals(); /** * Calculate and set all the integrals, if they haven't been calculated already */ void calculateIntegrals(); }; } // namespace libwint #endif // LIBWINT_BASIS_HPP
true
4161054a425fedd66fa49f912dc17cf660d1f9ac
C++
tudennis/LintCode
/C++/reverse-pairs.cpp
UTF-8
2,730
3.421875
3
[ "MIT" ]
permissive
// Time: O(nlogn) // Space: O(n) // BIT solution. class Solution { public: /** * @param A an array * @return total of reverse pairs */ long long reversePairs(vector<int>& A) { // Get the place (position in the ascending order) of each number. vector<int> sorted_A(A), places(A.size()); sort(sorted_A.begin(), sorted_A.end()); for (int i = 0; i < A.size(); ++i) { places[i] = lower_bound(sorted_A.begin(), sorted_A.end(), A[i]) - sorted_A.begin(); } // Count the smaller elements after the number. long long count = 0; vector<int> bit(A.size() + 1); for (int i = A.size() - 1; i >= 0; --i) { count += query(bit, places[i]); add(bit, places[i] + 1, 1); } return count; } private: void add(vector<int>& bit, int i, int val) { for (; i < bit.size(); i += lower_bit(i)) { bit[i] += val; } } int query(const vector<int>& bit, int i) { int sum = 0; for (; i > 0; i -= lower_bit(i)) { sum += bit[i]; } return sum; } int lower_bit(int i) { return i & -i; } }; // Time: O(nlogn) // Space: O(n) // Merge sort solution. class Solution2 { public: /** * @param A an array * @return total of reverse pairs */ long long reversePairs(vector<int>& A) { long long count = 0; vector<pair<int, int>> num_idxs; for (int i = 0; i < A.size(); ++i) { num_idxs.emplace_back(A[i], i); } countAndMergeSort(&num_idxs, 0, num_idxs.size() - 1, &count); return count; } private: void countAndMergeSort(vector<pair<int, int>> *num_idxs, int start, int end, long long *count) { if (end - start <= 0) { // The number of range [start, end] of which size is less than 2 doesn't need sort. return; } int mid = start + (end - start) / 2; countAndMergeSort(num_idxs, start, mid, count); countAndMergeSort(num_idxs, mid + 1, end, count); int l = start; vector<pair<int, int>> tmp; for (int i = mid + 1; i <= end; ++i) { // Merge the two sorted arrays into tmp. while (l <= mid && (*num_idxs)[l].first <= (*num_idxs)[i].first) { tmp.emplace_back((*num_idxs)[l++]); } tmp.emplace_back((*num_idxs)[i]); *count += mid - l + 1; } while (l <= mid) { tmp.emplace_back((*num_idxs)[l++]); } // Copy tmp back to num_idxs. copy(tmp.begin(), tmp.end(), num_idxs->begin() + start); } };
true
b8772dbebe9a34b0fa8baf5291019aa0b888654d
C++
rubengp39/CodeForces
/A-Set/703A_MishkaAndGame.cpp
UTF-8
497
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back const int INFINITE = 10000000; void solve() { int n, a, b,aC = 0, bC = 0; cin >> n; for (int i = 0; i < n; ++i) { cin >> a >> b; if (a > b) { aC++; } else if (a < b) { bC++; } } if (aC > bC) { cout << "Mishka"; } else if (bC > aC) { cout << "Chris"; } else { cout << "Friendship is magic!^^"; } } int main() { /*int t; cin >> t; while(t--) */ solve(); return 0; }
true
d1edac413ab87d870cdab75c9fc70b5f68cee21e
C++
toltec-astro/macana2
/Utilities/GslRandom.cpp
UTF-8
1,344
2.828125
3
[]
no_license
#include <iostream> #include <fstream> #include <cmath> #include <string> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <sys/time.h> using namespace std; #include "GslRandom.h" //constructor GslRandom::GslRandom() { //create the generator r = gsl_rng_alloc(gsl_rng_mt19937); //using the MT19937 generator //set the random number seed based on the current system time //which is seconds since a long time ago //GW - 17Nov15 - this turns out to have been a bad idea as //when running in parallel mode this constructor could be //called several times a second. The following increases //the resolution to ns. timespec ts; clock_gettime(CLOCK_REALTIME, &ts); seed = ts.tv_sec*1e9 + ts.tv_nsec; gsl_rng_set(r,seed); } //constructor with a given seed GslRandom::GslRandom(long seed) { //create the generator r = gsl_rng_alloc(gsl_rng_mt19937); //using the MT19937 generator gsl_rng_set(r,seed); } //return a gaussian deviate with variance=1 double GslRandom::gaussDeviate() { double ret; #pragma omp critical ret = gsl_ran_ugaussian(r); return ret; } //returns a uniform deviate on the range [a,b] double GslRandom::uniformDeviate(double a, double b) { double ret; #pragma omp critical ret=gsl_ran_flat(r, a, b); return ret; } GslRandom::~GslRandom() { gsl_rng_free(r); }
true
4f7a3c3713db2f67ee96cf7cea5baf71629c3e45
C++
NOVACProject/SpectralEvaluation
/src/Geometry.cpp
UTF-8
4,117
3.078125
3
[]
no_license
#include <SpectralEvaluation/DateTime.h> #include <SpectralEvaluation/Geometry.h> #include <SpectralEvaluation/Definitions.h> #include <cmath> namespace novac { // The following functions are taken from the NovacProgram. // Be sure to document further what is being done here. /// <summary> /// Calculates and returns the Right Ascension, declination and Equation of Time /// See also https://en.wikipedia.org/wiki/Position_of_the_Sun /// </summary> /// <param name="D"></param> /// <param name="RA"></param> /// <param name="dec"></param> /// <param name="EQT"></param> void EquatorialCoordinates(double D, double& RA, double& dec, double& EQT) { const double g_deg = fmod(357.529 + 0.98560028 * D, 360.0); const double g_rad = g_deg * DEGREETORAD; const double q_deg = fmod(280.459 + 0.98564736 * D, 360.0); const double L_deg = q_deg + 1.915 * std::sin(g_rad) + 0.02 * std::sin(2 * g_rad); const double L_rad = L_deg * DEGREETORAD; // The distance between the sun and the earth (in Astronomical Units) // const double R = 1.00014 - 0.01671 * cos(g_rad) - 0.00014 * cos(2 * g_rad); // The obliquity of the earth's orbit: const double obliq_deg = 23.439 - 0.00000036 * D; const double obliq_rad = obliq_deg * DEGREETORAD; // The right ascension (RA) double RA_rad = std::atan(std::cos(obliq_rad) * std::sin(L_rad) / std::cos(L_rad)); if (RA_rad < 0) RA_rad = TWO_PI + RA_rad; if (fabs(RA_rad - L_rad) > 1.570796) RA_rad = M_PI + RA_rad; const double dec_rad = std::asin(std::sin(obliq_rad) * std::sin(L_rad)); RA = fmod(RA_rad * RADTODEGREE, 360.0); // The right ascension // The declination dec = dec_rad * RADTODEGREE; // The Equation of Time EQT = q_deg / 15.0 - RA / 15.0; } void HorizontalCoordinates(double lat, double H, double dec, double& elev, double& azim) { double H_rad = H * DEGREETORAD; double lat_rad = lat * DEGREETORAD; double dec_rad = dec * DEGREETORAD; // The elevation angle double elev_rad = asin(cos(H_rad) * cos(dec_rad) * cos(lat_rad) + sin(dec_rad) * sin(lat_rad)); // The cosine of the azimuth - angle double cazim_rad = (cos(H_rad) * cos(dec_rad) * sin(lat_rad) - sin(dec_rad) * cos(lat_rad)) / cos(elev_rad); // The sine of the azimuth - angle double sazim_rad = (sin(H_rad) * cos(dec_rad)) / cos(elev_rad); double azim_rad = 0.0; if (cazim_rad > 0 && sazim_rad > 0) azim_rad = asin(sazim_rad); // azim is in the range 0 - 90 degrees else if (cazim_rad < 0 && sazim_rad > 0) azim_rad = M_PI - asin(sazim_rad); // azim is in the range 90 - 180 degrees else if (cazim_rad < 0 && sazim_rad < 0) azim_rad = M_PI - asin(sazim_rad); // azim is in the range 180 - 270 degrees else if (cazim_rad > 0 && sazim_rad < 0) azim_rad = TWO_PI + asin(sazim_rad); // azim is in the range 270 - 360 degrees elev = elev_rad * RADTODEGREE; azim = azim_rad * RADTODEGREE; } /** Returns the hour angle given the longitude and equation of time. */ double GetHourAngle(double hr, double lon, double EqT) { return 15.0 * (hr + lon / 15 + EqT - 12); } void GetSunPosition(const CDateTime& gmtTime, double lat, double lon, double& SZA, double& SAZ) { SZA = 0.0; SAZ = 0.0; // Get the julian day double D = JulianDay(gmtTime) - 2451545.0; // Get the Equatorial coordinates... double RA; // the right ascension (deg) double dec; // the declination (deg) double EqT; // the equation of time (hours) EquatorialCoordinates(D, RA, dec, EqT); // Get the hour angle double fractionalHour = (double)gmtTime.hour + gmtTime.minute / 60.0 + gmtTime.second / 3600.0; double H = GetHourAngle(fractionalHour, lon, EqT); // Get the horizontal coordinates double elev, sAzim; // The elevation and azimuth (towards south); HorizontalCoordinates(lat, H, dec, elev, sAzim); // Convert the elevation into sza SZA = 90.0 - elev; // Convert the azimuth to a value counted from the north and SAZ = fmod(180.0 + sAzim, 360.0); } }
true
97f45fc8cdfb043e22003e37f567906701717956
C++
AriCarvalho/Cpp
/RepresentacaoDeDouble/RepresentacaoDeDouble.cpp
UTF-8
618
2.890625
3
[]
no_license
void EntenderRepresentacaoDeDouble(){ struct data{ union { unsigned __int64 ui; double d; }; }; data s = data(); s.ui=0b0100000000001000000000000000000000000000000000000000000000000000u; //seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm //(-1^s)*(1+f(m))^(e+1-2^10) // S * M ^ E cout << "sizeof(ui)=" << sizeof(s.ui) << " sizeof(d)=" << sizeof(s.d) << " sizeof(s)=" << sizeof(s) << endl; cout << "ui=" << hex<< s.ui << " d=" << s.d << endl; } //sizeof(ui)=8 sizeof(d)=8 sizeof(s)=8 //ui=4008000000000000 d=3
true
fb12cef81f40939e60954b443e996cc932cd637e
C++
jpcerrone/handmadeHero
/gameCode.cpp
UTF-8
20,801
2.703125
3
[]
no_license
#include "gameCode.h" #define _USE_MATH_DEFINES #include <math.h> #include <iostream> #include "world.cpp" #include "memory_arena.cpp" #include "instrinsics.h" int roundFloat(float value) { return (int)(value + 0.5f); } uint32_t roundUFloat(float value) { return (uint32_t)(value + 0.5f); } void drawRectangle(void* bitmap, int bmWidth, int bmHeight, float minX, float minY, float maxX, float maxY, float r, float g, float b) { uint32_t* pixel = (uint32_t*)bitmap; if (minX < 0.0f) minX = 0.0f; if (minY < 0.0f) minY = 0.0f; if (maxX > bmWidth) maxX = (float)bmWidth; if (maxY > bmHeight) maxY = (float)bmHeight; float tmp = maxY; maxY = bmHeight - minY; minY = bmHeight - tmp; uint32_t color = (0xFF << 24) | (roundUFloat(r*255.0f) << 16) | (roundUFloat(g * 255.0f) << 8) | (roundUFloat(b * 255.0f) << 0); //0xAA RR GG BB 0b1111 // Go to upper left corner. pixel += bmWidth*(roundFloat(minY)); pixel += roundFloat(minX); int recWidth = roundFloat(maxX) - roundFloat(minX); int recHeight = roundFloat(maxY) - roundFloat(minY); for (int y = 0; y < recHeight; y++) { for (int x = 0; x < recWidth; x++) { *pixel = color; pixel++; } pixel += bmWidth - recWidth; } } void loadSineWave(uint32_t framesToWrite, void *bufferLocation, int samplesPerSec, float frequency, float *waveOffset) { int samplesPerWave = (int)(samplesPerSec / frequency); int volume = 1200; int16_t *sample = (int16_t *)bufferLocation; for (uint32_t i = 0; i < framesToWrite; i++) { // The size of an audio frame is the number of channels in the stream multiplied by the sample size { *waveOffset += ((float)1 / (float)samplesPerWave); float sinValue = sinf(2.0f * (float)M_PI * *waveOffset); *sample = (int16_t)(sinValue * volume); *(sample + 1) = (int16_t)(sinValue * volume); } sample += 2; } *waveOffset -= (int)*waveOffset; // Keep it between 0 and 1 to avoid overflow. } void initWorldArena(MemoryArena* worldArena, uint8_t *basePointer, size_t totalSize) { worldArena->base = basePointer; worldArena->total = totalSize; worldArena->used = 0; } #pragma pack(push, 1) struct BitmapHeader { uint16_t FileType; uint32_t FileSize; uint16_t Reserved1; uint16_t Reserved2; uint32_t BitmapOffset; uint32_t Size; /* Size of this header in bytes */ int32_t Width; /* Image width in pixels */ int32_t Height; /* Image height in pixels */ uint16_t Planes; /* Number of color planes */ uint16_t BitsPerPixel; /* Number of bits per pixel */ uint32_t Compression; /* Compression methods used */ uint32_t SizeOfBitmap; /* Size of bitmap in bytes */ int32_t HorzResolution; /* Horizontal resolution in pixels per meter */ int32_t VertResolution; /* Vertical resolution in pixels per meter */ uint32_t ColorsUsed; /* Number of colors in the image */ uint32_t ColorsImportant; /* Minimum number of important colors */ /* Fields added for Windows 4.x follow this line */ uint32_t RedMask; /* Mask identifying bits of red component */ uint32_t GreenMask; /* Mask identifying bits of green component */ uint32_t BlueMask; /* Mask identifying bits of blue component */ uint32_t AlphaMask; /* Mask identifying bits of alpha component */ }; #pragma pack(pop) Bitmap loadBMP(char* path, readFile_t* readFunction, ThreadContext *thread) { FileReadResult result = readFunction(thread, path); Bitmap retBitmap = {}; BitmapHeader *header = (BitmapHeader*)(result.memory); Assert(header->Compression == 3); retBitmap.startPixelPointer = (uint32_t*)((uint8_t*)result.memory + header->BitmapOffset); retBitmap.width = header->Width; retBitmap.height = header->Height; // Modify loaded bmp to set its pixels in the right order. Our pixel format is AARRGGBB, but bmps may vary because of their masks. int redOffset = findFirstSignificantBit(header->RedMask); int greenOffset = findFirstSignificantBit(header->GreenMask); int blueOffset = findFirstSignificantBit(header->BlueMask); int alphaOffset = findFirstSignificantBit(header->AlphaMask); uint32_t *modifyingPixelPointer = retBitmap.startPixelPointer; for (int j = 0; j < header->Height; j++) { for (int i = 0; i < header->Width; i++) { int newRedValue = ((*modifyingPixelPointer & header->RedMask) >> redOffset) << 16; int newGreenValue = ((*modifyingPixelPointer & header->GreenMask) >> greenOffset) << 8; int newBlueValue = ((*modifyingPixelPointer & header->BlueMask) >> blueOffset) << 0; int newAlphaValue = ((*modifyingPixelPointer & header->AlphaMask) >> alphaOffset) << 24; *modifyingPixelPointer = newAlphaValue | newRedValue | newGreenValue | newBlueValue; //OG RRGGBBAA modifyingPixelPointer++; } } return retBitmap; } float clamp(float value) { if (value < 0) { return 0; } else { return value; } } void displayBMP(uint32_t *bufferMemory, const Bitmap *bitmap, float x, float y, int screenWidth, int screenHeight) { y += bitmap->offset.y; x += bitmap->offset.x; //x = clamp(x); //y = clamp(y); int drawHeight = bitmap->height; int drawWidth = bitmap->width; if (drawHeight + y > screenHeight) { drawHeight = (int)(screenHeight - y); } if (drawWidth + x > screenWidth) { drawWidth = (int)(screenWidth - x); } // Go to upper left corner. bufferMemory += (int)clamp((float)screenWidth * (screenHeight - (bitmap->height + roundFloat(clamp(y))))); bufferMemory += roundFloat(clamp(x)); uint32_t* pixelPointer = bitmap->startPixelPointer; pixelPointer += (drawHeight-1) * bitmap->width; if (x < 0) { drawWidth += roundFloat(x); pixelPointer -= roundFloat(x); } if (y < 0) { drawHeight += roundFloat(y); bufferMemory -= screenWidth * (roundFloat(y)); } int strideToNextRow = screenWidth - drawWidth; if (strideToNextRow < 0) { strideToNextRow = 0; } for (int j = 0; j < drawHeight; j++) { for (int i = 0; i < drawWidth; i++) { float alphaValue = (*pixelPointer >> 24) / 255.0f; uint32_t redValueS = (*pixelPointer & 0xFF0000) >> 16; uint32_t greenValueS = (*pixelPointer & 0x00FF00) >> 8; uint32_t blueValueS = (*pixelPointer & 0x0000FF); uint32_t redValueD = (*bufferMemory & 0xFF0000) >> 16; uint32_t greenValueD = (*bufferMemory & 0x00FF00) >> 8; uint32_t blueValueD = *bufferMemory & 0x0000FF; uint32_t interpolatedPixel = (uint32_t)(alphaValue * redValueS + (1 - alphaValue) * redValueD) << 16 | (uint32_t)(alphaValue * greenValueS + (1 - alphaValue) * greenValueD) << 8 | (uint32_t)(alphaValue * blueValueS + (1 - alphaValue) * blueValueD); *bufferMemory = interpolatedPixel; bufferMemory++; pixelPointer++; // left to right } pixelPointer += bitmap->width - drawWidth; // Remainder pixelPointer -= 2* bitmap->width; // start at the top, go down bufferMemory += strideToNextRow; } } extern "C" GAMECODE_API UPDATE_AND_RENDER(updateAndRender) { GameState* gameState = (GameState*)gameMemory->permanentStorage; Assert(sizeof(GameState) <= gameMemory->permanentStorageSize); if (!gameMemory->isinitialized) { gameState->background = loadBMP("../data/test/test_background.bmp", gameMemory->readFile, thread); gameState->guyHead[0] = loadBMP("../data/test/test_hero_back_head.bmp", gameMemory->readFile, thread); gameState->guyHead[1] = loadBMP("../data/test/test_hero_front_head.bmp", gameMemory->readFile, thread); gameState->guyHead[2] = loadBMP("../data/test/test_hero_left_head.bmp", gameMemory->readFile, thread); gameState->guyHead[3] = loadBMP("../data/test/test_hero_right_head.bmp", gameMemory->readFile, thread); gameState->guyCape[0] = loadBMP("../data/test/test_hero_back_cape.bmp", gameMemory->readFile, thread); gameState->guyCape[1] = loadBMP("../data/test/test_hero_front_cape.bmp", gameMemory->readFile, thread); gameState->guyCape[2] = loadBMP("../data/test/test_hero_left_cape.bmp", gameMemory->readFile, thread); gameState->guyCape[3] = loadBMP("../data/test/test_hero_right_cape.bmp", gameMemory->readFile, thread); gameState->guyTorso[0] = loadBMP("../data/test/test_hero_back_torso.bmp", gameMemory->readFile, thread); gameState->guyTorso[1] = loadBMP("../data/test/test_hero_front_torso.bmp", gameMemory->readFile, thread); gameState->guyTorso[2] = loadBMP("../data/test/test_hero_left_torso.bmp", gameMemory->readFile, thread); gameState->guyTorso[3] = loadBMP("../data/test/test_hero_right_torso.bmp", gameMemory->readFile, thread); for (int i = 0; i < 4; i++) { gameState->guyHead[i].offset.y = -33; gameState->guyCape[i].offset.y = -33; gameState->guyTorso[i].offset.y = -33; gameState->guyHead[i].offset.x = -52; gameState->guyCape[i].offset.x = -52; gameState->guyTorso[i].offset.x = -52; } // Construct world initWorldArena(&gameState->worldArena, (uint8_t*)gameMemory->permanentStorage + sizeof(GameState), (size_t)(gameMemory->permanentStorageSize - sizeof(GameState))); gameState->world = pushStruct(&gameState->worldArena, World); gameState->world->numChunksX = 256; gameState->world->numChunksY = 256; gameState->world->numChunksZ = 8; gameState->world->bitsForTiles = 2; // 2**4 = 16 ||| bitsForTiles**tilesPerChunk = desired num of tiles per chunk gameState->world->tilesPerChunk = 4; gameState->world->tileSize = 1.0f; gameState->world->chunks = pushArray(&gameState->worldArena, gameState->world->numChunksX * gameState->world->numChunksY * gameState->world->numChunksZ, Chunk); int randomNumbers[10] = { 5, 6, 15, 18, 20, 3, 6, 8, 16, 19 }; int randomNumberIdx = 0; int screenOffsetX = 0; int screenOffsetY = 0; bool doorLeft = false; bool doorRight = false; bool doorUp = false; bool doorDown = false; const int SCREENS_TO_GENERATE = 15; for (int s = 0; s < SCREENS_TO_GENERATE; s++) { // Get random next room and stairs int randomNumber = randomNumbers[randomNumberIdx]; int nextOffsetX = screenOffsetX; int nextOffsetY = screenOffsetY; if ((randomNumber % 2) == 1) { doorRight = true; nextOffsetX += 1; } else { doorUp = true; nextOffsetY += 1; } randomNumberIdx = (randomNumberIdx + 1) % 10; int randomStairs = randomNumbers[(randomNumberIdx + 1) % 10] % 2; int stairsPosX = 5; int stairsPosY = 7; int zScreensToWrite = 1; if (randomStairs) { zScreensToWrite = 2; } for (int zScreen = 0; zScreen < zScreensToWrite; zScreen++) { for (int j = 0; j < SCREEN_TILE_HEIGHT; j++) { for (int i = 0; i < SCREEN_TILE_WIDTH; i++) { int valueToWrite = 1; if (j == 0) { if (!(i == SCREEN_TILE_WIDTH / 2 && doorDown)) { valueToWrite = 2; } } else if (j == SCREEN_TILE_HEIGHT - 1) { if (!(i == SCREEN_TILE_WIDTH / 2 && doorUp)) { valueToWrite = 2; } } else if (i == 0) { if (!(j == SCREEN_TILE_HEIGHT / 2 && doorLeft)) { valueToWrite = 2; } } else if (i == SCREEN_TILE_WIDTH - 1) { if (!(j == SCREEN_TILE_HEIGHT / 2 && doorRight)) { valueToWrite = 2; } } setTileValue(&gameState->worldArena, gameState->world, i + screenOffsetX * SCREEN_TILE_WIDTH, j + screenOffsetY * SCREEN_TILE_HEIGHT, zScreen, valueToWrite); } } if (randomStairs) { if (zScreen == 0) { setTileValue(&gameState->worldArena, gameState->world, stairsPosX + screenOffsetX * SCREEN_TILE_WIDTH, stairsPosY + screenOffsetY * SCREEN_TILE_HEIGHT, zScreen, 3); //Up } else { setTileValue(&gameState->worldArena, gameState->world, stairsPosX + screenOffsetX * SCREEN_TILE_WIDTH, stairsPosY + screenOffsetY * SCREEN_TILE_HEIGHT, zScreen, 4); //Down } } } doorLeft = doorRight; doorDown = doorUp; doorRight = false; doorUp = false; screenOffsetX = nextOffsetX; screenOffsetY = nextOffsetY; } // Player Vector2 player = { 1,2 }; int playerZ = 0; gameState->playerCoord = constructCoordinate(gameState->world, {0,0}, playerZ, player); gameState->offsetInTile = { 0.0, 0.0 }; gameState->velocity = { 0,0 }; gameState->orientation = 1; gameMemory->isinitialized = true; } World* overworld = gameState->world; static float playerSpeed = 40.0f; static float drag = 5.0f; Vector2 playerAcceleration = { 0,0 }; float playerWidth = 0.8f; float playerHeight = 1; Vector2 newOffset = gameState->offsetInTile; if (inputState.Left_Stick.xPosition < 0) { playerAcceleration.x = -playerSpeed; gameState->orientation = 2; } if (inputState.Left_Stick.xPosition > 0) { playerAcceleration.x = playerSpeed; gameState->orientation = 3; } if (inputState.Left_Stick.yPosition < 0) { playerAcceleration.y = playerSpeed; gameState->orientation = 0; } if (inputState.Left_Stick.yPosition > 0) { playerAcceleration.y = -playerSpeed; gameState->orientation = 1; } if (inputState.Left_Stick.yPosition != 0 && inputState.Left_Stick.xPosition != 0) { // Moving diagonally playerAcceleration /= 1.41f; // sqrt(2) } newOffset += playerAcceleration * square(inputState.deltaTime) / 2.0f + inputState.deltaTime * gameState->velocity; gameState->velocity += playerAcceleration * inputState.deltaTime - drag * gameState->velocity * inputState.deltaTime; Vector2 offsetLx = newOffset - Vector2{ playerWidth / 2.0f, playerHeight / 2.0f}; Vector2 offsetRx = newOffset + Vector2{ playerWidth / 2.0f, -playerHeight / 2.0f }; AbsoluteCoordinate middle = canonicalize(overworld, &gameState->playerCoord, &newOffset); AbsoluteCoordinate left = canonicalize(overworld, &gameState->playerCoord, &offsetLx); AbsoluteCoordinate right = canonicalize(overworld, &gameState->playerCoord, &offsetRx); if (canMove(overworld, middle) && canMove(overworld, left) && canMove(overworld, right)) { if (gameState->playerCoord != middle) { if (getTileValue(overworld, middle) == 3) { middle.z = 1; } else if (getTileValue(overworld, middle) == 4) { middle.z = 0; } } gameState->playerCoord = middle; gameState->offsetInTile = newOffset; } drawRectangle(bitmapMemory, width, height, 0, 0, (float)width, (float)height, 0.0f, 0.0f, 0.0f); // Clear screen to black Vector2 playerScreen = getTile(overworld, gameState->playerCoord) + getChunk(overworld, gameState->playerCoord) * (float)overworld->tilesPerChunk; // Draw TileMap displayBMP((uint32_t*)bitmapMemory, &gameState->background, 0, 0, width, height); float grayShadeForTile = 0.5; Vector2 currentScreen = {(float)((int)(playerScreen.x) / SCREEN_TILE_WIDTH), (float)((int)(playerScreen.y) / SCREEN_TILE_HEIGHT)}; for (int j = 0; j < SCREEN_TILE_HEIGHT; j++) { for (int i = 0; i < SCREEN_TILE_WIDTH; i++) { AbsoluteCoordinate tileCoord; tileCoord = constructCoordinate(overworld, { 0, 0 }, gameState->playerCoord.z, { i + currentScreen.x * SCREEN_TILE_WIDTH, j + currentScreen.y * SCREEN_TILE_HEIGHT }); if (getTileValue(overworld, tileCoord) == 1) { grayShadeForTile = 0.5; } else if (getTileValue(overworld, tileCoord) == 2) { grayShadeForTile = 1.0; } else if (getTileValue(overworld, tileCoord) == 3) { grayShadeForTile = 0.8f; } else if (getTileValue(overworld, tileCoord) == 4) { grayShadeForTile = 0.6f; } else { continue; } if (playerScreen == Vector2{i + currentScreen.x * SCREEN_TILE_WIDTH, j + currentScreen.y * SCREEN_TILE_HEIGHT}) { grayShadeForTile = 0.2f; } float minX = unitsToPixels((float)(overworld->tileSize * i)); float maxX = unitsToPixels((float)(overworld->tileSize * (i+1))); float minY = unitsToPixels((float)(overworld->tileSize * j)); float maxY = unitsToPixels((float)(overworld->tileSize * (j +1))); drawRectangle(bitmapMemory, width, height, minX, minY, maxX, maxY, grayShadeForTile, grayShadeForTile, grayShadeForTile); } } // Draw Player drawRectangle(bitmapMemory, width, height, unitsToPixels(playerScreen.x + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH) , unitsToPixels(playerScreen.y + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT), unitsToPixels(playerScreen.x + playerWidth + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH) , unitsToPixels(playerScreen.y + playerHeight + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT) , 1.0f, 1.0f, 0.0f); // Load data //displayBMP((uint32_t*)bitmapMemory, &gameState->guyTorso[gameState->orientation], unitsToPixels(playerScreen.x), unitsToPixels(playerScreen.y), width, height); //displayBMP((uint32_t*)bitmapMemory, &gameState->guyCape[gameState->orientation], unitsToPixels(playerScreen.x), unitsToPixels(playerScreen.y), width, height); /* drawRectangle(bitmapMemory, width, height, unitsToPixels(playerScreen.x + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH), unitsToPixels(playerScreen.y + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT), unitsToPixels(playerScreen.x + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH) + gameState->guyHead[gameState->orientation].width, unitsToPixels(playerScreen.y + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT) + gameState->guyHead[gameState->orientation].height, 1.0f, 0.0f, 0.0f);*/ displayBMP((uint32_t*)bitmapMemory, &gameState->guyTorso[gameState->orientation], unitsToPixels(playerScreen.x + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH), unitsToPixels(playerScreen.y + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT), width, height); displayBMP((uint32_t*)bitmapMemory, &gameState->guyCape[gameState->orientation], unitsToPixels(playerScreen.x + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH), unitsToPixels(playerScreen.y + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT), width, height); displayBMP((uint32_t*)bitmapMemory, &gameState->guyHead[gameState->orientation], unitsToPixels(playerScreen.x + gameState->offsetInTile.x - currentScreen.x * SCREEN_TILE_WIDTH), unitsToPixels(playerScreen.y + gameState->offsetInTile.y - currentScreen.y * SCREEN_TILE_HEIGHT), width, height); //displayBMP((uint32_t*)bitmapMemory, &gameState->guyHead[gameState->orientation],0, 0, width, height); Vector2 v = { 2,3 }; Vector2 b = { 3,4 }; v += b; }
true
b4e1e9251819b88d80951d53b0857968aae62f52
C++
ShadowKingdoms/BAKEJOON
/모래시계.cpp
UTF-8
380
2.890625
3
[]
no_license
#include<iostream> using namespace std; int main() { int a; cin >> a; int i, j, k; for (i = 0; i < a; i++) { for (j = 0; j < i; j++) cout << " "; for (j = (a - i - 1) * 2; j >= 0; j--) cout << "*"; cout << endl; } for (i = 2; i <= a; i++) { for (j = 1; j <= a - i; j++) cout << " "; for (k = 0; k <= 2 * (i - 1); k++) cout << "*"; cout << endl; } }
true
e8137a727a3df9f721ac8172ce8e1a9a1f7f1285
C++
lydrainbowcat/tedukuri
/配套光盘/例题/0x10 基本数据结构/0x11 栈/火车进出栈问题/CH1101 火车进栈 方法一.cpp
UTF-8
485
2.546875
3
[]
no_license
//Author:XuHt #include <cstdio> #include <iostream> using namespace std; const int N = 26; int n, num = 0, st[N], top = 0, ans[N], t = 0; void z(int x) { if (x == n + 1) { if (++num > 20) exit(0); for (int i = 1; i <= t; i++) printf("%d", ans[i]); for (int i = top; i; i--) printf("%d", st[i]); cout << endl; return; } if (top) { ans[++t] = st[top--]; z(x); st[++top] = ans[t--]; } st[++top] = x; z(x + 1); --top; } int main() { cin >> n; z(1); return 0; }
true
40b10411fbd840ab456fcef26af77a753771882a
C++
Mervyn-Jian/LeetcodePractice
/117. Populating Next Right Pointers in Each Node II/bfsExtraSpace.cpp
UTF-8
1,055
3.453125
3
[]
no_license
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() {} Node(int _val, Node* _left, Node* _right, Node* _next) { val = _val; left = _left; right = _right; next = _next; } }; */ class Solution { public: Node* connect(Node* root) { deque<Node*> que; if(root != NULL) que.push_back(root); while(!que.empty()){ int qSize = que.size(); for(int i=qSize-2; i>=0; i--){ Node* nextNode = *(que.begin() + i + 1); Node* curNode = *(que.begin() + i); curNode->next = nextNode; } for(int i=0; i<qSize; i++){ Node* node = que.front(); que.pop_front(); if(node->left != NULL) que.push_back(node->left); if(node->right != NULL) que.push_back(node->right); } } return root; } };
true
39797f46c950892eb7c5047df82deadda03dc1c8
C++
useyourfeelings/POJ
/2922/3757026_WA.cc
UTF-8
1,492
2.734375
3
[]
no_license
#include<iostream> using namespace std; int org[100][100]; int temp[100][100]; int scenario, Scenario, n, i, mid; int highest, lowest, high, low; void init() { int i, j; scanf("%d", &n); highest = 0; lowest = 200; for(i = 0; i < n; ++ i) for(j = 0; j < n; ++ j) { scanf("%d", &org[i][j]); if(org[i][j] > highest) highest = org[i][j]; else if(org[i][j] < lowest) lowest = org[i][j]; } } int search(int r, int c) { if(r < 0 || r >= n || c < 0 || c >= n || temp[r][c] == 1 || org[r][c] < low || org[r][c] > mid) return 0; temp[r][c] = 1; return (r == (n - 1) && c == (n - 1)) || search(r + 1, c) || search(r - 1, c) || search(r, c + 1) || search(r, c - 1); } int mindiff() { init(); int best = 200; for(low = lowest; low <= highest; ++ low) { i = low; high = highest + 1; while(i < high) { memset(temp, 0, sizeof(temp)); mid = (i + high) / 2; if(search(0, 0)) high = mid; else i = mid + 1; } if(high != highest + 1) if(high - low < best) best = high - low; } return best; } int main() { scanf("%d", &Scenario); for(scenario = 1; scenario <= Scenario; ++ scenario) { printf("Scenario #%d:\n%d\n\n", scenario, mindiff()); } return 0; }
true
a034792daef58b6e030df12a9e2720bc9752beb0
C++
demaisj/synth
/src/midi/messages/control_change.hpp
UTF-8
730
2.890625
3
[]
no_license
#pragma once #include <string> #include "base.hpp" #include "../protocol.hpp" namespace midi { class control_change_message : public message_base { public: control_change_message(const unsigned char data[]) : _channel(protocol::get_command_channel(data[0])), _control(data[1]), _value(data[2]) {} const std::string string() const { return "midi::control_change_message(channel=" + std::to_string(_channel) + ",control=" + std::to_string(_control) + ",value=" + std::to_string(_value) + ")"; } char channel() const { return _channel; } char control() const { return _control; } char value() const { return _value; } private: char _channel; char _control; char _value; }; }
true
bbfbefa31aff2d653c58aa6122d49612db578d77
C++
kmsmith137/rf_kernels
/time-std-dev-clipper.cpp
UTF-8
2,462
2.609375
3
[]
no_license
#include "rf_kernels/core.hpp" #include "rf_kernels/internals.hpp" #include "rf_kernels/unit_testing.hpp" #include "rf_kernels/std_dev_clipper.hpp" using namespace std; using namespace rf_kernels; struct std_dev_clipper_timing_thread : public kernel_timing_thread { std_dev_clipper_timing_thread(const shared_ptr<timing_thread_pool> &pool_, const kernel_timing_params &params_) : kernel_timing_thread(pool_, params_) { } virtual void thread_body() override { this->allocate(); // The std_dev_clipper's running time depends on what fraction of data // actually gets masked! For the test, I decided to fill 'intensity' // with random values, set all weights to 1, clip at 1-sigma, and // reset all weights to 1 between iterations of the timing loop. std::random_device rd; std::mt19937 rng(rd()); for (int i = 0; i < nfreq * stride; i++) intensity[i] = uniform_rand(rng, -1.0, 1.0); for (int Df: { 1, 2, 4, 8, 16, 64, 256 }) { for (int Dt: { 1, 2, 4, 8, 16 }) { for (axis_type axis: { AXIS_FREQ, AXIS_TIME }) { for (bool two_pass: {false,true}) { stringstream ss; ss << "std_dev_clipper(axis=" << axis << ",Df=" << Df << ",Dt=" << Dt << ",two_pass=" << two_pass << ")"; string s = ss.str(); const char *cp = s.c_str(); double sigma = 1.0; std_dev_clipper sd(nfreq, nt_chunk, axis, sigma, Df, Dt, two_pass); this->start_timer(); for (int iter = 0; iter < this->niter; iter++) { // As described above, we reset all weights to 1 between // iterations of the timing loop. We pause the timer so // that this resetting isn't included in the timing result. this->pause_timer(); for (int ifreq = 0; ifreq < nfreq; ifreq++) for (int it = 0; it < nt_chunk; it++) weights[ifreq*stride + it] = 1.0; this->unpause_timer(); sd.clip(intensity, stride, weights, stride); } this->stop_timer2(cp); } } } } } }; int main(int argc, char **argv) { kernel_timing_params params("time-std-dev-clipper"); params.parse_args(argc, argv); int nthreads = params.nthreads; auto pool = make_shared<timing_thread_pool> (nthreads); vector<std::thread> threads; for (int i = 0; i < nthreads; i++) threads.push_back(spawn_timing_thread<std_dev_clipper_timing_thread> (pool, params)); for (int i = 0; i < nthreads; i++) threads[i].join(); return 0; }
true
d057b08f8cf10e87d777eba5d575eb7f7de7e4df
C++
WeiMengXS/blog_systeam
/blog_systeam.cc
UTF-8
8,906
2.671875
3
[]
no_license
#include "db.hpp" #include "httplib.h" //int test() //{ //MYSQL* mysql=blog_systream::Mysqlinit(); //blog_systream::TableUser table_user(mysql); //Json::Value user; //user["name"]="陈东瑞"; //table_user.Insert(user); //user.clear(); //user["name"]="蔡自桂"; /*table_user.Insert(user); user.clear(); user["name"]="马新航"; table_user.Insert(user); table_user.GetOne(5,&user); table_user.Delete(5); Json::Reader reader; Json::StyledWriter writer; std::cout<<writer.write(user)<<std::endl; blog_systream::MysqlRelease(mysql); return 0; }i */ blog_systream::TableUser *table_user; blog_systream::TableTag *table_tag; blog_systream::TableBlog *table_blog; void InsertUser(const httplib::Request &req,httplib::Response &rsp) { //用户信息在req的body中。 //1.获取json字符串 std:: string json_user=req.body; Json::Reader reader; Json::Value root; bool ret=reader.parse(json_user,root); if(ret==false) { printf("InsertUser body info json error"); rsp.status=400;//请求错误 return ; } //2.江字符串转换为VALU格式 //3。调用接口修改数据库 ret=table_user->Insert(root); if(ret==false){ printf("insert user value error"); rsp.status=500; return ; } rsp.status=200; //4.填充rsp响应 return ; } void DeleteUser(const httplib::Request &req,httplib::Response &rsp) { int user_id =std::stoi(req.matches[1]); bool ret=table_user->Delete(user_id); if(ret==false) { printf("Delete info user seq error"); rsp.status=500; return ; } rsp.status=200; return ; } void UpdateUser(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"更新用户"<<std::endl; int user_id =std::stoi(req.matches[1]); std::string json_user =req.body; Json::Reader reader; Json::Value root; bool ret =reader.parse(json_user,root); rsp.status=200; if(ret==false) { printf("Update js error"); rsp.status=400; return ; } ret=table_user->Update(user_id,root); if(ret==false) { printf("server is error update error"); rsp.status=500; return ; } rsp.status=200; return ; } void GetOneUser(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"获取单个用户"<<std::endl; Json::Value root; int user_id=stoi(req.matches[1]); bool ret=table_user->GetOne(user_id,&root); if(ret==false) { printf("Get one for server is error"); rsp.status=500; return ; } Json::FastWriter writer; rsp.set_content(writer.write(root),"application/json"); return ; } void GetAllUser(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"获取所有用户"<<std::endl; Json::Value root; bool ret=table_user->GetAll(&root); if(ret==false) { printf("Get all is error json"); rsp.status=500; return ; } Json::FastWriter writer; std::string body; body=writer.write(root); rsp.set_content(body,"application/json"); return ; } void InsertTag(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"插入单个标签"<<std::endl; std::string json_tag=req.body; Json::Value root; Json::Reader reader; bool ret=reader.parse(json_tag,root); if(ret==false) { printf("Insert tag is error reader"); rsp.status=400; return ; } ret=table_tag->Insert(root); if(ret==false){ printf("Insert tag is db error"); rsp.status=500; return ; } rsp.status=200; return ; } void DeleteTag(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"删除单个标签"<<std::endl; int tag_id=std::stoi(req.matches[1]); bool ret=table_tag->Delete(tag_id); if(ret==false) { printf("Tag delete is error for db"); rsp.status=500; return ; } rsp.status=200; return ; } void UpdateTag(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"更新标签"<<std::endl; int tag_id=std::stoi(req.matches[1]); std::string json_tag=req.body; Json::Reader reader; Json::Value root; bool ret=reader.parse(json_tag,root); if(ret==false) { printf("Tag update is error for reader"); rsp.status=400; return ; } ret=table_tag->Update(tag_id,root); if(ret==false) { printf("Tag update is error for db"); rsp.status=500; return ; } rsp.status=200; return ; } void GetOneTag(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"获取单个标签"<<std::endl; Json::Value root; int tag_id=stoi(req.matches[1]); bool ret=table_tag->GetOne(tag_id,&root); if(ret==false) { printf("Get tagone for server is error"); rsp.status=500; return ; } Json::FastWriter writer; rsp.set_content(writer.write(root),"application/json"); return ; } void GetAllTag(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"获取所有标签"<<std::endl; Json::Value root; bool ret=table_tag->GetAll(&root); if(ret==false) { printf("Get all tag is error json"); rsp.status=500; return ; } Json::FastWriter writer; std::string body; body=writer.write(root); rsp.set_content(body,"application/json"); return ; } void InsertBlog(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"插入博客"<<std::endl; std::string json_str=req.body; Json::Value root; Json::Reader reader; bool ret=reader.parse(json_str,root); if(ret==false) { printf("Insert blog is error reader"); rsp.status=400; return ; } ret=table_blog->Insert(root); if(ret==false){ printf("Insert blog is db error"); rsp.status=500; return ; } rsp.status=200; return ; } void DeleteBlog(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"删除博客"<<std::endl; int blog_id=std::stoi(req.matches[1]); bool ret=table_blog->Delete(blog_id); if(ret==false) { printf("blog delete is error for db"); rsp.status=500; return ; } rsp.status=200; } void UpdateBlog(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"更新博客"<<std::endl; int blog_id=std::stoi(req.matches[1]); std::string json_str=req.body; Json::Reader reader; Json::Value root; bool ret=reader.parse(json_str,root); if(ret==false) { printf("Blog update is error for reader"); rsp.status=400; return ; } ret=table_blog->Updeta(blog_id,root); if(ret==false) { printf("blog update is error for db"); rsp.status=500; return ; } rsp.status=200; return ; } void GetOneBlog(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"获取单个博客"<<std::endl; Json::Value root; int blog_id=std::stoi(req.matches[1]); bool ret=table_blog->GetOne(blog_id,&root); if(ret==false){ printf("GetOneBlog is error 283"); rsp.status=500; return ; } Json::FastWriter writer; rsp.set_content(writer.write(root),"application"); rsp.status=200; return ; } void GetAllBlog(const httplib::Request &req,httplib::Response &rsp) { std::cout<<"获取所有博客"<<std::endl; bool ret; Json::Value root; if(req.has_param("tag_id")) { int tag_id=std::stoi(req.get_param_value("tag_id")); ret=table_blog->GetOne(tag_id,&root); if(ret==false) { printf("blog gettag is error for db"); rsp.status=500; return ; } } else if(req.has_param("user_id")){ int user_id=std::stoi(req.get_param_value("user_id")); ret=table_blog->GetUser(user_id,&root); if(ret==false) { printf("blog getuser is error for db"); rsp.status=500; return ; } } else { ret = table_blog->GetAll(&root); if(ret==false) { printf("get blog all is error"); rsp.status=500; return ; } } Json::FastWriter writer; rsp.set_content(writer.write(root),"application/json"); rsp.status=200; return ; } #define WWWROT "./www" int main() { MYSQL* mysql=blog_systream::Mysqlinit(); if(mysql==NULL) { return -1; } table_blog=new blog_systream::TableBlog(mysql); table_tag=new blog_systream::TableTag(mysql); table_user=new blog_systream::TableUser(mysql); httplib::Server server; server.set_base_dir(WWWROT); //路由注册处理函数可以是一个正则表达式。 //正则表达式在:匹配某种规则,特定格式的字符串 server.Post(R"(/user)",InsertUser); server.Delete(R"(/user/(\d+))",DeleteUser); server.Put(R"(/user/(\d+))",UpdateUser); server.Get(R"(/user)",GetAllUser); server.Get(R"(/user/(\d+))",GetOneUser); server.Post(R"(/tag)",InsertTag); server.Delete(R"(/tag/(\d+))",DeleteTag); server.Put(R"(/tag/(\d+))",UpdateTag); server.Get(R"(/tag)",GetAllTag); server.Get(R"(/tag/(\d+))",GetOneTag); server.Post(R"(/blog)",InsertBlog); server.Delete(R"(/blog/(\d+))",DeleteBlog); server.Put(R"(/blog/(\d+))",UpdateBlog); server.Get(R"(/blog)",GetAllBlog); server.Get(R"(/blog/(\d+))",GetOneBlog); server.listen("0.0.0.0",9000); blog_systream::MysqlRelease(mysql); return 0; }
true
2e9d75342079ca7af1cb22ae648e335558fee162
C++
CodesbyUnnati/Round3__100DaysOfCode
/Hackerrank/Divisible_sum_pairs.cpp
UTF-8
1,377
3.75
4
[]
no_license
//QUESTION /* You are given an array of integers, , and a positive integer, . Find and print the number of pairs where and + is divisible by . For example, and . Our three pairs meeting the criteria are and . Function Description Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria. divisibleSumPairs has the following parameter(s): n: the integer length of array ar: an array of integers k: the integer to divide the pair sum by Input Format The first line contains space-separated integers, and . The second line contains space-separated integers describing the values of . Constraints Output Format Print the number of pairs where and + is evenly divisible by . Sample Input 6 3 1 3 2 6 1 2 Sample Output 5 */ //SOLUTION #include <iostream> using namespace std; int main() { int a[20]; int k; int n; int count = 0; cout << "Enter size of array: "; cin >> n; for (int i = 0; i < n - 1; i++) { cin >> a[i]; } cout << "Enter the number divisible: "; cin >> k; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if ((a[i] + a[j]) % k == 0) { count++; } } } cout << "The answer is: " << count; return 0; }
true
4b036cb83f402674e733264b72b83b88455eca27
C++
jakewhitton/robotarm
/graphics_example/main.cpp
UTF-8
5,654
3.1875
3
[]
no_license
#include <SDL2/SDL.h> #include <cmath> #include <cstdio> const float pi = 3.1415926; //Useful structs struct Vec { float x; float y; }; struct Line { Vec start; Vec end; }; //Function prototypes Line calculateLine(float theta, float length, Vec startPoint); Vec calculateAngularVelocity(float alpha, float beta, Vec velocity); void drawLine(const Line& line, SDL_Renderer* render); bool init(); void close(); //USER TWEAKABLE VARIABLES const int length1 = 200; const int length2 = 350; const int margin = 50; float a = pi / 3; float b = -pi / 6; float aVel = 0; float bVel = 0; float aVelMax = 2 * pi; float bVelMax = 2 * pi; //Init variables const int SCREEN_WIDTH = 2 * (length1 + length2 + margin); const int SCREEN_HEIGHT = (2 * margin) + (length1 + length2); Line line1 = calculateLine(a, length1, Vec{SCREEN_WIDTH / 2, margin}); Line line2 = calculateLine(b, length2, line1.end); SDL_Window* window = NULL; SDL_Renderer* renderer = NULL; int main(int argc, char* args[]) { if( !init() ) { printf( "Failed to initialize!\n" ); } else { bool quit = false; SDL_Event event; int ticks = 0; int iterationTime = 0; bool buttonDown = false; Vec origin; Vec currentPosition; Vec cartesianVelocity; Vec angularVelocity; while(!quit) { ticks = SDL_GetTicks(); while(SDL_PollEvent( &event ) != 0) { if (event.type == SDL_QUIT) { quit = true; } if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) { buttonDown = true; origin = Vec{(float)event.button.x, (float)event.button.y}; } if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) { buttonDown = false;; } if (event.type == SDL_MOUSEMOTION) { currentPosition = Vec{(float)event.motion.x, (float)event.motion.y}; } } //Clear screen SDL_SetRenderDrawColor( renderer, 0x00, 0x00, 0x00, 0xFF ); SDL_RenderClear( renderer ); //User rendering //Update cartesian velocity if left mouse button is pressed down if (buttonDown) { cartesianVelocity = Vec{currentPosition.x - origin.x, (float)-1.0000 * (currentPosition.y - origin.y)}; angularVelocity = calculateAngularVelocity(a, b, cartesianVelocity); } else { cartesianVelocity = Vec{0.0000f, 0.0000f}; angularVelocity = Vec{0.0000f, 0.0000f}; } aVel = angularVelocity.x; bVel = angularVelocity.y; //Update a and b a = a + ((float)iterationTime / 1000.0000 * aVel); b = b + ((float)iterationTime / 1000.0000 * bVel); //Update lines line1 = calculateLine(a, length1, line1.start); line2 = calculateLine(b, length2, line1.end); SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); drawLine(line1, renderer); drawLine(line2, renderer); SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF); drawLine(Line{line2.end, Vec{line2.end.x + cartesianVelocity.x, line2.end.y + cartesianVelocity.y}}, renderer); //Update screen SDL_RenderPresent( renderer ); //Update iteration time(in ms) iterationTime = SDL_GetTicks() - ticks; } } close(); return 0; } Line calculateLine(float theta, float length, Vec startPoint) { return Line{startPoint, Vec{startPoint.x + (length * (float)cos(theta)), startPoint.y + (length * (float)sin(theta))}}; } void drawLine(const Line& line, SDL_Renderer* render) { SDL_RenderDrawLine(render, rint(line.start.x), SCREEN_HEIGHT - rint(line.start.y), rint(line.end.x), SCREEN_HEIGHT - rint(line.end.y) ); } bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( window == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create renderer for window renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); if( renderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( renderer, 0xFF, 0xFF, 0xFF, 0xFF ); } } } return success; } void close() { //Destroy window SDL_DestroyRenderer( renderer ); SDL_DestroyWindow( window ); window = NULL; renderer = NULL; //Quit SDL subsystems SDL_Quit(); } Vec calculateAngularVelocity(float alpha, float beta, Vec velocity) { float motif1 = (velocity.y * sin(alpha) ) + ( velocity.x * cos(alpha) ); float motif2 = ( sin(alpha)*cos(beta) ) - ( cos(alpha) * sin(beta) ); if (motif2 != 0 && alpha != 0) { float motif = motif1 / motif2; Vec angularVelocityVector = Vec{ -1.0000f / length1 / (float)sin(alpha) * (velocity.x + ( (float)sin(beta) * motif ) ), (float)1 / (float)length2 * motif}; float scalingFactor = 1; if (angularVelocityVector.x > aVelMax) { scalingFactor = aVelMax / angularVelocityVector.x; } else if (angularVelocityVector.y > bVelMax) { scalingFactor = bVelMax / angularVelocityVector.y; } angularVelocityVector = Vec{angularVelocityVector.x * scalingFactor, angularVelocityVector.y * scalingFactor}; return angularVelocityVector; } else { return calculateAngularVelocity(alpha + 0.0001f, beta - 0.0001f, velocity); } }
true
689917e871cf5e77f09c40b4eeba5c3bae543640
C++
lucycosta/ProjetoLiP2018.2
/cplusplus.cpp
UTF-8
13,669
2.9375
3
[]
no_license
#include <iostream> #include <cstring> #include <cstdlib> #include <time.h> #define MAX 40 #define NAME struct tempos{ int times = 0; char nomes[NAME] = {}; }; using namespace std; char conversor(int n); int telaInicial(int inicio, int nivel); void imprimeCampo(char campo[MAX][MAX], int linha, int coluna, int tempo, tempos t); void preencher(char campo[MAX][MAX], int linha, int coluna, int nivel, int tempo, tempos t, int minas); void comandos(char campoReal[MAX][MAX], char campo[MAX][MAX],int linha, int coluna, int nivel, int minas,int tempo, tempos t); void resultado(char campoReal[MAX][MAX], char campo[MAX][MAX], int comando, int minas, int linha, int coluna, int nivel, int linha_esc, int coluna_esc,int tempo, tempos t); void varredura(char campoReal[MAX][MAX], char campo[MAX][MAX], int linha, int coluna, int linha_esc, int coluna_esc); char conversor(int n){ int aux; aux = n+48; if(aux == 48){ aux = '_'; } return((char)aux); } int telaInicial(int inicio, int nivel){ cout<<"Novo jogo[1] "<<endl; cout<<"Melhores Tempos[2] "<<endl; cout<<"Sair[3] "<<endl; cin>>inicio; cout<<"Jogo Iniciante[1]"<<endl; cout<<"Jogo Intermediario[2]"<<endl; cout<<"Jogo Personalizado[3]"<<endl; cout<<"Voltar[4]"<<endl; cin>>nivel; return ((inicio*10)+nivel); } void imprimeCampo(char campo[MAX][MAX], int linha, int coluna, int tempo){ cout<<" "; for(int i = 0; i < coluna; i++){ cout<<i+1<<" "; } cout<<endl; cout<<endl; for(int i = 0; i < linha; i++){ if(i <= 8) cout<<i+1<<" "; else cout<<i+1<<" "; for(int j = 0; j < coluna; j++){ campo[i][j] = '.'; cout<<campo[i][j]<<" "; if(j >= 8) cout<<" "; } cout<<endl; } } void preencher(char campo[MAX][MAX], int linha, int coluna, int nivel, int tempo, tempos t, int minas){ char campoReal[MAX][MAX]; int cont; srand(time(NULL)); cout<<endl; if(nivel == 1){ minas = 10; } else if(nivel == 2){ minas = 20; } for(int i = 0; i < minas; i++){ int a = rand()%linha, b = rand()%coluna; if(campoReal[a][b] != 'x'){ campoReal[a][b] = 'x'; } else{ while(campoReal[a][b] == 'x'){ a = rand()%linha; b = rand()%coluna; } campoReal[a][b] = 'x'; } } for(int i = 0; i < linha; i++){ for(int j = 0; j < coluna; j++){ if(campoReal[i][j] != 'x'){ cont = 0; if(i == 0 && j == 0){ if(campoReal[i][j+1] == 'x') cont++; if(campoReal[i+1][j] == 'x') cont++; if(campoReal[i+1][j+1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(i == 0 && j == (coluna-1)){ if(campoReal[i][j-1] == 'x') cont++; if(campoReal[i+1][j-1] == 'x') cont++; if(campoReal[i+1][j] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(i == (linha-1) && j == 0){ if(campoReal[i-1][j] == 'x') cont++; if(campoReal[i-1][j+1] == 'x') cont++; if(campoReal[i][j+1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(i == (linha-1) && j == (coluna-1)){ if(campoReal[i-1][j] == 'x') cont++; if(campoReal[i-1][j-1] == 'x') cont++; if(campoReal[i][j-1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(i == 0 && j > 0 && j < (coluna-1)){ if(campoReal[i][j-1] == 'x') cont++; if(campoReal[i][j+1] == 'x') cont++; if(campoReal[i+1][j-1] == 'x') cont++; if(campoReal[i+1][j] == 'x') cont++; if(campoReal[i+1][j+1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(i == (linha-1) && j > 0 && j < (coluna-1)){ if(campoReal[i][j-1] == 'x') cont++; if(campoReal[i-1][j-1] == 'x') cont++; if(campoReal[i-1][j] == 'x') cont++; if(campoReal[i-1][j+1] == 'x') cont++; if(campoReal[i][j+1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(j == 0 && i > 0 && i < (linha-1)){ if(campoReal[i-1][j] == 'x') cont++; if(campoReal[i-1][j+1] == 'x') cont++; if(campoReal[i][j+1] == 'x') cont++; if(campoReal[i+1][j] == 'x') cont++; if(campoReal[i+1][j+1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else if(j == (coluna-1) && i > 0 && i < (linha-1)){ if(campoReal[i-1][j] == 'x') cont++; if(campoReal[i-1][j-1] == 'x') cont++; if(campoReal[i][j-1] == 'x') cont++; if(campoReal[i+1][j] == 'x') cont++; if(campoReal[i+1][j-1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } else{ if(campoReal[i-1][j-1] == 'x') cont++; if(campoReal[i-1][j] == 'x') cont++; if(campoReal[i-1][j+1] == 'x') cont++; if(campoReal[i][j-1] == 'x') cont++; if(campoReal[i][j+1] == 'x') cont++; if(campoReal[i+1][j-1] == 'x') cont++; if(campoReal[i+1][j] == 'x') cont++; if(campoReal[i+1][j+1] == 'x') cont++; campoReal[i][j] = conversor(cont); cont = 0; } } } campo[i][coluna] = '\0'; } comandos(campoReal, campo, linha, coluna, nivel, minas, tempo, t); } void comandos(char campoReal[MAX][MAX], char campo[MAX][MAX],int linha, int coluna, int nivel, int minas, int tempo, tempos t){ char comando; int linha_esc, coluna_esc; cout<<"Minas a marcar: "<<minas<<" "<<endl; cout<<"D --> Descobrir quadrado "<<endl; cout<<"M --> Marcar mina "<<endl; cout<<"T --> Talvez mina "<<endl; cout<<"L --> Limpar Campo "<<endl; cout<<"S --> Sair "<<endl; cin>>comando>>linha_esc>>coluna_esc; resultado(campoReal, campo, comando, minas, linha, coluna, nivel, linha_esc, coluna_esc, tempo, t); } void resultado(char campoReal[MAX][MAX], char campo[MAX][MAX], int comando, int minas, int linha, int coluna, int nivel, int linha_esc, int coluna_esc, int tempo, tempos t){ int cont_minas = 0, Melhor = time(NULL)-tempo; if(comando == 'D' || comando =='M' || comando == '?'){ if(campoReal[linha_esc-1][coluna_esc-1] == 'x' && comando == 'D'){ cout<<"Voce Perdeu"; } else{ if(comando == 'M'){ campo[linha_esc-1][coluna_esc-1] = 'M'; } else if(comando == '?'){ campo[linha_esc-1][coluna_esc-1] = '?'; } cout<<" "; for(int i = 0; i < coluna; i++){ cout<<i+1<<" "; } cout<<" Tempo atual: "<<time(NULL)-tempo<<" segundo(s)"; cout<<endl; cout<<endl; for(int i = 0; i < linha; i++){ if(i <= 8) cout<<i+1<<" "; else cout<<i+1<<" "; for(int j = 0; j < coluna; j++){ if(campo[i][j]=='M'){ cont_minas++; minas=10-cont_minas; } if(i == (linha_esc-1) && j == (coluna_esc-1) && campo[i][j] != 'M' && campo[i][j] != '?'){ campo[i][j] = campoReal[linha_esc-1][coluna_esc-1]; if(campo[i][j] == '_'){ varredura(campoReal, campo, linha, coluna, linha_esc, coluna_esc); } cout<<campo[i][j]<<" "; if(j >= 8) cout<<" "; } else{ cout<<campo[i][j]<<" "; if(j >= 8) cout<<" "; } } cout<<endl; } comandos(campoReal, campo, linha, coluna, nivel, minas, tempo, t); } } } void varredura(char campoReal[MAX][MAX], char campo[MAX][MAX], int linha, int coluna, int linha_esc, int coluna_esc){ int i = (linha_esc-1), j = (coluna_esc-1); if(i == 0 && j == 0){ campo[i][j+1] = campoReal[i][j+1]; campo[i+1][j] = campoReal[i+1][j]; campo[i+1][j+1] = campoReal[i+1][j+1]; } else if(i == 0 && j == (coluna-1)){ campo[i][j-1] = campoReal[i][j-1]; campo[i+1][j-1] = campoReal[i+1][j-1]; campo[i+1][j] = campoReal[i+1][j]; } else if(i == (linha-1) && j == 0){ campo[i-1][j] = campoReal[i-1][j]; campo[i-1][j+1] = campoReal[i-1][j+1]; campo[i][j+1] = campoReal[i][j+1]; } else if(i == (linha-1) && j == (coluna-1)){ campo[i-1][j] = campoReal[i-1][j]; campo[i-1][j-1] = campoReal[i-1][j-1]; campo[i][j-1] = campoReal[i][j-1]; } else if(i == 0 && j > 0 && j < (coluna-1)){ campo[i][j-1] = campoReal[i][j-1]; campo[i][j+1] = campoReal[i][j+1]; campo[i-1][j+1] = campoReal[i-1][j+1]; campo[i+1][j] = campoReal[i+1][j]; campo[i+1][j+1] = campoReal[i+1][j+1]; } else if(i == (linha-1) && j > 0 && j < (coluna-1)){ campo[i][j-1] = campoReal[i][j-1]; campo[i-1][j-1] = campoReal[i-1][j-1]; campo[i-1][j] = campoReal[i-1][j]; campo[i-1][j+1] = campoReal[i-1][j+1]; campo[i][j+1] = campoReal[i][j+1]; } else if(j == 0 && i > 0 && i < (linha-1)){ campo[i-1][j] = campoReal[i-1][j]; campo[i-1][j+1] = campoReal[i-1][j+1]; campo[i][j+1] = campoReal[i][j+1]; campo[i+1][j] = campoReal[i+1][j]; campo[i+1][j+1] = campoReal[i+1][j+1]; } else if(j == (coluna-1) && i > 0 && i < (linha-1)){ campo[i-1][j] = campoReal[i-1][j]; campo[i-1][j-1] = campoReal[i-1][j-1]; campo[i][j-1] = campoReal[i][j-1]; campo[i+1][j] = campoReal[i+1][j]; campo[i+1][j-1] = campoReal[i+1][j-1]; } else{ campo[i-1][j-1] = campoReal[i-1][j-1]; campo[i-1][j] = campoReal[i-1][j]; campo[i-1][j+1] = campoReal[i-1][j+1]; campo[i][j-1] = campoReal[i][j-1]; campo[i][j+1] = campoReal[i][j+1]; campo[i+1][j-1] = campoReal[i+1][j-1]; campo[i+1][j] = campoReal[i+1][j]; campo[i+1][j+1] = campoReal[i+1][j+1]; } } int main(void){ tempos t; char campo[MAX][MAX]; int tela, inicio, nivel, linha, coluna, minas = 0; int tempo = time(NULL); tela = telaInicial(inicio, nivel); if((tela/10) == 1 && (tela%10) <= 3){ if((tela%10) == 1){ linha = 8; coluna = 8; } if((tela%10) == 2){ linha = 16; coluna = 16; } if((tela%10) == 3){ cout<<"quantas linhas terao o campo? "; cin>>linha; cout<<"quantas colunas terao o campo? "; cin>>coluna; cout<<"quantas minas terao? "; cin>>minas; } imprimeCampo(campo, linha, coluna, tempo); preencher(campo, linha, coluna, (tela%10), tempo, t, minas); } else if(tela/10==4){ } return 0; } /* QUANDO IMPLEMENTADA A VITÓRIA COLOCAR ESSE ALGORITMO: for(int i = 0; i<3;i++){ if(t<t.tempos[i]){ cout<<"Entre com seu nome: "; cin.getline(nome,NAME); t[i].nomes = nome; t[i].times = Melhor; break; } } */
true
b3cfeeef476571284012dbc9f882c98d38bb8e6f
C++
EZ-Phantom/TopWordsCounter
/WordsCounter.cpp
UTF-8
3,948
3.0625
3
[ "MIT" ]
permissive
#include "WordsCounter.h" #include <QFile> #include <QDateTime> // can be used to update chart while loading file void WordsCounter::TopWordsHolder::recalculate(const Dictionary& dictionary) { for (auto dictIter = dictionary.begin(); dictIter != dictionary.end(); dictIter++) { // if not full and no such key then add if (wordsFrequence.size() < maxCount && !wordsFrequence.contains(dictIter.key())) { wordsFrequence.insert(dictIter.key(), dictIter.value()); continue; } // update value of existing key if (wordsFrequence.contains(dictIter.key())) { wordsFrequence[dictIter.key()] = dictIter.value(); continue; } // find min element auto minWordsIter = wordsFrequence.begin(); for (auto wordsIter = wordsFrequence.begin(); wordsIter != wordsFrequence.end(); wordsIter++) { if (wordsIter.value() < minWordsIter.value()) minWordsIter = wordsIter; } // replace min element if new is higher if (dictIter.value() > minWordsIter.value()) { wordsFrequence.remove(minWordsIter.key()); wordsFrequence.insert(dictIter.key(), dictIter.value()); } } } WordsCounter::WordsCounter(const QString& filePath, int topWordsCount, QObject* parent) : QObject(parent) , _filePath(filePath) , _dictionary(Dictionary()) , _topWordsHolder(TopWordsHolder{topWordsCount, {}}) { } void WordsCounter::process() { QFile file(_filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { emit canNotOpenFile(); emit finished(); return; } const auto rows = totalRows(file); quint64 lineCounter = 0; auto lastUpdate = QDateTime::currentDateTime(); while (!file.atEnd()) { auto line = QString::fromUtf8(file.readLine()); lineCounter++; for (auto word : line.split(' ')) addToDictionary(normalizeWord(word)); // emit progress signal every 100+ms if (lastUpdate.msecsTo(QDateTime::currentDateTime()) > 100) { lastUpdate = QDateTime::currentDateTime(); emit progressed(lineCounter / static_cast<double>(rows)); } } _topWordsHolder.recalculate(_dictionary); emit progressed(1.); emit finished(); } QStringList WordsCounter::getWords() const { return _topWordsHolder.wordsFrequence.keys(); } QVariantList WordsCounter::getCounts() const { auto values = _topWordsHolder.wordsFrequence.values(); QVector<QVariant> vector(values.size()); std::copy(values.begin(), values.end(), vector.begin()); return vector.toList(); } quint64 WordsCounter::getMaxFrequence() const { quint64 max = 0; for (auto iter = _topWordsHolder.wordsFrequence.begin(); iter != _topWordsHolder.wordsFrequence.end(); iter++) max = std::max(max, iter.value()); return max; } QString WordsCounter::normalizeWord(const QString& word) const { enum State { Begin, Letter }; QString nWord; State state = Begin; for (const auto ch : word) { switch (state) { case Begin : if (ch.isLetter()) { nWord.append(ch.toLower()); state = Letter; } break; case Letter : if (ch.isLetter() || ch == '-') nWord.append(ch.toLower()); else return nWord; break; } } return nWord; } void WordsCounter::addToDictionary(const QString& word) { if (word.isEmpty()) return; _dictionary[word]++; } quint64 WordsCounter::totalRows(QFile& file) const { quint64 total = 0; while (!file.atEnd()) { file.readLine(); total++; } file.seek(0); return total; }
true
b903a6d95f20294db226f718d6fba6f4a45a8c10
C++
Kaylier/Map-generator
/src/shader_program.cpp
UTF-8
6,824
2.609375
3
[ "MIT" ]
permissive
#include "shader_program.hpp" Shader_program::Shader_program() : _shaders(), _program_id(0) { } Shader_program::~Shader_program() { note("Delete shader program #%u", _program_id); glDeleteProgram(_program_id); } int Shader_program::load_shader(const char *filename, GLenum shader_type) { std::string code; std::ifstream stream(filename, std::ios::in); if(!stream.is_open()) { error("Failed to open '%s'", filename); return 0; } note("Read shader file '%s'...", filename); std::string Line; while(getline(stream, Line)) code += "\n" + Line; stream.close(); return load_shader_source(code.c_str(), shader_type); } int Shader_program::load_shader_source(const char *source, GLenum shader_type) { note("Compile %s shader...", (shader_type == GL_VERTEX_SHADER) ? "vertex" : (shader_type == GL_FRAGMENT_SHADER) ? "fragment" : (shader_type == GL_GEOMETRY_SHADER) ? "geometry" : (shader_type == GL_COMPUTE_SHADER) ? "compute" : (shader_type == GL_TESS_CONTROL_SHADER) ? "tess-control" : (shader_type == GL_TESS_EVALUATION_SHADER) ? "tess-evaluation" : "unknown" ); GLuint id = glCreateShader(shader_type); glShaderSource(id, 1, &source , nullptr); glCompileShader(id); GLint status, log_len; glGetShaderiv(id, GL_COMPILE_STATUS, &status); glGetShaderiv(id, GL_INFO_LOG_LENGTH, &log_len); if (log_len > 1) { GLchar *log_msg = new GLchar[log_len]; glGetShaderInfoLog(id, log_len, nullptr, log_msg); if (status == GL_TRUE) note("Compiled successfully\n%s", log_msg); else error("The compilation has failed\n%s", log_msg); delete [] log_msg; } if (status != GL_TRUE) return EXIT_FAILURE; _shaders.push_back(id); return EXIT_SUCCESS; } int Shader_program::link_shaders() { note("%s", "Link shaders..."); GLuint id = glCreateProgram(); if (!id) { error("%s", "Impossible to create a new program"); return EXIT_FAILURE; } for (std::vector<GLuint>::iterator it = _shaders.begin() ; it != _shaders.end() ; ++it) glAttachShader(id, *it); bind_attrib("vertex_position", SHADER_ATTRIB_POSITION); bind_attrib("vertex_color", SHADER_ATTRIB_COLOR); bind_attrib("vertex_texture", SHADER_ATTRIB_TEXTURE); bind_attrib("vertex_normal", SHADER_ATTRIB_NORMAL); glLinkProgram(id); GLint status, log_len; glGetProgramiv(id, GL_LINK_STATUS, &status); glGetProgramiv(id, GL_INFO_LOG_LENGTH, &log_len); if (log_len > 1) { GLchar *log_msg = new GLchar[log_len]; glGetShaderInfoLog(id, log_len, nullptr, log_msg); if (status == GL_TRUE) note("Linked successfully\n%s", log_msg); else error("The linkage has failed\n%s", log_msg); delete [] log_msg; } if (status == GL_FALSE) return EXIT_FAILURE; for (std::vector<GLuint>::iterator it = _shaders.begin() ; it != _shaders.end() ; ++it) { glDetachShader(id, *it); glDeleteShader(*it); } _shaders.clear(); glDeleteProgram(_program_id); _program_id = id; bind_uniform_block("block_camera", SHADER_UNIFORM_BLOCK_CAMERA); bind_uniform_block("block_mesh", SHADER_UNIFORM_BLOCK_MESH); bind_uniform_block("block_precomputed", SHADER_UNIFORM_BLOCK_PRECOMPUTED); bind_uniform_block("block_light", SHADER_UNIFORM_BLOCK_LIGHT); bind_uniform_block("block_material", SHADER_UNIFORM_BLOCK_MATERIAL); print_summary(); return EXIT_SUCCESS; } void Shader_program::use() const { glUseProgram(_program_id); } void Shader_program::print_summary() const { note("Summary of the shader program #%u", _program_id); GLint answer; glGetProgramiv(_program_id, GL_PROGRAM_BINARY_LENGTH, &answer); note("Size : %i bytes", answer); glGetProgramiv(_program_id, GL_DELETE_STATUS, &answer); note("Flagged for deletion : %s", (answer == GL_TRUE) ? "yes" : "no"); glGetProgramiv(_program_id, GL_LINK_STATUS, &answer); note("Link status : %s", (answer == GL_TRUE) ? "success" : "failed"); glGetProgramiv(_program_id, GL_VALIDATE_STATUS, &answer); note("Validate status : %s", (answer == GL_TRUE) ? "success" : "failed"); glGetProgramiv(_program_id, GL_ACTIVE_ATOMIC_COUNTER_BUFFERS, &answer); note("%i buffer used", answer); glGetProgramiv(_program_id, GL_ATTACHED_SHADERS, &answer); note("%i shaders attached :", answer); { GLuint *shaders = new GLuint[answer]; glGetAttachedShaders(_program_id, answer, nullptr, shaders); for (uint32_t index = 0 ; index < (uint32_t)answer ; ++index) note(" name:%u", shaders[index]); delete [] shaders; } glGetProgramiv(_program_id, GL_ACTIVE_ATTRIBUTES, &answer); note("%i attributes :", answer); for (uint32_t index = 0 ; index < (uint32_t)answer ; ++index) { const uint32_t bufSize = 32; int32_t size; GLenum type; char name[bufSize]; glGetActiveAttrib(_program_id, index, bufSize, nullptr, &size, &type, name); note(" type:%u size:%i name:%s", type, size, name); } glGetProgramiv(_program_id, GL_ACTIVE_UNIFORMS, &answer); note("%i uniforms :", answer); for (uint32_t index = 0 ; index < (uint32_t)answer ; ++index) { const uint32_t bufSize = 32; int32_t size; GLenum type; char name[bufSize]; glGetActiveUniform(_program_id, index, bufSize, nullptr, &size, &type, name); note(" type:%u size:%i name:%s", type, size, name); } glGetProgramiv(_program_id, GL_GEOMETRY_VERTICES_OUT, &answer); note("Geometry shader generates %u vert%s", (uint32_t)answer, (answer <= 1) ? "ex" : "ices"); glGetProgramiv(_program_id, GL_GEOMETRY_INPUT_TYPE, &answer); note("Geometry shader takes type %u as input", (uint32_t)answer); glGetProgramiv(_program_id, GL_GEOMETRY_OUTPUT_TYPE, &answer); note("Geometry shader create type %u as output", (uint32_t)answer); glGetProgramiv(_program_id, GL_INFO_LOG_LENGTH, &answer); if (answer > 1) { GLchar *log_msg = new GLchar[answer]; glGetShaderInfoLog(_program_id, answer, nullptr, log_msg); note("Info log : \n%s", log_msg); delete [] log_msg; } } inline void Shader_program::bind_attrib(const char *name, enum Attribute attrib) { glBindAttribLocation(_program_id, attrib, name); } inline void Shader_program::bind_uniform_block(const char *name, enum Uniform_block block) { GLuint index = glGetUniformBlockIndex(_program_id, name); if (index == GL_INVALID_INDEX) warning("Impossible to get the index of '%s'", name); else glUniformBlockBinding(_program_id, index, block); }
true
de89dc63cd9900649863db97c7e723b0ce610d76
C++
ZdravkoD/Algo-1
/week9/2-Light-Switches/Light-Switches.cpp
UTF-8
2,301
3.5
4
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; #define N 16 struct Switch{ bool TogglesBulb[N]; }; Switch Switches[N]; bool Bulbs[N]; vector<int> Solution; /** Reads the input **/ void read() { string State; for(int i=0;i<N;i++) { cin >> State; Bulbs[i] = (State=="on" ? true : false); } for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { cin >> Switches[i].TogglesBulb[j]; } } } /** Returns true if any bulb is on **/ bool bulbsOn() { for(int i=0;i<N;i++) { if(Bulbs[i]) return true; } return false; } /** Inverses the state of the bulbs to which the 'cur' switch is connected to **/ void toggleBulbs(const Switch &cur) { for(int i=0;i<N;i++) { if(cur.TogglesBulb[i]) { Bulbs[i]=!Bulbs[i]; } } } /** Checks combination without repetitions with given parameters: * k - number of switches to include in the combination. * curElement - Position of the current switch(count of switches until now). * startFrom - From which switch to count combinations **/ bool checkCombination(const int &k, const int curElement, const int startFrom) { for(int i=startFrom;i<N;i++) { toggleBulbs(Switches[i]); if(curElement == k) { if(bulbsOn()) { toggleBulbs(Switches[i]); // return to previous state } else { Solution.push_back(i+1); return true; } } else { if(checkCombination(k,curElement+1,i+1)) { Solution.push_back(i+1); return true; } else { toggleBulbs(Switches[i]); // return to previous state } } } return false; } /** Solves the problem. * Checks combinations with 1,2,3,...,N switches. **/ void solve() { for(int i=1;i<=N;i++) { if(checkCombination(i,1,0)) { return; } } } /** Prints the solution of the problem. * If there is no solution it prints "IMPOSSIBLE!". * Otherwise it prints the switches in sorted order **/ void printSolution() { if(Solution.size()==0) { cout << "IMPOSSIBLE!" << endl; return; } sort(Solution.begin(),Solution.end()); for(unsigned int i=0;i<Solution.size();i++) { cout << Solution[i] << " "; } cout << endl; } int main() { read(); solve(); printSolution(); return 0; }
true
1e80d765696ddcc1abea5007ece553dd847ff901
C++
ahmadtc1/Basic-Calculator
/getMathematicalOperation.cpp
UTF-8
604
3.046875
3
[]
no_license
// // getMathematicalOperation.cpp // Calculator // // Created by Ahmad Chaudhry on 2018-07-09. // Copyright © 2018 Ahmad Chaudhry. All rights reserved. // #include <iostream> #include "calculator.hpp" int getMathematicalOperation(){ std::cout<< "For addition please type '1'"<<std::endl; std::cout<< "For subtraction please type '2'"<<std::endl; std::cout<< "For multiplication please type '3'"<<std::endl; std::cout<< "For division please type '4'"<<std::endl; std::cout<< "For squareroot please type '5'"<<std::endl; int operation; std::cin>> operation; return operation; }
true
5ebad023b76a26656cb0e8a6708f8bf2433543c5
C++
jonwa/Nukes-of-the-Patriots
/Nukes of the patriots/President.cpp
UTF-8
3,741
2.53125
3
[]
no_license
#include "president.h" #include "ResourceHandler.h" #include <iostream> President::President(std::string &filename) { initializeImages(filename); randomStatFunc(); } President::~President() { } void President::randomStatFunc() { Randomizer *randomizer; randomizer = Randomizer::getInstance(); randomStats.push_back("foodPrice"); randomStats.push_back("goodsPrice"); randomStats.push_back("techPrice"); randomStats.push_back("nuclearPrice"); randomStats.push_back("spacePrice"); randomStats.push_back("spyPrice"); randomStats.push_back("patriotismTax"); std::map<std::string, float> posStatMap; posStatMap.insert(std::pair<std::string,float>("foodPrice", -2.f)); posStatMap.insert(std::pair<std::string,float>("goodsPrice", -2.f)); posStatMap.insert(std::pair<std::string,float>("techPrice", -2.f)); posStatMap.insert(std::pair<std::string,float>("nuclearPrice", 0.8f)); posStatMap.insert(std::pair<std::string,float>("spacePrice",0.8f)); posStatMap.insert(std::pair<std::string,float>("spyPrice", 0.8f)); posStatMap.insert(std::pair<std::string,float>("patriotismTax", 1.f)); std::map<std::string, float> negStatMap; negStatMap.insert(std::pair<std::string,float>("foodPrice", 2.f)); negStatMap.insert(std::pair<std::string,float>("goodsPrice", 2.f)); negStatMap.insert(std::pair<std::string,float>("techPrice", 2.f)); negStatMap.insert(std::pair<std::string,float>("nuclearPrice", 1.2f)); negStatMap.insert(std::pair<std::string,float>("spacePrice", 1.2f)); negStatMap.insert(std::pair<std::string,float>("spyPrice", 1.2f)); negStatMap.insert(std::pair<std::string,float>("popEatsMore", 0.1f)); int random = ( randomizer->randomNr(randomStats.size(),0) ); mValues.insert(std::pair<std::string,float>(randomStats[random], posStatMap.find(randomStats[random])->second)); randomStats[random] = randomStats.back(); randomStats.pop_back(); random = ( randomizer->randomNr(randomStats.size(),0) ); mValues.insert(std::pair<std::string,float>(randomStats[random], posStatMap.find(randomStats[random])->second)); randomStats[random] = randomStats.back(); randomStats.pop_back(); randomStats.push_back("popEatsMore"); random = ( randomizer->randomNr(randomStats.size(),0) ); if(randomStats[random] == "patriotismTax") { randomStats[random] = randomStats.back(); randomStats.pop_back(); random = ( randomizer->randomNr(randomStats.size(),0) ); } mValues.insert(std::pair<std::string,float>(randomStats[random], negStatMap.find(randomStats[random])->second)); randomStats[random] = randomStats.back(); randomStats.pop_back(); for(std::vector<std::string>::iterator it = randomStats.begin(); it != randomStats.end(); it++) { mValues.insert(std::pair<std::string, float>((*it), 0.f)); } randomStats.clear(); } float President::getFoodPriceModifier() { return mValues["foodPrice"]; } float President::getGoodsPriceModifier() { return mValues["goodsPrice"]; } float President::getTechPriceModifier() { return mValues["techPrice"]; } float President::getNuclearPriceModifier() { return mValues["nuclearPrice"] == 0 ? 1 : mValues["nuclearPrice"]; } float President::getSpacePriceModifier() { return mValues["spacePrice"] == 0 ? 1 : mValues["spacePrice"]; } float President::getSpyPriceModifier() { return mValues["spyPrice"] == 0 ? 1 : mValues["spyPrice"]; } float President::getPatriotismTaxModifier() { return mValues["patriotismTax"]; } float President::getPopEatsMore() { return mValues["popEatsMore"]; } void President::initializeImages(std::string &path) { ResourceHandler* handler = ResourceHandler::getInstance(); mTexture = &handler->getTexture(path); mPortrait.setTexture(*mTexture); } sf::Texture* President::getTexture() { return mTexture; }
true
d086bb516afb3daa8dc1770f7fa16726e39b1295
C++
wlpwz/spiderPro
/dsotest/main.cpp
UTF-8
851
2.578125
3
[]
no_license
#include <iostream> #include "dso.h" using namespace std; int main() { int argc = 4; DsoManager *dso_manager = new DsoManager(); if(dso_manager->load("./","libtestmod")) cout << "load success !"<<endl; Module* module = dso_manager->getModule("libtestmod"); if(dso_manager->load("./","libtestmod1")) cout << "load success 1!"<<endl; Module* module1 = dso_manager->getModule("libtestmod1"); if(module1 != NULL) module1->handle((void *)argc); if(module != NULL) module->handle((void *)argc); int count = 0; map<string, Module*>::iterator itor ; for(itor = dso_manager->m_modules.begin();itor != dso_manager->m_modules.end();itor++) { count++; cout << count <<endl; cout <<(Module*)itor->second->name << endl; } return 0; }
true
bf2a71ca4274aaf7f126264e063a549139c9b9ee
C++
hzhang22/hack
/leetcode/Reverse_Nodes_KGroup.cpp
UTF-8
1,168
3.375
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseK(ListNode *head, int k){ if (head == NULL) return NULL; //if (k == 1) return head; ListNode *prev =NULL; ListNode *cur =head; ListNode *next =NULL; while (k > 0){ next = cur->next; cur->next = prev; prev = cur; cur = next; k--; } return prev; } ListNode *reverseKGroup(ListNode *head, int k) { // Start typing your C/C++ solution below // DO NOT write int main() function if (k <= 0 || head == NULL) return head; ListNode* runner = head; for(int i = 0; i < k; i++){ runner = runner->next; if (runner == NULL && i < k - 1) return head; } head = reverseK(head, k); ListNode* newP = head; for (int i = 1; i < k; i++){ newP = newP->next; } newP->next = reverseKGroup(runner, k); return head; } };
true
0d7eb9a88fa75ef11db4f440eb35e3bdee5eebb2
C++
heliy/oj
/bailian/2121.cpp
UTF-8
1,935
2.671875
3
[]
no_license
#include<cstdio> #include<iostream> #include<cstring> #include<cmath> using namespace std; /*WA*/ char names[200][20]; char line[4000]; int ds[3]; char onedits[10][20] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; char twodits1[9][20] = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", }; char twodits2[10][20] = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred", }; int find(char *a, char array[][20], int n){ int i; for(i = 0; i < n; i++){ if(strcmp(a, array[i]) == 0){ return i; } } return -1; } int main(){ while(fgets(line, 4000, stdin) != NULL){ if(line[0] == ' '){ break; } ds[0] = ds[1] = ds[2] = 0; int i, j, n; for(n = j = i = 0; true; i++, j++){ if(line[i] == ' ' || line[i] == '\n' || line[i] == '\0'){ names[n][j] = '\0'; j = -1; n++; if(line[i] != ' '){ break; } }else{ names[n][j] = line[i]; } } long long num = 0, flag = 0, temp = 0, t; for(i = 0; i < n; i++){ if(strcmp(names[i], "negative") == 0){ flag = 1; }else if((t = find(names[i], twodits1, 9)) && t > 0){ temp += (11+t); }else if((t = find(names[i], twodits2, 10)) && t > 0){ if(t == 9){ temp *= 100; }else{ temp += (10*t+10); } }else if((t = find(names[i], onedits, 10)) && t > 0){ temp += (t); }else{ if(strcmp(names[i], "thousand") == 0){ ds[1] = temp; }else{ ds[0] = temp; } temp = 0; } // cout << ds[0]<<","<<ds[1]<<","<<ds[2] << ":" << temp << endl; } ds[2] = temp; if(flag){ cout << "-"; } for(i = 0; i < 3; i++){ if(ds[i] != 0){ break; } } if(i == 3){ cout << 0; }else{ cout << ds[i]; for(i++; i < 3; i++){ printf("%03d", ds[i]); } } cout << endl; } }
true
cdd7f13a2c96d165349b00eee79898e61b49f24b
C++
giulianoxt/qassault
/minimax.cpp
UTF-8
7,323
2.953125
3
[]
no_license
#include "minimax.h" #include <QList> #include <string> #include <cassert> MinimaxAI::MinimaxAI(PlayerType p, int depth) : isMax(p == Attack), lookahead(depth), player(p), cache(cacheSize) { } Move MinimaxAI::searchTree(const GameState& st) { numNodes = 0; int movInd = -1; const QList<Move> moves = st.moves(player); if (moves.size() == 1) { movInd = 0; numNodes = 1; } else if (oneMoveWin(st, moves, movInd)) { numNodes = movInd + 1; } else { double eval = minimax( st, isMax, lookahead, movInd, GameState::evalMin, GameState::evalMax ); if (eval == GameState::evalMin) cout << "Defense is going to win!" << endl; else if (eval == GameState::evalMax) cout << "Attack is going to win!" << endl; } //cout << numNodes << " nodes" << endl; return moves.at(movInd); } bool MinimaxAI::oneMoveWin(const GameState& st, const QList<Move>& moves, int& movInd) { if (!st.almostOver()) return false; movInd = 0; GameState next; foreach (const Move& m, moves) { st.copyAndMove(m, next); if (next.gameOver()) return true; ++movInd; } return false; } double MinimaxAI::minimax(const GameState& st, bool max, int depth, int& movInd, double alpha, double beta) { ++numNodes; if (!depth || st.gameOver()) { return st.eval(); } double nodeEval; ResultType type = Exact; movInd = 0; int i = 0, d; GameState child; QList<Move>::const_iterator it; const QList<Move> moves = st.moves(max ? Attack : Defense); if (max) { for (it = moves.begin(); it != moves.end(); ++it, ++i) { st.copyAndMove(*it, child); double eval = minimax(child, false, depth-1, d, alpha, beta); if (eval > alpha) { alpha = eval; movInd = i; } if (alpha >= beta) { type = LowerBound; break; } } nodeEval = alpha; } else { for (it = moves.begin(); it != moves.end(); ++it, ++i) { st.copyAndMove(*it, child); double eval = minimax(child, true, depth-1, d, alpha, beta); if (eval < beta) { beta = eval; movInd = i; } if (alpha >= beta) { type = UpperBound; break; } } nodeEval = beta; } return nodeEval; } Move MinimaxAI::searchTreeCache(const GameState& st) { hitNodes = 0; numNodes = 0; int movInd = -1; const QList<Move> moves = st.moves(player); if (moves.size() == 1) { movInd = 0; numNodes = 1; } else if (oneMoveWin(st, moves, movInd)) { numNodes = movInd + 1; } else { double eval = minimaxCache( st, isMax, lookahead, movInd, GameState::evalMin-100, GameState::evalMax+100 ); if (eval == GameState::evalMin) cout << "Defense is going to win!" << endl; else if (eval == GameState::evalMax) cout << "Attack is going to win!" << endl; } cout << numNodes << " nodes" << endl; cout << "hit = " << hitNodes / double(numNodes) << endl; cout << "cacheSize = " << cache.size() << endl; return moves.at(movInd); } double MinimaxAI::minimaxCache(const GameState& st, bool max, int depth, int& movInd, double alpha, double beta) { ++numNodes; SearchResult* result = cache.object(st); bool validCache = result && (result->depth == depth); /*if (validCache && result->type == Exact) { ++hitNodes; movInd = result->movInd; return result->eval; }*/ if (!depth || st.gameOver()) { return st.eval(); } double nodeEval; ResultType nodeType = Exact; movInd = 0; int i = 0, d; GameState child; QList<Move>::const_iterator it; const QList<Move> moves = st.moves(max ? Attack : Defense); if (max) { /*if (validCache && result->type == LowerBound && result->eval >= beta) { movInd = result->movInd; return result->eval; }*/ for (it = moves.begin(); it != moves.end(); ++it, ++i) { st.copyAndMove(*it, child); double eval = minimaxCache(child, false, depth-1, d, alpha, beta); if (eval > alpha) { alpha = eval; movInd = i; } if (alpha >= beta) { nodeType = LowerBound; movInd = i; break; } } nodeEval = alpha; } else { /*if (validCache && result->type == UpperBound && result->eval <= alpha) { movInd = result->movInd; return result->eval; }*/ for (it = moves.begin(); it != moves.end(); ++it, ++i) { st.copyAndMove(*it, child); double eval = minimaxCache(child, true, depth-1, d, alpha, beta); if (eval < beta) { beta = eval; movInd = i; } if (alpha >= beta) { nodeType = UpperBound; movInd = i; break; } } nodeEval = beta; } if (nodeType == Exact && depth >= cacheDepth) { SearchResult* result = cache.object(st); if (!result || depth > result->depth || nodeType == Exact && result->type != Exact) { SearchResult* res(new SearchResult( depth, movInd, nodeEval, nodeType )); res->st.copy(st); res->alpha = alpha; res->beta = beta; cache.insert(st, res); } } if (validCache && result->type == Exact && nodeType == Exact && nodeEval != result->eval) { if (alpha == result->alpha && beta == result->beta) cout << "#### opa ####" << endl; } return nodeEval; } SearchResult::SearchResult() { } SearchResult::SearchResult(int _d, int _i, double _e, ResultType _t) : depth(_d), movInd(_i), eval(_e), type(_t) { } uint qHash(const GameState& st) { return st.hash(); }
true
906d0564693b0e211b4a4f25fea0d4957a6bf77f
C++
skyjhyp11/HistgramStretech
/opencvT3_histg/histogram1d.cpp
UTF-8
3,035
2.671875
3
[]
no_license
#include "histogram1d.h" #include <QTextStream> cv::MatND Histogram1D::getHistogram(const cv::Mat &image)//获取直方图数据 { cv::MatND hist; //重载2(src,单张图像,通道数量,不使用掩码,返回到hist,1D直方图,项数,像素范围) cv::calcHist(&image,1,channels,cv::Mat(),hist,1,histSize,ranges); return hist; } cv::Mat Histogram1D::getHistogramImage(const cv::Mat &image)//画出直方图 { cv::MatND hist=getHistogram(image);//得到直方图数组 double maxVal=0; double minVal=0; cv::minMaxLoc(hist,&minVal,&maxVal);//获取最大最小值 double scaX=2;//缩放倍数rows double scaY=1;//cols double rows[1],cols[1]; rows[0]=scaY*histSize[0]; cols[0]=scaX*histSize[0]; cv::Mat histImg (rows[0],cols[0],CV_8U,cv::Scalar(255));//设置要显示的直方图//(行,列..) //int hpt=static_cast<int>(0.9*histSize[0]); for(int h=0;h<histSize[0];h++) { float binVal=hist.at<float>(h); int intensity=static_cast<int>(binVal*rows[0]/maxVal); cv::line(histImg,cv::Point(scaX*h,rows[0]),cv::Point(scaX*h,rows[0]-intensity),cv::Scalar(0)); } return histImg; } cv::Mat Histogram1D::applyLookUP(const cv::Mat &image,const cv::Mat &lookup) { cv::Mat result; cv::LUT(image,lookup,result);//(src,查找换算表,result) return result; } cv::Mat Histogram1D::stretch(const cv::Mat &image,int minValue=0) { //QTextStream cin( stdin, QIODevice::ReadOnly); QTextStream cout( stdout, QIODevice::WriteOnly); //QTextStream cerr(stderr, QIODevice::WriteOnly); cv::MatND hist=getHistogram(image); int imin=0; for(;imin<histSize[0];imin++) { cout<<imin<<"="<<hist.at<float>(imin)<<endl; if(hist.at<float>(imin)>minValue) { //minValue 像素的最小个数如100,此处从灰度为imin=0的像素开始检索 //得到像素个数大于100的第一个灰度值索引:imin break; } } int imax=histSize[0]-1; for(;imax>=0;imax--) { cout<<imax<<"="<<hist.at<float>(imax)<<endl; if (hist.at<float>(imax)>minValue) { //minValue 像素的最小个数如100,此处从灰度为imin=255的像素开始检索 //得到像素个数大于100的第一个灰度值索引:imax break; } } //创建查找换算表 int dim(256);//初始换dim=256; cv::Mat lookup(1,&dim,CV_8U);//(1维dimension,256条目entries,uchar) for(int i=0;i<256;i++) { if(i<imin) //两头灰度值对应数量变成0,中间灰度值线性映射 lookup.at<uchar>(i)=0; else if(i>imax) lookup.at<uchar>(i)=0; else lookup.at<uchar>(i)=static_cast<uchar>(255.0*(i-imin)/(imax-imin)+0.5); } cv::Mat result; result=applyLookUP(image,lookup); return result; }
true
a1f94d5c18f1ef319b8a6c491bbd3734123a2b74
C++
kihira/FoxerEngine
/src/render/Light.h
UTF-8
570
3
3
[ "MIT", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
#pragma once #include <glm/vec3.hpp> class Shader; /** * A simple directional light */ class Light { private: glm::vec3 position; glm::vec3 direction; float intensity; public: Light(const glm::vec3& position, const glm::vec3& direction); /** * Applies the light properties to the shader */ void apply(Shader *shader); glm::vec3 getPosition() const; void setPosition(const glm::vec3& position); glm::vec3 getDirection() const; void setDirection(const glm::vec3& direction); float getIntensity() const; void setIntensity(float intensity); };
true
75cb506fcdee9a0df4597449ef4f2f34d0210955
C++
novikov-ilia-softdev/thinking_cpp
/tom_1/chapter_13/14/main.cpp
UTF-8
662
2.96875
3
[]
no_license
#include <iostream> #include <new> #include <vector> #include <boost/lexical_cast.hpp> class MyClass{ public: void* operator new( size_t, const std::string& str) { vector_.push_back( str); return ::new MyClass; } static void printArgs() { for( int i = 0; i < vector_.size(); i++) { std::cout << vector_[ i] << std::endl; } } private: typedef std::vector<std::string> StringVector; static StringVector vector_; }; MyClass::StringVector MyClass::vector_; int main() { new( __FILE__) MyClass; new( boost::lexical_cast<std::string>( __LINE__)) MyClass; new( boost::lexical_cast<std::string>( __LINE__)) MyClass; MyClass::printArgs(); }
true
0b35dc216cb58b3bea7fb6758e5b5f53c57019e1
C++
yangSQI/SocketClass
/SocketServer/NetEventServer.hpp
GB18030
3,394
2.515625
3
[]
no_license
#ifndef __NETEVENTSERVER_H__ #define __NETEVENTSERVER_H__ #include "../SocketClass/NetEvent.hpp" #include "../SocketClass/DataGather.hpp" namespace yang { class NetEventServer : public NetEvent { public: /** * @description : Ϣ * @param : _sockInfo: sockϢṹ */ void OnNetRecv(SocketInfo* _sockInfo) { char* startPos = _sockInfo->_recvStart; char* lastPos = _sockInfo->_recvLast; char* buff = startPos; DataHeader* lpDataHeader = NULL; // ճٰ int len = 0; while ((len = lastPos - startPos) > sizeof(DataHeader)) { lpDataHeader = (DataHeader*)startPos; if (len > lpDataHeader->len) { //printf("SOCKET: %d\t", sockInfo->_sock); switch (lpDataHeader->dataType) { case DataType::LOGIN: { Login* lpLogin = (Login*)startPos; printf("û: %s, : %s, ݳ: %d\n", lpLogin->username, lpLogin->password, lpLogin->dataHeader.len); if (_sockInfo->_sendLen - (_sockInfo->_sendLast - _sockInfo->_sendStart) >= sizeof(LoginReply)) { // ظϢ LoginReply loginReply; snprintf(loginReply.reply, 100, "յϢ, û: %s, : %s", lpLogin->username, lpLogin->password); memmove(_sockInfo->_sendLast, (char*)&loginReply, sizeof(LoginReply)); _sockInfo->_sendLast += sizeof(LoginReply); // ͻβλ } startPos += lpLogin->dataHeader.len; break; } case DataType::LOGOUT: { Logout* lpLogout = (Logout*)startPos; printf("ûid: %u, ݳ: %d\n", lpLogout->uid, lpLogout->dataHeader.len); if (_sockInfo->_sendLen - (_sockInfo->_sendLast - _sockInfo->_sendStart) >= sizeof(LogoutReply)) { // ظϢ LoginReply logoutReply; snprintf(logoutReply.reply, 100, "յϢ, ûid: %d", lpLogout->uid); memmove(_sockInfo->_sendLast, (char*)&logoutReply, sizeof(LogoutReply)); _sockInfo->_sendLast += sizeof(LoginReply); // ͻβλ } startPos += lpLogout->dataHeader.len; break; } } } else { break; } } if (buff != startPos) { //printf("ʣ೤%d\n", len); memcpy(buff, startPos, len); } // ʣλ _sockInfo->_recvLast = buff + len; // sockͻӽϢмб SocketHandle::send_push_back(_sockInfo); } /** * @description : ͻ뿪Ϣ * @param : _sockInfo: sockϢṹ */ void OnNetLeave(SocketInfo* _sockInfo) { --_sockNum; #ifdef _WIN32 char buff[20]; snprintf(buff, 20, "SockNum: %d", _sockNum); SetConsoleTitleA(buff); #endif //printf("socket<%d> leval, port: %d, ip: %s\n", _sockInfo->_sock, ntohs(_sockInfo->_sockaddr.sin_port), inet_ntoa(_sockInfo->_sockaddr.sin_addr)); } /** * @description : ͻ˵Ϣ * @param : _sockInfo: sockϢṹ */ void OnNetAccept(SocketInfo* _sockInfo) { ++_sockNum; #ifdef _WIN32 char buff[20]; snprintf(buff, 20, "SockNum: %d", _sockNum); SetConsoleTitleA(buff); #endif //printf("ͻSOCKET: %d, ˿: %d, ip: %s\n", _sockInfo->_sock, ntohs(_sockInfo->_sockaddr.sin_port), inet_ntoa(_sockInfo->_sockaddr.sin_addr)); } }; }; #endif
true
a6d58596287eeb697ec5b3ae78aef44e9bb01086
C++
screamatthewind/multicast
/mctest3/mctest3/src/CsvWriter.cpp
UTF-8
2,548
3.015625
3
[]
no_license
// CsvWriter.cpp // Implementation of a multithread safe singleton logger class #include "CsvWriter.h" #include "unistd.h" #include "string.h" using namespace std; CsvWriter* CsvWriter::pInstance = nullptr; mutex CsvWriter::sMutex; CsvWriter& CsvWriter::instance(string& csvHeader) { static Cleanup cleanup; lock_guard<mutex> guard(sMutex); if (pInstance == nullptr) pInstance = new CsvWriter(csvHeader); return *pInstance; } CsvWriter::Cleanup::~Cleanup() { lock_guard<mutex> guard(CsvWriter::sMutex); delete CsvWriter::pInstance; CsvWriter::pInstance = nullptr; } CsvWriter::~CsvWriter() { mOutputStream.close(); } CsvWriter::CsvWriter(string& csvHeader) : m_csvHeader(csvHeader) { OpenStream(); } void CsvWriter::OpenStream() { time_t now; char hostname[255]; filename[0] = '\0'; now = time(NULL); // strftime(filename_timestamp, 255, "%m%d%Y_%H%M", localtime(&now)); strftime(filename_timestamp, 255, "%m%d%Y", localtime(&now)); gethostname(hostname, 255); if (strcmp(hostname, "(none)") == 0) sprintf(filename, "/tmp/mctest3-%s.csv", filename_timestamp); else sprintf(filename, "/tmp/%s-mctest3-%s.csv", hostname, filename_timestamp); string logFilename = string(filename); ifstream f(logFilename); mOutputStream.open(logFilename, ios_base::app); if (!mOutputStream.good()) { throw runtime_error("Unable to initialize the CsvWriter!"); } if (!f.good()) writeHelper(m_csvHeader, false); } char *CsvWriter::getFileTimestamp() { return (char *) &filename_timestamp; } void CsvWriter::write(const string& inMessage) { lock_guard<mutex> guard(sMutex); writeHelper(inMessage, true); } void CsvWriter::write(const vector<string>& inMessages) { lock_guard<mutex> guard(sMutex); for (size_t i = 0; i < inMessages.size(); i++) { writeHelper(inMessages[i], true); } } void CsvWriter::writeHelper(const std::string& inMessage, bool writeTimestamp) { if (access(filename, F_OK) == -1) { mOutputStream.close(); OpenStream(); } time_t now; char cur_timestamp[32]; cur_timestamp[0] = '\0'; now = time(NULL); // reopen file with new name when date changes // strftime(cur_timestamp, 255, "%m%d%Y_%H%M", localtime(&now)); strftime(cur_timestamp, 255, "%m%d%Y", localtime(&now)); if (strcmp(filename_timestamp, cur_timestamp) != 0) { mOutputStream.close(); OpenStream(); } if (writeTimestamp) { strftime(cur_timestamp, 32, "%F %H:%M:%S", gmtime(&now)); mOutputStream << cur_timestamp << ", " << inMessage << endl; } else mOutputStream << inMessage << endl; }
true
b64c27b954c6feb540e7d69ce88e3aad06b3e59c
C++
egolearner/documents
/ARTS/Algorithm/leetcode/103_binary-tree-zigzag-level-order-traversal/solution.cpp
UTF-8
3,450
4.21875
4
[]
no_license
/* Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> result; queue<TreeNode*> queue; if (root) { queue.push(root); } bool rev = false; while (!queue.empty()) { result.push_back({}); auto& cur = result.back(); for (int size = queue.size(); size != 0; size--) { auto n = queue.front(); queue.pop(); cur.push_back(n->val); if (n->left) { queue.push(n->left); } if (n->right) { queue.push(n->right); } } if (rev) { reverse(cur.begin(), cur.end()); } rev = !rev; } return result; } }; /* * 想不出如何更好的处理,偷懒用了reverse * 答案中用两个stack的思路 * 交替先push left和先push right All you have to do is do the standard bfs(with two stacks instead) with two adjustments - 1. instead of dequeueing from a queue, pop() from our first stack pointer. Simmilarly instead of enqueueing push to our second stack pointer. 2. In queue you will push in left child then right child in every level. Here we alternately first push right and left (why? because you want to have level two in reverse order), then in second iteration left and right and so on. class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> v; if(root==NULL) return v; stack<TreeNode*> s1,s2; s1.push(root); vector<int> v1; while(!s1.empty() || !s2.empty()) { if(!s1.empty()) { while(!s1.empty()) { TreeNode* odd = s1.top(); s1.pop(); v1.push_back(odd->val); if(odd->left) s2.push(odd->left); if(odd->right) s2.push(odd->right); } v.push_back(v1); v1.clear(); } if(!s2.empty()) { while(!s2.empty()) { TreeNode* even = s2.top(); s2.pop(); v1.push_back(even->val); if(even->right) s1.push(even->right); if(even->left) s1.push(even->left); } v.push_back(v1); v1.clear(); } } return v; } }; */
true
df718e1e2e15165a9660925ba7b73625008de738
C++
weimingtom/wmt_mingw_study
/sgi/test008.cpp
UTF-8
6,339
3.453125
3
[]
no_license
// 编译命令行: // g++ test008.cpp //《C++程序设计语言(特别版)》 // 19.4.2 一个用户定义分配器 //演示标准库分配器allocator接口的简单实现 #include <cstddef> #include <vector> #include <iostream> #include <iterator> //class Pool定义一个简单接口的小内存块内存池 //这个内存池一次只能分配恒定大小的小内存块(由构造函数参数指定) class Pool { private: //用于分配和释放内存的链表 //比Chunk的粒度小,多个Link分割一个Chunk //分配前Link的next域用于计算下一个分配位置 //分配后Link只是void*内存块的头部 struct Link { Link *next; }; // 底层内存分配区的分区块 // 一个Pool内有多个依次链接的Chunk //每个Chunk被多个Link分割成更小的内存块 //(但所有Link的排列次序不一定依照其所在Chunk块的排列次序), //但因为内存是连续的,所以在增量分配和全体释放时速度会较快 struct Chunk { //让一个Chunk不超过8K且略小于8K enum { SIZE = 8 * 1024 - 16 }; unsigned char mem[SIZE]; Chunk *next; //next应该不会超过16个字节 }; //多个Chunk前后组成一个链表(好像一个栈) Chunk *chunks; //每次alloc()返回的内存块最大大小, //但不能比sizeof(Link)小,也不能比Chunk::SIZE大 const unsigned int esize; //当前空闲Chunk块内的空闲Link头部 Link *head; //禁用默认的复制构造函数和复制赋值, //所以这里不需要定义方法体 private: Pool(Pool& sz); void operator=(Pool&); private: void grow(); public: Pool(unsigned int n);//指定每次alloc()返回的内存块大小 ~Pool(); void* alloc(); //不需要指定内存块大小(在构造函数中指定) void free(void* b); }; //从head链表的头部取出一个Link //如果空闲Chunk块用完,需要分配新的Chunk块, //然后用Link链表分割这个新的空闲Chunk块。 inline void* Pool::alloc() { if (head == 0) { grow(); } Link *p = head; head = p->next; std::cout << "Pool::alloc(): p == " << p << ", head == " << head << std::endl; return p; } //把要释放的b放回head链表的头部 inline void Pool::free(void* b) { Link* p = static_cast<Link*>(b); p->next = head; std::cout << "Pool::free(): p == " << p << ", head == " << head << std::endl; head = p; } Pool::Pool(unsigned int sz) : esize(sz < sizeof(Link) ? sizeof(Link) : sz) { head = 0; chunks = 0; } Pool::~Pool() { Chunk *n = chunks; while (n) { Chunk *p = n; n = n->next; delete p; } } //增量分配内存 //虽然Link*所在的小内存块是连续的, //但alloc的分配次序不一定是连续的 //(因为free()可能放回旧的内存块) void Pool::grow() { Chunk *n = new Chunk(); n->next = chunks; chunks = n; std::cout << "Pool::grow(): esize == " << esize << std::endl; const int nelem = Chunk::SIZE / esize; unsigned char *start = n->mem; unsigned char *last = &start[(nelem - 1) * esize]; for (unsigned char *p = start; p < last; p += esize) { reinterpret_cast<Link*>(p)->next = reinterpret_cast<Link*>(p + esize); } reinterpret_cast<Link*>(last)->next = 0; //见alloc()的if (head == 0) head = reinterpret_cast<Link*>(start); } //template Pool_alloc把class Pool适配到C++标准库的分配器接口 //不完整,因为有些接口没有实现,而有些接口只实现部分功能 template<class T> class Pool_alloc { private: static Pool mem; //全局,以提高效率 public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T *pointer; typedef const T *const_pointer; typedef T &reference; typedef const T&const_reference; Pool_alloc(); T* allocate(size_type n, void*); void deallocate(pointer p, size_type n); }; //构造静态的mem域 //因为Pool只能分配固定大小的小内存块, //而且Pool_alloc没有实现rebind方法 //所以这里指定每次分配的连续内存区都必须是sizeof(T) * 128, //虽然造成浪费,但确保分配的内存是连续的。 //没有超过Chunk块的8K上限,所以是安全的。 template <class T> Pool Pool_alloc<T>::mem(sizeof(T) * 128); template <class T> Pool_alloc<T>::Pool_alloc() { } template<class T> T* Pool_alloc<T>::allocate(size_type n, void* = 0) { if (n <= 128) { void *p = mem.alloc(); std::cout << "allocate : " << n << ", " << p << std::endl; return static_cast<T*>(p); } else { //TODO: std::cout << "allocate : " << n << std::endl; throw "allocate error"; //出错 } } template<class T> void Pool_alloc<T>::deallocate(pointer p, size_type n) { if (n <= 128) { std::cout << "deallocate : " << n << ", " << p << std::endl; mem.free(p); return; } else { //TODO: std::cout << "deallocate : " << n << std::endl; throw "deallocate error"; //出错 } } int main(int argc, const char *argv[]) { { std::vector<int> V1; V1.push_back(1); V1.push_back(2); V1.push_back(3); V1.push_back(4); std::cout << "V1:"<< std::endl; std::copy(V1.begin(), V1.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } { std::cout << "==================="<< std::endl; try { std::vector< int, Pool_alloc<int> > V2; std::cout << "V2.push_back(1);" << std::endl; V2.push_back(1); std::cout << "V2.push_back(2);" << std::endl; V2.push_back(2); std::cout << "V2.push_back(3);" << std::endl; V2.push_back(3); V2.push_back(4); std::cout << "V2:"<< std::endl; std::copy(V2.begin(), V2.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } catch (const char *&str) { std::cout << str << std::endl; } } return 0; } /** 运行结果: $ g++ -g test008.cpp $ ./a.exe V1: 1 2 3 4 =================== V2.push_back(1); Pool::grow(): esize == 512 Pool::alloc(): p == 0x3e4d68, head == 0x3e4f68 allocate : 1, 0x3e4d68 V2.push_back(2); Pool::alloc(): p == 0x3e4f68, head == 0x3e5168 allocate : 2, 0x3e4f68 deallocate : 1, 0x3e4d68 Pool::free(): p == 0x3e4d68, head == 0x3e5168 V2.push_back(3); Pool::alloc(): p == 0x3e4d68, head == 0x3e5168 allocate : 4, 0x3e4d68 deallocate : 2, 0x3e4f68 Pool::free(): p == 0x3e4f68, head == 0x3e5168 V2: 1 2 3 4 deallocate : 4, 0x3e4d68 Pool::free(): p == 0x3e4d68, head == 0x3e4f68 */
true
34f36b2449aeac6cb7fa611f1c46f38c342758b6
C++
cmglass123/CS202
/HW2c/Main.cpp
UTF-8
274
3.171875
3
[]
no_license
/* Christopher Glass CS202x HW2c */ #include<iostream> using std::cout; void lowerCase(char *x) { for (int i = 0; x[i] != 0; i++) { if (x[i] <= 'Z' && x[i] >= 'A') { x[i] += ('a'-'A'); } } } int main() { char word[] = "HELLO WORLD!"; lowerCase(word); cout << word; }
true
6b78c04938145e5f9570f2eb1b4f882e3d700159
C++
P-H-Pancholi/Cplusplus-Practice-Programs
/projectEuler/FactDigitSum.cpp
UTF-8
705
3.453125
3
[]
no_license
#include <iostream> using namespace std; void factDigitSum(int a){ int digits[1000]; int index = 1000; digits[index] = 1; int carry = 0; for(int i = 1;i <= a;i++){ for(int j = 1000; j >= index;j--){ digits[j] = digits[j] * i; digits[j] += carry; carry = 0; if(digits[j] > 9){ carry = digits[j] / 10; digits[j] %= 10; } } while(carry != 0){ int div = carry / 10; int mod = carry % 10; index -= 1; digits[index] = mod; carry = div; } } int sum = 0; for(int i = index; i <= 1000;i++){ cout << digits[i]; sum += digits[i]; } cout << endl; cout << "The sum is " << sum << endl; } int main(){ int n; cin >> n; factDigitSum(n); return 0; }
true
6e39d5e90b70bdd9ec04dcfbf4183642c78dd751
C++
afshanayubi/Basic-coding
/recur_parenthesis.cpp
UTF-8
264
3.203125
3
[]
no_license
#include <iostream> using namespace std; void parenthesis(char* str,int i){ if (str[i]!='(') { return; } if (str[i]=='(') { cout<<str[i+1]; } return parenthesis(str,i+1); } int main(){ char str[100]; cin>>str; parenthesis(str,0); return 0; }
true
00ef1240b26147d4214a3ab24d22eeee30ed267d
C++
Morainy/MyCode
/searchTree.cpp
GB18030
2,481
3.359375
3
[]
no_license
// searchTree.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <stack> using namespace std; typedef struct Node { int key; struct Node * left; struct Node * right; struct Node * parent; } Node ,* pNode; void treeInsert(pNode & root , int key) { pNode newNode =(pNode)malloc(sizeof(Node)); newNode->key = key; newNode->left = NULL; newNode->right = NULL; newNode->parent = NULL; pNode tmpY = NULL; pNode tmpX = root; while(tmpX != NULL) { tmpY = tmpX; if(tmpX->key < key) tmpX = tmpX->right; else tmpX = tmpX->left; } newNode->parent = tmpY; if (tmpY == NULL) root = newNode; else { if(tmpY->key > key) tmpY->left = newNode; else tmpY->right = newNode; } } //void inOrderTree(pNode root) //{ // if(root != NULL) // { // inOrderTree(root->left); // //cout<<root->key<<" "; // printf("%d " , root->key); // inOrderTree(root->right); // } //} pNode treeMinimum(pNode tmpX) { while(tmpX->left != NULL) tmpX = tmpX->left; return tmpX; } pNode treeSuccessor(pNode tmpX) { if(tmpX->right != NULL) return treeMinimum(tmpX->right); pNode tmpY = tmpX->parent; while(tmpY != NULL && tmpX == tmpY->right) { tmpX = tmpY; tmpY = tmpX->parent; } return tmpY; } void treeDelete(pNode & root , pNode & tmpZ) { pNode tmpY , tmpX; if(!tmpZ->left || !tmpZ->right) tmpY = tmpZ; else tmpY = treeSuccessor(tmpZ); if(tmpY->left != NULL) tmpX = tmpY->left; else tmpX = tmpY->right; if(tmpX != NULL) tmpX->parent = tmpY->parent; if(tmpY->parent == NULL) root = tmpX; else { if(tmpY == tmpY->parent->left) tmpY->parent->left = tmpX; else tmpY->parent->right = tmpX; } if(tmpY != tmpZ) tmpZ->key = tmpY->key; } void inOrderTree(pNode & root) { pNode tmp = root; stack <pNode> s; while(tmp != NULL || !s.empty() ) { if(tmp != NULL) { s.push(tmp); tmp = tmp->left; } else { tmp = s.top(); printf("%d " , tmp->key); s.pop(); tmp = tmp->right; } } } int _tmain(int argc, _TCHAR* argv[]) { pNode root = NULL; treeInsert(root , 15); treeInsert(root , 6); treeInsert(root , 18); treeInsert(root , 3); treeInsert(root , 7); treeInsert(root , 17); treeInsert(root , 20); treeInsert(root , 2); treeInsert(root , 4); treeInsert(root , 13); treeInsert(root , 9); inOrderTree(root); printf("\n"); treeDelete(root , root); inOrderTree(root); printf("\n"); system("pause"); return 0; }
true
4e4559f334b882ed8bb126120b04a9488cc3d24d
C++
simsieg/DYOD_WS1819
/src/test/storage/dictionary_segment_test.cpp
UTF-8
3,909
2.859375
3
[ "MIT" ]
permissive
#include <memory> #include <string> #include "gtest/gtest.h" #include "../../lib/resolve_type.hpp" #include "../../lib/storage/base_segment.hpp" #include "../../lib/storage/dictionary_segment.hpp" #include "../../lib/storage/fitted_attribute_vector.cpp" #include "../../lib/storage/value_segment.hpp" class StorageDictionarySegmentTest : public ::testing::Test { protected: std::shared_ptr<opossum::ValueSegment<int>> vc_int = std::make_shared<opossum::ValueSegment<int>>(); std::shared_ptr<opossum::ValueSegment<std::string>> vc_str = std::make_shared<opossum::ValueSegment<std::string>>(); }; TEST_F(StorageDictionarySegmentTest, CompressSegmentString) { vc_str->append("Bill"); vc_str->append("Steve"); vc_str->append("Alexander"); vc_str->append("Steve"); vc_str->append("Hasso"); vc_str->append("Bill"); auto col = opossum::make_shared_by_data_type<opossum::BaseSegment, opossum::DictionarySegment>("string", vc_str); auto dict_col = std::dynamic_pointer_cast<opossum::DictionarySegment<std::string>>(col); // Test attribute_vector size EXPECT_EQ(dict_col->size(), 6u); // Test dictionary size (uniqueness) EXPECT_EQ(dict_col->unique_values_count(), 4u); // Test sorting auto dict = dict_col->dictionary(); EXPECT_EQ((*dict)[0], "Alexander"); EXPECT_EQ((*dict)[1], "Bill"); EXPECT_EQ((*dict)[2], "Hasso"); EXPECT_EQ((*dict)[3], "Steve"); } TEST_F(StorageDictionarySegmentTest, LowerUpperBound) { for (int i = 0; i <= 10; i += 2) vc_int->append(i); auto col = opossum::make_shared_by_data_type<opossum::BaseSegment, opossum::DictionarySegment>("int", vc_int); auto dict_col = std::dynamic_pointer_cast<opossum::DictionarySegment<int>>(col); EXPECT_EQ(dict_col->lower_bound(4), (opossum::ValueID)2); EXPECT_EQ(dict_col->upper_bound(4), (opossum::ValueID)3); EXPECT_EQ(dict_col->lower_bound(5), (opossum::ValueID)3); EXPECT_EQ(dict_col->upper_bound(5), (opossum::ValueID)3); EXPECT_EQ(dict_col->lower_bound(15), opossum::INVALID_VALUE_ID); EXPECT_EQ(dict_col->upper_bound(15), opossum::INVALID_VALUE_ID); } TEST_F(StorageDictionarySegmentTest, AppendElements) { vc_str->append("Bill"); auto col = opossum::make_shared_by_data_type<opossum::BaseSegment, opossum::DictionarySegment>("string", vc_str); auto dict_col = std::dynamic_pointer_cast<opossum::DictionarySegment<std::string>>(col); // Test appending new element EXPECT_ANY_THROW(dict_col->append("Steve")); } TEST_F(StorageDictionarySegmentTest, GetElements) { vc_str->append("Bill"); vc_str->append("Steve"); vc_str->append("Alexander"); vc_str->append("Steve"); vc_str->append("Hasso"); vc_str->append("Bill"); auto col = opossum::make_shared_by_data_type<opossum::BaseSegment, opossum::DictionarySegment>("string", vc_str); auto dict_col = std::dynamic_pointer_cast<opossum::DictionarySegment<std::string>>(col); // Test getting elements EXPECT_EQ(dict_col->get(0), "Bill"); EXPECT_EQ(dict_col->get(1), "Steve"); EXPECT_EQ(dict_col->get(3), "Steve"); EXPECT_ANY_THROW(dict_col->get(6)); } TEST_F(StorageDictionarySegmentTest, DictionaryEncoding) { vc_str->append("Bill"); vc_str->append("Steve"); vc_str->append("Alexander"); vc_str->append("Steve"); vc_str->append("Bill"); auto col = opossum::make_shared_by_data_type<opossum::BaseSegment, opossum::DictionarySegment>("string", vc_str); auto dict_col = std::dynamic_pointer_cast<opossum::DictionarySegment<std::string>>(col); // Test getting elements EXPECT_EQ(dict_col->value_by_value_id(opossum::ValueID(0)), "Alexander"); EXPECT_EQ(dict_col->value_by_value_id(opossum::ValueID(1)), "Bill"); EXPECT_EQ(dict_col->value_by_value_id(opossum::ValueID(2)), "Steve"); EXPECT_ANY_THROW(dict_col->value_by_value_id(opossum::ValueID(3))); } // TODO(student): You should add some more tests here (full coverage would be appreciated) and possibly in other files.
true
447fb47c62b565350b913b1bb67d132e067cff59
C++
du-dung/algorithm
/PROG_기둥과보설치_200506.cpp
UTF-8
2,359
3.203125
3
[]
no_license
/* 기둥과 보 설치 Level 3 https://programmers.co.kr/learn/courses/30/lessons/60061 */ #include <algorithm> #include <vector> using namespace std; #define x frame[0] #define y frame[1] bool isok(vector<vector<vector<bool>>>& map){ //조건을 만족하는지 for (int i=0; i<map.size(); i++) { for (int j=0; j<map.size(); j++) { if (map[i][j][0] //기둥이 있는데 && !(i == 0 || map[i-1][j][0] || map[i][j][1] || (j>0 && map[i][j-1][1]))) { //조건 만족 x return false; } if (map[i][j][1] //보가 있는데 && !(map[i-1][j][0] || map[i-1][j+1][0] || ((j>0 && map[i][j-1][1]) && map[i][j+1][1]))) { //조건 만족 x return false; } } } return true; } vector<vector<int>> solution(int n, vector<vector<int>> build_frame) { vector<vector<vector<bool>>>map(n+1, vector<vector<bool>>(n+1, vector<bool>(2, false))); //[n+1][n+1][2] 인 3차원 배열, [][][0]은 기둥, [][][1]은 보 for (vector<int> &frame : build_frame) { if (frame[3] == 1) { //설치 if (frame[2] == 0) { //기둥 if (y == 0 //바닥 위에 있거나 || map[y-1][x][0] //다른 기둥 위에 있거나 || map[y][x][1] || (x>0 && map[y][x-1][1]) //보의 한쪽 끝 부분 위에 있거나 ) { map[y][x][0] = true; } }else{ //보 if (map[y-1][x][0] || map[y-1][x+1][0] //다른 기둥 위에 있거나 || ((x>0 && map[y][x-1][1]) && map[y][x+1][1]) //양쪽 끝 부분이 다른 보와 동시에 연결 ) { map[y][x][1] = true; } } }else{ //삭제 map[y][x][frame[2]] = false; //일단 삭제해보고 if(!isok(map)) map[y][x][frame[2]] = true; //조건 만족 x -> 원상복구 } } //리턴 형식 맞추기 vector<vector<int>> answer; answer.reserve(n*n*2); for (int i=0; i<=n; i++) { for (int j=0; j<=n; j++) { for (int k=0; k<2; k++) { if(map[i][j][k]) answer.push_back({j, i, k}); } } } sort(answer.begin(), answer.end()); return answer; }
true
693f6149c7ebe04fcccf1c7e1b8df9ff2959104c
C++
shinw97/MY-UVA-Solutions
/CPP/uva10013.cpp
UTF-8
876
2.921875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <vector> using namespace std; int main(){ int testcase; scanf("%d", &testcase); bool first = true; for(int i = 0; i < testcase; i++){ if(!first){ cout<<endl; } first = false; int digits; scanf("%d", &digits); vector<int> n1; vector<int> n2; int x, y; for(int j = 0; j < digits; j++){ scanf("%d %d", &x, &y); n1.push_back(x); n2.push_back(y); } int sum = 0, carry = 0; string ans(digits, ' '); for(int j = digits - 1; j >= 0; j--){ sum = n1[j] + n2[j] + carry; carry = sum / 10; ans[j] = (sum % 10 ) + '0'; } if(carry == 1){ printf("1"); } cout<<ans<<endl; } return 0; }
true
4ec4b795c333cbf608068bb30d9a3cf18abf8ef2
C++
siegfrkn/CSCI2270_dataStructures
/Lecture/CSCI2270_Lecture12/bst.cpp
UTF-8
1,770
3.53125
4
[ "MIT" ]
permissive
//#include <stdio.h> //#include <iostream> using namespace std; #include "bst_class.h" BST::BST() { // go to BST and access BST } BST::~BST(){ } Node *BST::createNode(int value, Node *parent, Node *left, Node *right) { //go to the BST class and access the function createNode // as soon as i instantiate it will have left and right set to nullptr Node *newNode = new Node; newNode -> key = value; newNode -> parent = parent; newNode -> left = left; newNode -> right = right; return newNode; } bool BST::addNode(int value){ Node *tmpNode = root; Node *curParent = nullptr; // if there is nothing in the tree... if (!root){ root = createNode(value, nullptr, nullptr, nullptr); cout << "new root created" << endl; // for debug purposes, not needed or encouraged return false;; } // traverse the tree and find the correct place // think while loop - while I don't reach the bottom of my tree while (tmpNode != nullptr) { // set the current parent curParent = tmpNode; // fundamental for the logic below // will be the parent of our new child if(value > tmpNode -> key) { tmpNode = tmpNode -> right; } else { tmpNode = tmpNode -> left; } } // When found the right parent to add the child to the new child either // to the left or to the right // if null? if (curParent == nullptr){ root = createNode(value, nullptr, nullptr, nullptr); } // else add it to the left else if (value < curParent -> key){ curParent -> left = createNode(value, curParent, nullptr, nullptr); } // else add it to the left else if (value < curParent -> key){ curParent -> right = createNode(value, curParent, nullptr, nullptr); } return true; }
true
31c913b206739dbbb5369240e4ed7e017989803a
C++
anatartari/War
/Auxi.cpp
UTF-8
2,253
2.609375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <cstdio> #include <ctime> using namespace std; class Territorio; //Dados do Jogador class jogador{ public: int id; char nome[20]; int Ndominios; int cor; }; //Dados do territorio class Territorio{ public: jogador* player; int x, y, id; Territorio* fronteira[8]; int nexercitos; }; Territorio paisesT[26]; /* declarando os paises */ Territorio paisesTaux[26]; /* variavel auxiliar para regra de remanejamento */ jogador player1, player2; jogador* dono_da_vez; char user; int user_int; bool fim = false; int dado_atk[3]; int dado_def[3]; void ordenar_dados(); int random(int menor, int maior); int turno=1; //Ordem decrescente. void ordenar_dados(){ int aux[3]={0,0,0}, p[3]={0,0,0}; /* ordenando os dados de ataque */ for(int i=0; i<3; i++) if(aux[0] < dado_atk[i] ){ aux[0] = dado_atk[i]; // guarda o maior em aux p[0] = i; } for(int i=0; i<3; i++) if(aux[1] < dado_atk[i] && i != p[0]) { aux[1] = dado_atk[i]; // guarda o intermediario em aux p[1] = i; } for(int i=0; i<3; i++) if(i != p[0] && i != p[1]) aux[2] = dado_atk[i]; // guarda o menor em aux //Guarda em ordem for(int i=0; i<3; i++){ dado_atk[i] = aux[i]; aux[i] = 0; p[i]=0; } /* ordenando os dados de defesa */ for(int i=0; i<3; i++) if(aux[0] < dado_def[i] ){ aux[0] = dado_def[i]; // guarda o maior em aux p[0] = i; } for(int i=0; i<3; i++) if(aux[1] < dado_def[i] && i != p[0]) { aux[1] = dado_def[i]; // guarda o intermediario em aux p[1] = i; } for(int i=0; i<3; i++) if(i != p[0] && i != p[1]) aux[2] = dado_def[i]; // guarda o menor em aux //Guarda em ordem for(int i=0; i<3; i++){ dado_def[i] = aux[i]; aux[i] = 0; p[i] = 0; } } int random(int menor, int maior){ return rand()%(maior-menor+1)+menor; } void rolar_dados(int num_atk, int num_def){ if(num_atk > 3)num_atk = 3; if(num_def > 3)num_def = 3; for(int i=0; i<3; i++){ dado_atk[i] = 0; dado_def[i] = 0; } for(int i=0; i<num_atk; i++){ dado_atk[i] = random(1, 6); } for(int i=0; i<num_def; i++){ dado_def[i] = random(1, 6); } }
true
aac53ab174d90fc8bb29cc5639c1162200343d0e
C++
MrLukeKR/Party-Animals
/G53GRA.Framework/Code/Objects/DJ Objects/Scaffolding.cpp
UTF-8
1,782
3.03125
3
[]
no_license
#include "Scaffolding.h" /* Party Animals: Scaffolding Author: Luke K. Rose April 2018 */ /* Draws the object */ void Scaffolding::Display() { glPushMatrix(); glPushAttrib(GL_ALL_ATTRIB_BITS); glTranslatef(pos[0], pos[1], pos[2]); glScalef(scale[0], scale[1], scale[2]); glRotatef(rotation[0], 1.f, 0.f, 0.f); glRotatef(rotation[1], 0.f, 1.f, 0.f); glRotatef(rotation[2], 0.f, 0.f, 1.f); drawScaffolding(); //Draw the scaffolding to hold the DJ equipment glPopAttrib(); glPopMatrix(); } /* Draws the scaffolding to hold the DJ equipment */ void Scaffolding::drawScaffolding() { glColor4f(0.3f, 0.3f, 0.3f, 1); //Set the colour to opaque dark grey drawHalf(); //Draw half of the scaffolding glRotatef(180, 0, 1, 0); //Flip around drawHalf(); //Draw the other half of the scaffolding } /* Draws half of the scaffolding for assured mirrored modelling */ void Scaffolding::drawHalf() { glPushMatrix(); gluCylinder(gluNewQuadric(), .5f, 0.5f, 35, 5, 5); //Draw a pole glPushMatrix(); glTranslatef(0, -3, 0); //Move down by 3 gluCylinder(gluNewQuadric(), .5f, 0.5f, 35, 5, 5); //Draw another pole glPopMatrix(); glTranslatef(0, 0, 35); //Move forward by 35 glPushMatrix(); glRotatef(90, 1, 0, 0); //Rotate 90 degrees counter clockwise along the x axis gluCylinder(gluNewQuadric(), .5f, .5f, 20, 5, 5); //Draw another pole glPopMatrix(); glTranslatef(0, -20, 0); //Move down by 20 for (int i = 0; i < 3; i++) { //Draws the feet of the scaffolding glRotatef(120, 0, 1, 0); //Rotate 120 degrees counter clockwise around the y axis glPushMatrix(); glRotatef(45, 1, 0, 0); //Rotate 45 degrees around the x axis gluCylinder(gluNewQuadric(), .5f, .5f, 5, 5, 5); //Draw another pole glPopMatrix(); } glPopMatrix(); }
true
779752df0b20bf0bbfc1ec21ce1049fe50e403a4
C++
MOZGIII/nqueens-genetic-cpp
/src/genetic.cpp
UTF-8
4,552
3.109375
3
[]
no_license
#include <set> #include "NQueens.h" class Chromosome { public: Chromosome(NQueens::board_t board) : board(board), value(NQueens::score(board)) { } const NQueens::board_t board; const int value; inline bool operator<(const Chromosome& rhs) const { return value < rhs.value; } }; typedef std::multiset<Chromosome> population_t; const int population_size = 100; void fill_initial_population(population_t * population) { auto local_population_size = population_size; if(local_population_size > 2) { population->emplace(0); population->emplace(NQueens::board_mask); local_population_size -= 2; } for (int i = 0; i < local_population_size; ++i) { population->emplace(NQueens::randomBoard()); } } Chromosome fullrandom_crossingover(const Chromosome& one, const Chromosome& two) { #define set_bits(a, b) (((a) & NQueens::board_mask) & ((b) & NQueens::board_mask)) #define mix(a, b, shift) (set_bits((a), (shift)) | set_bits((b), ~(shift))) NQueens::board_t shift = NQueens::randomBoard(); NQueens::board_t new_board = mix(one.board, two.board, shift); return Chromosome(new_board); } Chromosome half_crossingover(const Chromosome& one, const Chromosome& two) { NQueens::board_t new_board = (one.board & 0x00FFF000) | (two.board & 0x00000FFF); return Chromosome(new_board); } Chromosome random_single_crossingover(const Chromosome& one, const Chromosome& two) { NQueens::board_t split_mask = ((1 << ((rand() % 22) + 1)) - 1); NQueens::board_t new_board = (one.board & (split_mask & NQueens::board_mask)) | (two.board & (~split_mask & NQueens::board_mask)); return Chromosome(new_board); } Chromosome mutate(const Chromosome& source) { NQueens::board_t new_board = source.board; NQueens::moveRandomQueenRandomly(new_board); return Chromosome(new_board); } void print_population(const population_t& population) { for (auto i = population.cbegin(); i != population.cend(); ++i) { std::cout << (*i).value << " "; } std::cout << std::endl; } Chromosome subling(const Chromosome& one, const Chromosome& two) { if((rand() % 10) == 0) { // mutate return mutate(random_single_crossingover(one, two)); } else { // no mutate return random_single_crossingover(one, two); } } bool population_same(const population_t& population) { int local_value; auto i = population.cbegin(); local_value = (*i).value; ++i; for (; i != population.cend(); ++i) { if((*i).value != local_value) return false; } return true; } bool population_contains_optimal(const population_t& population) { auto i = population.cbegin(); return (*i).value == 0; } const Chromosome& random_high_fitness_chromosome(const population_t& population) { auto best = population.cbegin(); auto c = population.count(*best); if(c == 1) { return *best; } int distance = rand() % (c - 1); // std::cout << "D: " << distance << " from " << (c - 1) << std::endl; std::advance(best, distance); return *best; } const Chromosome& random_any_fitness_chromosome(const population_t& population) { auto chosen = population.cbegin(); int distance = rand() % (population.size() - 1); std::advance(chosen, distance); return *chosen; } const Chromosome& random_first_half_fitness_chromosome(const population_t& population) { auto chosen = population.cbegin(); int distance = rand() % (population.size()/2 - 1); std::advance(chosen, distance); return *chosen; } Chromosome Genetic() { population_t * current_population = new population_t; fill_initial_population(current_population); bool stop = false; while(!stop) { population_t * next_population = new population_t; for (int i = 0; i < population_size/2; ++i) { auto one = random_first_half_fitness_chromosome(*current_population); auto two = random_first_half_fitness_chromosome(*current_population); next_population->insert(subling(one, two)); next_population->insert(subling(one, two)); } delete current_population; current_population = next_population; // std::cout << "==========" << std::endl; // print_population(*current_population); // auto board = (*(current_population->cbegin())).board; // std::cout << "Score: " << NQueens::score(board) << std::endl; // NQueens::printBoard(std::cout, board); // NQueens::drawBoard(std::cout, board); if(population_contains_optimal(*current_population)) { stop = true; } } return *current_population->cbegin(); }
true
5f26e355ba6ec3ec0d1b12e46775a5c6164a5066
C++
more-tacigar/ARC-Answers
/ARC-004-A/main.cpp
UTF-8
654
3.171875
3
[]
no_license
#include <iostream> #include <cmath> #include <vector> using namespace std; struct P { double x; double y; }; int main() { double max = 0.0; int N; cin >> N; vector<P> Ps; for (int i = 0; i < N; i++) { double x, y; cin >> x >> y; P tmp = {x, y}; Ps.push_back(tmp); } for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { double dx = Ps[i].x - Ps[j].x; double dy = Ps[i].y - Ps[j].y; double tmp = dx * dx + dy * dy; if (max < tmp) { max = tmp; } } } cout << sqrt(max) << endl; }
true
f97db0482afdc62571a48bbb73ab0b262bfc53b0
C++
Crazy-Dog/LearnAdvancedCppProgrammingCourse
/Files/ReadingTextFiles/Source.cpp
UTF-8
377
3
3
[]
no_license
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream inf; string filename = "text.txt"; inf.open(filename); if (inf.is_open()) { string line; while (inf) { getline(inf, line); cout << line << endl; } inf.close(); } else { cout << "Can't open file" << filename << endl; } getchar(); return 0; }
true
0e3bc44ccbfa23f1636bfff8c7c50a9ebe34e045
C++
juniway/lint
/data_structures/graph/nearest_bike_recursive.cpp
UTF-8
1,062
3.140625
3
[]
no_license
#include <iostream> #include <queue> #include <vector> using namespace std; struct BuildingBlock{ int row, col, distance; BuildingBlock(int row, int col):row(row), col(col) {} }; BuildingBlock findBikeBFS(vector<vector<int>> buildings, BuildingBlock&& bb, vector<vector<bool>>& visited) { int n = buildings.size(); int m = buildings[0].size(); if (bb.row < 0 || bb.row >= n \ || bb.col < 0 || bb.col >= m || visited[bb.row][bb.col]) return BuildingBlock(-1, -1); if (buildings[bb.row][bb.col] == 1) { bb.distance = 1; return bb; } visited[bb.row][bb.col] = true; } BuildingBlock findBike(vector<vector<int>> buildings, int start_row, int start_col) { int row_size = buildings.size(); if (row_size == 0) return BuildingBlock(-1, -1); int col_size = buildings[0].size(); if (col_size == 0) return BuildingBlock(-1, -1); vector<vector<bool>> visited(row_size, vector<bool>(col_size, false)); return findBikeBFS(buildings, BuildingBlock(start_row, start_col)); }
true
ed8bb768e22596036bca012c457fd78c49045935
C++
yashul117/DSA-Sheet
/bit manipulation/10 power set.cpp
UTF-8
853
3.15625
3
[]
no_license
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: vector<string> AllPossibleStrings(string s) { // Code here int powerSet_size = pow(2, s.length()); vector<string> ans; for (int i = 0; i < powerSet_size; i++) { string temp = ""; for (int j = 0; j < s.length(); j++) { if (i & (1 << j)) { temp.push_back(s[j]); } } ans.push_back(temp); } vector<string> res; for (auto x : ans) { if (x != "") { res.push_back(x); } } sort(res.begin(), res.end()); return res; } }; // { Driver Code Starts. int main() { int tc; cin >> tc; while (tc--) { string s; cin >> s; Solution ob; vector<string> res = ob.AllPossibleStrings(s); for (auto i : res) cout << i << " "; cout << "\n"; } return 0; } // } Driver Code Ends
true
ad01e97cde6a5b48144558f5f888df4c162d48bc
C++
chiraggarg96/VirtualKeyboard
/service.h
UTF-8
2,722
2.65625
3
[]
no_license
#include <windows.h> #include <stdio.h> #include<inttypes.h> #include<winuser.h> #include<string> #include "mapping.h" HANDLE hStdin; DWORD fdwSaveOldMode; std::string s; SpecialCharacters *specialCharactersObj; VOID ErrorExit(LPSTR); VOID KeyEventProc(KEY_EVENT_RECORD,Mapping* mappingObject); VOID ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD); int service(VOID) { specialCharactersObj = new SpecialCharacters; DWORD cNumRead, fdwMode, i; INPUT_RECORD irInBuf[128]; int counter=0; s=""; // Mapping mappingObject = new Mapping(); Mapping * mappingObject = new Mapping; // Get the standard input handle. hStdin = GetStdHandle(STD_INPUT_HANDLE); if (hStdin == INVALID_HANDLE_VALUE) ErrorExit("GetStdHandle"); // Save the current input mode, to be restored on exit. if (! GetConsoleMode(hStdin, &fdwSaveOldMode) ) ErrorExit("GetConsoleMode"); // Enable the window and mouse input events. fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT; if (! SetConsoleMode(hStdin, fdwMode) ) ErrorExit("SetConsoleMode"); // Loop to read and handle the next 100 input events. while (true) { // Wait for the events. if (! ReadConsoleInput( hStdin, // input buffer handle irInBuf, // buffer to read into 128, // size of read buffer &cNumRead) ) // number of records read ErrorExit("ReadConsoleInput"); // Dispatch the events to the appropriate handler. for (i = 0; i < cNumRead; i++) { switch(irInBuf[i].EventType) { case KEY_EVENT: // keyboard input KeyEventProc(irInBuf[i].Event.KeyEvent,mappingObject); break; case MOUSE_EVENT: // mouse input break; case WINDOW_BUFFER_SIZE_EVENT: // scrn buf. resizing break; case FOCUS_EVENT: // disregard focus events case MENU_EVENT: // disregard menu events break; default: ErrorExit("Unknown event type"); break; } } } // Restore input mode on exit. SetConsoleMode(hStdin, fdwSaveOldMode); return 0; } VOID ErrorExit (LPSTR lpszMessage) { fprintf(stderr, "%s\n", lpszMessage); // Restore input mode on exit. SetConsoleMode(hStdin, fdwSaveOldMode); ExitProcess(0); } VOID KeyEventProc(KEY_EVENT_RECORD ker,Mapping* mappingObject) { if(ker.bKeyDown) { char characterPressed= mappingObject->getCharMapping((int)ker.wVirtualKeyCode,specialCharactersObj); if(characterPressed==13) { std::cout<<s<<std::endl; s=""; } else if(characterPressed==8) { if(!s.empty()) s.pop_back(); } else if(characterPressed!=0) { s=s+characterPressed; } } }
true
29d1635e0628237ea0a8cc9c2505bb971227ae3d
C++
yumakmc/cuigame
/Project3/Project3/Common.h
SHIFT_JIS
2,880
3.046875
3
[]
no_license
#ifndef __COMMON_H__ #define __COMMON_H__ #include <cassert> #include <tchar.h> #include <windows.h> #include <string> #include "typedef.h" using namespace Library; namespace Common { enum ERROR_CODE { ERR_CONSTRUCT = 1, // RXgN^O }; namespace Meta { // rbgʒu̐ÓIZo // lNɂ‚āAő̃rbgʒuƍŏ̃rbgʒu //iF126most:7,least:1 128most:8, least:8 template<U32 N> struct BitPos { enum { most = (1 < N) ? BitPos<N / 2>::most + 1 : 0, least = ((N & 1) == 0) ? BitPos<N / 2>::least + 1 : 0 }; }; template<> struct BitPos<0> { enum { most = -1, least = -1 }; }; // ^`FbN template<class T1, class T2> struct isEqualType { static const bool result = false; }; template<class T1> struct isEqualType<T1, T1> { static const bool result = true; }; } // XbvNX class Swap { public: // ľ template<typename T> static void xor(T& v1, T& v2) { assert((&v1 != &v2) && ((&v1 != 0) && (&v2 != 0))); v1 ^= v2, v2 ^= v1, v1 ^= v2; } // ľ template<typename T> static void temporary(T* v1, T* v2) { assert((v1 != 0) && (v2 != 0)); T tv = *v1; *v1 = *v2; *v2 = tv; } // rbgp^[̋t] template<typename T> static T reverseBits(T v) { assert(sizeof T <= 4); switch(sizeof T) { case 4: v = (v >> 16) | (v << 16); case 2: v = ((v & 0xff00ff00) >> 8) | ((v & 0x00ff00ff) << 8); case 1: v = ((v & 0xf0f0f0f0) >> 4) | ((v & 0x0f0f0f0f) << 4); v = ((v & 0xcccccccc) >> 2) | ((v & 0x33333333) << 2); v = ((v & 0xaaaaaaaa) >> 1) | ((v & 0x55555555) << 1); } return v; } }; // ^NX class Rand { public: // void init(); // S32 gen(); U32 ugen(); // zVbt template<typename T> void shuffle(T* arrayVal, U32 valueCnt) { assert(arrayVal != 0); for(U32 i = 0; i < valueCnt; i++) { Swap::temporary(&arrayVal[ugen() % valueCnt], &arrayVal[i]); } } private: typedef S32 (*GENERATE)(); typedef U32 (*UGENERATE)(); static GENERATE fn_Generate; static UGENERATE fn_UGenerate; }; // R\[EBhE֘ANX class ConsoleWindow { public: typedef void (*CLOSEFUNC)(int); HWND getHandle() const; // EBhEnh擾 void setTitle(const TCHAR* const newTitle) const; // ^Cgݒ void entryCloseCallback(CLOSEFUNC function); // EBhEĨR[obN֐o^ private: static BOOL WINAPI HandlerRoutine(DWORD dwCtrlType); static CLOSEFUNC fn_close; }; std::string inline To_ZString(const int anum) { std::string st = std::to_string(anum); if (st.size() % 2) { st = " " + st; } return st; } }; #endif // __COMMON_H__
true
38d58f8b3c3481f0c1c1a8c18c3c51642b5bfe32
C++
BranimirE/Workspace
/UVa/10110 - Light, more light/main.cpp
UTF-8
770
3
3
[]
no_license
#include <iostream> #include <bitset> #include <vector> using namespace std; #define MAXP 66000 bitset<MAXP+2> criba; vector<int> primos; void generaPrimos(){ criba.set(); for(int i = 2;i <= MAXP; i++ ) if(criba[i]){ primos.push_back(i); for(int j = i + i; j <= MAXP; j += i) criba[j] = false; } } long long int divisores(long long int nro){ int i = 0; long long int ans = 1; while(i < primos.size() && primos[i] * primos[i] <= nro){ long long int tmp = 0; while(nro%primos[i] == 0){ nro /= primos[i]; tmp++; } ans = ans * (tmp + 1); i++; } if(nro > 1) ans *= 2; return ans; } int main(){ generaPrimos(); long long int nro; while(cin >> nro && nro){ cout << ((divisores(nro)%2 == 0)?"no":"yes") << endl; } return 0; }
true
08380ba0f553ad7aaec44508421cbe56ee9db1be
C++
JeakeG/Portal
/ConceptTest/ConceptTest.ino
UTF-8
2,037
2.9375
3
[]
no_license
/* * ConceptTest * * The purpose of this sketch is to test team Portal's concept design. * It will consist of having the an arduino communicate with a motor driver so that a stepper * motor will be controlled within by two buttons. * * Created 18 Feb 2021 * Jake Guidry * Modified 19 Feb 2021 * Jake Guidry *It work now* * * https://github.com/JeakeG/Portal * * Driver Connections * PU+ => 5V * PU- => 11 * * DR+ => 5V * DI- => 13 * * Run Button attaches to pin 3 and ground * Dir Button attaches to pin 2 and ground * * Pot attaches to +5V, pin A0, and ground */ int const PUL_PIN = 11; int const DIR_PIN = 13; int const GO_READ_PIN = 3; int const DIR_READ_PIN = 2; int const POT_PIN = A0; bool shouldGo = false; int long last_go_interrupt = 0; int long last_dir_interrupt = 0; void setup() { pinMode(PUL_PIN, OUTPUT); pinMode(DIR_PIN, OUTPUT); pinMode(GO_READ_PIN, INPUT_PULLUP); pinMode(DIR_READ_PIN, INPUT_PULLUP); digitalWrite(DIR_PIN, LOW); attachInterrupt(digitalPinToInterrupt(GO_READ_PIN), toggleRunning, RISING); attachInterrupt(digitalPinToInterrupt(DIR_READ_PIN), toggleDirection, RISING); Serial.begin(9600); } void loop() { if (shouldGo) { int time = map(analogRead(POT_PIN), 0, 1023, 1, 1000); digitalWrite(PUL_PIN, HIGH); delayMicroseconds(time); digitalWrite(PUL_PIN, LOW); delayMicroseconds(time); } else { delay(1); } } void toggleRunning() { long time = millis(); if (time - last_go_interrupt > 200) { shouldGo = !shouldGo; if (shouldGo) { Serial.println("Running: True"); } else { Serial.println("Running: False"); } } last_go_interrupt = time; } void toggleDirection() { long time = millis(); if (time - last_dir_interrupt > 200) { digitalWrite(DIR_PIN, !digitalRead(DIR_PIN)); if (digitalRead(DIR_PIN)) { Serial.println("Direction: 1"); } else { Serial.println("Direction: 0"); } } last_dir_interrupt = time; }
true
738653b22cf2b300a2f58b1d55932acfd6fcb7c8
C++
pthis/CppLogging
/include/logging/appender.h
UTF-8
989
3.03125
3
[ "MIT" ]
permissive
/*! \file appender.h \brief Logging appender interface definition \author Ivan Shynkarenka \date 26.07.2016 \copyright MIT License */ #ifndef CPPLOGGING_APPENDER_H #define CPPLOGGING_APPENDER_H #include "logging/element.h" #include "logging/record.h" namespace CppLogging { //! Logging appender interface /*! Logging appender takes an instance of a single logging record and store it content in some storage or show it in console. \see NullAppender \see ConsoleAppender \see DebugAppender \see ErrorAppender \see MemoryAppender \see OstreamAppender \see FileAppender \see RollingFileAppender \see SysLogAppender */ class Appender : public Element { public: //! Append the given logging record /*! \param record - Logging record */ virtual void AppendRecord(Record& record) = 0; //! Flush the logging appender virtual void Flush() {} }; } // namespace CppLogging #endif // CPPLOGGING_APPENDER_H
true
84b363b9d284cb98a7dd0bc10df76de0d1eba3e0
C++
wangdongshi/RTOS
/rtos/eHMI/proj/inc/EHmiMain.h
UTF-8
1,286
2.703125
3
[ "BSD-2-Clause" ]
permissive
/// /// file EHmiMain.h /// brief HMI main process file /// /// author Wang.Yu /// version 00.01.00 /// date 2018/11/26 /// #include <queue> #include <mutex> #include <condition_variable> #include <X11/Xlib.h> #include "SCColor.h" #include "SCDrawCommand.h" #include "SCBoard.h" #include "EHmiEvent.h" #ifndef __EHMI_MAIN_H__ #define __EHMI_MAIN_H__ enum _SCRENN_ID { SCREEN_NONE = -1, SCREEN_TEST1, SCREEN_TEST2, SCREEN_TEST3, }; /// /// class : EHmiMain /// HMI main class /// class EHmiMain { public : EHmiMain(); virtual ~EHmiMain(); void Start(void) {run();} bool IsReady(void) {return(is_ready);} void SetReady(bool ready) {is_ready = ready;} std::mutex& Mutex(void) {return(mtx);} std::condition_variable& ConditionVariable(void) {return(cv);} void AddQueue(EHmiEvent ev) {deq.push_back(ev);} private : void run(void); void main(void); void eventHandler(EHmiEvent& ev); public : void StartScreen(void); void ChangeScreen(const short id, const EHmiEvent& ev); SCBoard* GetBoard(){return(m_screen);} private : std::deque<EHmiEvent> deq; std::mutex mtx; std::condition_variable cv; bool is_ready; short m_screen_id; SCBoard* m_screen; }; #endif // __EHMI_MAIN_H__
true
113746c5007dc121778b363e9298466295000b6d
C++
sammiewalker9/Assignment-6
/Sorting.cpp
UTF-8
5,958
3.84375
4
[]
no_license
#include <iostream> #include <fstream> #include <time.h> // in order to use clock function #include "Sorting.h" using namespace std; Sorting::Sorting(){ } Sorting::~Sorting(){ delete [] bubbleArray; delete [] insertArray; delete [] selectionArray; delete [] quickSortArray; } // this function will open the file and create the arrays void Sorting::readFile(string fileName){ string numElems; string line; double size; // will be the first line in the file int lineNumber = 1; ifstream inputFile; inputFile.open(fileName.c_str()); getline(inputFile, numElems); nElems = atoi(numElems.c_str()); // convert string to int // create arrays for each type of sorting algorithm, make size the first number in the file bubbleArray = new double[nElems]; insertArray = new double[nElems]; selectionArray = new double[nElems]; quickSortArray = new double[nElems]; for(int i = 0; i < nElems; ++i){ lineNumber ++; getline(inputFile, line); size = stod(line); // the num of elems to sort bubbleArray[i] = size; insertArray[i] = size; selectionArray[i] = size; } inputFile.close(); timer(); // call function to run all algorithms } /* Bubble Sort: - move through array comparing neighboring pairs of elements and swap them if they are not in the correct order - time complexity: O(n^2) */ void Sorting::bubbleSort(double array[], int n){ for(int i = 0; i < n; ++i){ double temp = 0; for(int j = 0; j < (n-1); ++j){ if(array[j] > array[j+1]){ temp = array[j+1]; array[j+1] = array[j]; array[j] = temp; } } } // check to make sure it's sorting correctly: /*cout << "Bubble Sort: " << endl; for(int f = 1; f < n; ++f){ cout<< array[f] << endl; }*/ } /* Insertion Sort: - use a marker, paritally sorted to left of marker - check elem to right of marker and move it to it's place on the left - time complexity: O(n^2) */ void Sorting::insertionSort(double array[], int n ){ for(int i = 1; i < nElems; ++i){ // marker double temp = array[i]; // store marked item int marker = i; // where to start shiftting while(marker > 0 && array[marker-1] >= temp){ // while the thing to the left is larger, shift array[marker] = array[marker-1]; --marker; } array[marker] = temp; // put marked item in the right spot } } /* Selection Sort: - find the smallest element in the array, bring it to the front, and recurse on rest of array - time complexity: O(n^2) */ void Sorting::selectionSort(double array[], int n){ int i; int j; int minIndex; int temp; for(i = 0; i < n-1; i++){ minIndex = i; for(j = i +1; j < n; j++){ if(array[j] < array[minIndex]){ minIndex = j; } } if(minIndex!=i){ temp = array[i]; array[i] = array[minIndex]; array[minIndex] = temp; } } } /* Quick Sort: - selecting a pivot element and move all elements bigger than the pivot into the right list and smaller than pivot in the left list - preform this recursively on the two new lists until list size reaches 0 or 1. - there are different methods for selecting the piovt, in this one we use the median value. - time complexity: most of the time it is O(nlogn) with randomized pivot. With a very bad pivot it ends up being O(n^2). */ void Sorting::quickSort(double array[], int left, int right, int n){ int index = partition(array, left, right); if(left < index-1){ // sort left half int idx = index - 1; quickSort(array, left, index-1, n); } if(index < right){ // sort right half quickSort(array, index, right, n); } } int Sorting::partition(double array[], int left, int right){ //choose middle value as pivot int pivot = array[(left+right)/2]; while(left <= right){ while(array[left] < pivot){ // objects to left of pivot left ++; } while(array[right] > pivot){ // objects to right of pivot right --; } if(left <= right){ // move elements and swap left and right swap(array, left, right); left ++; right--; } } return left; } void Sorting::swap(double array[], int a, int b){ double temp = array[a]; array[a] = array[b]; array[b] = temp; } // this function times each sorting algorithm and outputs the time void Sorting::timer(){ clock_t start; clock_t stop; float amntOfTime; // bubble sort start = clock(); bubbleSort(bubbleArray, nElems); stop = clock(); amntOfTime = (float(stop - start)/CLOCKS_PER_SEC) * 1000; // 1 second = 1 millisecond cout << "Bubble Sort: " << endl; cout << "Start time: " << start << endl; cout << "Stop time: " << stop << endl; cout << "Total amount of time: \n " << amntOfTime << " \n " << endl; // insertion sort start = clock(); insertionSort(insertArray, nElems); stop = clock(); amntOfTime = (float(stop - start)/CLOCKS_PER_SEC) * 1000; // 1 second = 1 millisecond cout << "Insertion Sort: " << endl; cout << "Start time: " << start << endl; cout << "Stop time: " << stop << endl; cout << "Total amount of time: \n" << amntOfTime << " \n " << endl; // selection sort start = clock(); selectionSort(selectionArray, nElems); stop = clock(); amntOfTime = (float(stop - start)/CLOCKS_PER_SEC) * 1000; // 1 second = 1 millisecond cout << "Selection Sort: " << endl; cout << "Start time: " << start << endl; cout << "Stop time: " << stop << endl; cout << "Total amount of time: " << amntOfTime << " \n " << endl; // quick sort start = clock(); quickSort(quickSortArray, 0, nElems-1, nElems); stop = clock(); amntOfTime = (float(stop - start)/CLOCKS_PER_SEC) * 1000; // 1 second = 1 millisecond cout << "Quick Sort: " << endl; cout << "Start time: " << start << endl; cout << "Stop time: " << stop << endl; cout << "Total amount of time: " << amntOfTime << " \n " << endl; cout << "\n Done sorting. \n" << endl; }
true
c8c97f3e35d61cf42701690078c6c033f927345a
C++
dmkz/competitive-programming
/codeforces.com/Codeforces Ladder 1600-1699 (extra)/0194A.cpp
UTF-8
707
3.34375
3
[]
no_license
/* Problem: 194A. Exams Solution: brute force, O(n^3) Author: Dmitry Kozyrev, github: dmkz, e-mail: dmkozyrev@rambler.ru */ #include <iostream> #include <algorithm> int solve(int n, int sum) { int min = n; for (int n5 = 0; n5 <= n; ++n5) { for (int n4 = 0; n4 + n5 <= n; ++n4) { for (int n3 = 0; n3 + n4 + n5 <= n; ++n3) { int n2 = n - n3 - n4 - n5; if (n5 * 5 + n4 * 4 + n3 * 3 + n2 * 2 == sum) { min = std::min(min, n2); } } } } return min; } int main() { int n, sum; while (std::cin >> n >> sum) { std::cout << solve(n, sum) << std::endl; } return 0; }
true
2b1614276d39e9f7a842a2648eaebde9d6b1f246
C++
rheehot/Algorithm-57
/BOJ/cpp/1654.cpp
UTF-8
2,639
3.171875
3
[]
no_license
/* 문제 집에서 시간을 보내던 오영식은 박성원의 부름을 받고 급히 달려왔다. 박성원이 캠프 때 쓸 N개의 랜선을 만들어야 하는데 너무 바빠서 영식이에게 도움을 청했다. 이미 오영식은 자체적으로 K개의 랜선을 가지고 있다. 그러나 K개의 랜선은 길이가 제각각이다. 박성원은 랜선을 모두 N개의 같은 길이의 랜선으로 만들고 싶었기 때문에 K개의 랜선을 잘라서 만들어야 한다. 예를 들어 300cm 짜리 랜선에서 140cm 짜리 랜선을 두 개 잘라내면 20cm는 버려야 한다. (이미 자른 랜선은 붙일 수 없다.) 편의를 위해 랜선을 자르거나 만들 때 손실되는 길이는 없다고 가정하며, 기존의 K개의 랜선으로 N개의 랜선을 만들 수 없는 경우는 없다고 가정하자. 그리고 자를 때는 항상 센티미터 단위로 정수길이만큼 자른다고 가정하자. N개보다 많이 만드는 것도 N개를 만드는 것에 포함된다. 이때 만들 수 있는 최대 랜선의 길이를 구하는 프로그램을 작성하시오. 입력 첫째 줄에는 오영식이 이미 가지고 있는 랜선의 개수 K, 그리고 필요한 랜선의 개수 N이 입력된다. K는 1이상 10,000이하의 정수이고, N은 1이상 1,000,000이하의 정수이다. 그리고 항상 K ≦ N 이다. 그 후 K줄에 걸쳐 이미 가지고 있는 각 랜선의 길이가 센티미터 단위의 정수로 입력된다. 랜선의 길이는 231-1보다 작거나 같은 자연수이다. 출력 첫째 줄에 N개를 만들 수 있는 랜선의 최대 길이를 센티미터 단위의 정수로 출력한다. */ #include <iostream> #define MAX 10001 using namespace std; int n, k; long long length[MAX]; long long low=1; long long high=0; long long result=0; void Input(){ cin>>n>>k; for(int i=1; i<=n; i++){ cin>>length[i]; } } bool possible(long long len){ long long cnt=0; for(int i=1; i<=n; i++){ cnt+=length[i]/len; } if(cnt>=k) return true; return false; } long long Solution(){ for(int i=1; i<=n; i++){ if(high<=length[i]){ high=length[i]; } } while(low<=high){ long long mid=(low+high)/2; if(possible(mid)){ if(result<mid){ result=mid; } low=mid+1; } else { high=mid-1; } } return result; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); Input(); cout<<Solution()<<endl; return 0; }
true
f05e2f90a750950192230e01da7b63f41e84c606
C++
Wxalex98/WeWinThisTime
/functions.cpp
UTF-8
1,205
2.75
3
[]
no_license
//float function for getting the distance between two points float vector[3]; float dist; bool areWeinsideShadow(float pos[3]){ float distance2center; centerPos[0] = pos[0]; distance2center = getDistance(centerPos, pos); if (pos[0] > 0 && distance2center < asteroidRadius) { return true; } else { return false; } } float getDistance(float pos[3],float target[3]){ mathVecSubtract(vector,target,pos,3); dist = mathVecMagnitude(vector,3); return dist; } //float function to get an angle between to attitudes float getAngle(float initAtt[3],float currentAtt[3]){ float dot = mathVecInner(initAtt,currentAtt,3); float angle = acosf(dot)*180/PI; return angle; } void move(float ourPos[3],float target[3]){ float vec[3]; mathVecSubtract(vec,ourPos,target,3); float dist = mathVecMagnitude(vec,3); distancia_a_origen(float distanceToAstVec[3],ourPos,target); float distanceToAst = mathVecMagnitude(distanceToAstVec,3); if(distanceToAst<0.22){ dodgeAsteroid(); //Function needs to be created--------------------------------------------------- } if(dist>0.1){ api.setVelocityTarget(vec); }else{ api.setPositionTarget(target); } }
true
330bfa1d85e9da574dbbe2c29c4c16e3302de104
C++
ryanmrichard/BPHash
/test/test_helpers.hpp
UTF-8
7,961
2.921875
3
[ "BSD-3-Clause" ]
permissive
/*! \file * \brief Helper functions for testing */ /* Copyright (c) 2016 Benjamin Pritchard <ben@bennyp.org> * This file is part of the BPHash project, which is released * under the BSD 3-clause license. See the LICENSE file for details */ #pragma once #include "bphash/Hasher.hpp" #include "bphash/types/All.hpp" #include <iostream> ////////////////////////////////// // This is the data we test with ////////////////////////////////// // integer values to test // This contains negative integers, and we purposely pass them // as unsigned sometimes. // Unsigned overflow is defined behavior static const std::vector<long> int_test{ 0, 1, 10, 100, 241, -1, -10, -100, -241}; static const std::vector<double> dbl_test{ 0, 1.0, 1.000001, 1.12e12, 1.12001e12, 1.12001e-12 -1.0, -1.000001, -1.12e12, -1.12001e12, -1.12001e-12}; static std::vector<const char *> str_test{"", " ", "\n", "String1", "String 1", "string1", "string 1", "STRING1", " String1", "String1!", "String1!\n"}; template<typename T> void test_single(const T & val, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { using namespace bphash; using namespace std; const char * type = typeid(T).name(); HashValue val_hash = make_hash(htype, val); // output the results cout << "Testing type: " << type << "\n"; cout << " normal: " << hash_to_string(val_hash) << "\n" << " trunc: " << hash_to_string(truncate_hash(val_hash, 8)) << "\n" << " conv: " << convert_hash<size_t>(val_hash) << "\n"; all_hashes.push_back(move(val_hash)); } template<typename To, typename From> void test_values(const std::vector<From> & vals, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { for(const auto & it : vals) test_single(static_cast<To>(it), htype, all_hashes); } template<typename To, typename From> void test_pointers(const std::vector<From> & vals, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { std::vector<To *> new_rptrs; std::vector<std::unique_ptr<To>> new_uptrs; std::vector<std::shared_ptr<To>> new_sptrs; for(const auto & it : vals) { To new_val = static_cast<To>(it); new_rptrs.push_back(new To(new_val)); new_uptrs.push_back(std::unique_ptr<To>(new To(new_val))); new_sptrs.push_back(std::shared_ptr<To>(new To(new_val))); } for(const auto & it : new_rptrs) test_single(it, htype, all_hashes); for(const auto & it : new_uptrs) test_single(it, htype, all_hashes); for(const auto & it : new_sptrs) test_single(it, htype, all_hashes); for(const auto & it : new_rptrs) delete it; } template<typename To, typename From, size_t N> void test_array_helper(const std::vector<From> & vec, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { std::array<To, N> arr_values; To plain_arr[N]; for(size_t i = 0; i < N; i++) { arr_values[i] = static_cast<To>(vec.at(i)); plain_arr[i] = static_cast<To>(vec.at(i)); } test_single(arr_values, htype, all_hashes); test_single(bphash::hash_pointer(plain_arr, N), htype, all_hashes); } #define HANDLE_TEST_ARRAY(N) \ case N: \ test_array_helper<To, From, N>(values, htype, all_hashes); \ break; template<typename To, typename From> void test_arrays(const std::vector<From> & values, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { // arrays have to be handled slightly differently for(size_t i = 0; i < values.size(); i++) { switch(i) { HANDLE_TEST_ARRAY( 1) HANDLE_TEST_ARRAY( 2) HANDLE_TEST_ARRAY( 3) HANDLE_TEST_ARRAY( 4) HANDLE_TEST_ARRAY( 5) HANDLE_TEST_ARRAY( 6) HANDLE_TEST_ARRAY( 7) HANDLE_TEST_ARRAY( 8) HANDLE_TEST_ARRAY( 9) HANDLE_TEST_ARRAY(10) HANDLE_TEST_ARRAY(11) HANDLE_TEST_ARRAY(12) HANDLE_TEST_ARRAY(13) HANDLE_TEST_ARRAY(14) HANDLE_TEST_ARRAY(15) HANDLE_TEST_ARRAY(16) HANDLE_TEST_ARRAY(17) HANDLE_TEST_ARRAY(18) HANDLE_TEST_ARRAY(19) HANDLE_TEST_ARRAY(20) default: break; } } } #undef HANDLE_TEST_ARRAY template<typename To, typename From> void test_containers(const std::vector<From> & values, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { // tests the entire vector, as well subvectors for(size_t i = 0; i <= values.size(); i++) { std::vector<To> new_vec{values.begin(), values.begin() + i}; std::list<To> new_list{values.begin(), values.begin() + i}; std::unordered_set<To> new_uset{values.begin(), values.begin() + i}; std::forward_list<To> new_flist{values.begin(), values.begin() + i}; std::set<To> new_set{values.begin(), values.begin() + i}; test_single(new_vec, htype, all_hashes); test_single(new_list, htype, all_hashes); test_single(new_uset, htype, all_hashes); test_single(new_flist, htype, all_hashes); test_single(new_set, htype, all_hashes); } } template<typename To, typename From> void test_fundamental(const std::vector<From> & values, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { test_values<To>(values, htype, all_hashes); test_pointers<To>(values, htype, all_hashes); test_arrays<To>(values, htype, all_hashes); test_containers<To>(values, htype, all_hashes); } template<typename To1, typename To2, typename From1, typename From2> void test_tuples_2(const std::vector<From1> & values1, const std::vector<From2> & values2, bphash::HashType htype, std::vector<bphash::HashValue> & all_hashes) { typedef std::tuple<To1, To2> To12; typedef std::pair<To1, To2> ToPair12; std::vector<To12> tup12; std::vector<ToPair12> pair12; for(size_t i = 0; i < values1.size(); i++) for(size_t j = 0; j < values2.size(); j++) { tup12.push_back(std::make_tuple<To1, To2>( static_cast<To1>(values1.at(i)), static_cast<To2>(values2.at(j)))); pair12.push_back(std::make_pair<To1, To2>( static_cast<To1>(values1.at(i)), static_cast<To2>(values2.at(j)))); } test_values <To12>(tup12, htype, all_hashes); test_pointers<To12>(tup12, htype, all_hashes); test_arrays <To12>(tup12, htype, all_hashes); test_values <ToPair12>(pair12, htype, all_hashes); test_pointers<ToPair12>(pair12, htype, all_hashes); test_arrays <ToPair12>(pair12, htype, all_hashes); // test some containers // tuple's don't have comparisons or std::hash for(size_t i = 0; i <= tup12.size(); i++) { std::vector<To12> new_vec{tup12.begin(), tup12.begin() + i}; std::list<To12> new_list{tup12.begin(), tup12.begin() + i}; test_single(new_vec, htype, all_hashes); test_single(new_list, htype, all_hashes); } for(size_t i = 0; i <= pair12.size(); i++) { std::vector<ToPair12> new_vec{pair12.begin(), pair12.begin() + i}; std::list<ToPair12> new_list{pair12.begin(), pair12.begin() + i}; test_single(new_vec, htype, all_hashes); test_single(new_list, htype, all_hashes); } }
true
873b41abd9a328f48d25cc1fdc0367ccc4a708bf
C++
jindalshivam09/cppcodes
/Aug13/LELEMON.cpp
UTF-8
2,058
3
3
[]
no_license
#include<iostream> #include<vector> #include<cstring> #include<utility> #include<algorithm> using namespace std; /////////////////////////////////////////////////////////////////////////////// typedef long long ll; #define MAX 100009 typedef struct { int frequency; int bottles; int total_capacity; int max_cap; int bottle_cap[MAX]; } data; //////////////////////////////////////////////////////////////////////////////// void reset (data *room , int n) { for(int i = 0 ; i < n ; i++) { room[i].frequency = 0; // memset(room[i].is_avail ,0 , sizeof(room[i].is_avail)); } } void input_path (data *room,int m) { int c; for(int i = 0 ; i < m ; i ++) { cin >> c; room[c].frequency++; } } void input_lemonade (data *room , int n) { int c,v; ll sum = 0; int maxm ; for(int i = 0 ; i < n ; i ++) { cin >> c; room[i].bottles = c; sum = 0; maxm = -1; for(int j = 0 ; j < c ; j ++) { cin >> v; sum += v; if(maxm < v) maxm = v; room[i].bottle_cap[j] = v;; } room[i].max_cap = maxm; room[i].total_capacity = sum; } } void sort_bottle_cap(data *room,int n) { for(int i = 0 ; i < n ; i++) sort(room[i].bottle_cap, room[i].bottle_cap + room[i].bottles); } ll total_drunk(data *room,int n) { ll sum = 0; for(int i = 0 ; i < n ; i++) { // cout << room[i].bottles << " " << room[i].frequency << endl; if(room[i].bottles <= room[i].frequency) sum += room[i].total_capacity; else { for(int j = room[i].bottles-1 ; j >= 0 && room[i].frequency && room[i].bottles ; j --) { // cout << room[i].is_avail[j] << endl; // cout << "else"; // cout << room[i].is_avail[j] << endl; // cout << j << " "; sum += room[i].bottle_cap[j] ; room[i].bottles--; room[i].frequency--; } // cout << endl; } // cout << sum << endl; } return sum; } data room[109]; int main () { int t; cin >> t; while(t--) { int n,m; cin >> n >> m; reset(room,n); input_path(room,m); input_lemonade(room,n); sort_bottle_cap(room,n); cout << total_drunk(room,n) << endl; } }
true
80009cf3bd30e59c0ee6a493b7b39bc3c0d0db09
C++
bishop986/CompileConstruction
/grammar/exam/source/scan.cc
UTF-8
11,443
2.65625
3
[ "MIT" ]
permissive
#include "include/scan.h" #include "include/global.h" #include "include/json.hpp" #include <fstream> using json = ::nlohmann::json; namespace dh{ scanner::scanner() { _fp = NULL; scanflag = false; rightflag = true; _tokens.clear(); line = 1; } scanner::scanner( const ::std::string& fp) { _fp = NULL; scanflag = false; rightflag = true; _tokens.clear(); line = 1; this->getTokenFromFile(fp); } void scanner::destroy() { if ( _fp != NULL) { ::std::fclose(NULL); _fp = NULL; } _tokens.clear(); } bool scanner::isScanned() { return scanflag; } bool scanner::isRight() { return rightflag; } scanner& scanner::operator=(const scanner& eq) { this->_tokens.assign( eq._tokens.begin(), eq._tokens.end()); this->_fp = eq._fp; this->scanflag = eq.scanflag; _it = _tokens.begin();; return *this; } void scanner::setBegin() { _it = _tokens.begin(); } token scanner::getToken() { if ( scanflag == false || _tokens.end() == _it) { return token( "", TYPE::NONES); } //::std::cout << "[SS] " << _it->getVal() << std::endl; token tmp(_it->getVal(),_it->getType()); ++_it; //::std::cout << "[DEBUG] " << tmp.getVal() << std::endl; return tmp; } bool scanner::ungetToken() { if ( scanflag == false || _tokens.begin() == _it) { return false; } --_it; return true; } /* * Transform Function: * S0 = START ; S1 = INNUMBER; S2 = DONE */ bool scanner::scan(::std::FILE *fp) { STATE state = STATE::START; char cur = 0; char assign = 0; ::std::string tmp = ""; if ( fp == NULL) { return false; } cur = ::std::fgetc(fp); while( cur == ' ' || cur == '\t') cur = ::std::fgetc(fp); while( cur != EOF) { if ( cur == '\n') { ++line; } switch(state) { case STATE::START: if ( cur == '\t' || cur == ' ' || cur == '\n' || cur == '\r') { state = STATE::START; } else if ( cur == '+') { state = STATE::INPLUS; tmp += cur; } else if ( cur == '-') { state = STATE::INMINUS; tmp += cur; } else if ( cur >= '0' && cur <= '9') { state = STATE::INFIDECI; tmp += cur; } else if ( ( cur >= 'a' && cur <= 'z') || ( cur >= 'A' && cur <= 'Z')) { state = STATE::INID; tmp += cur; } else if ( cur == ':') { state = STATE::INSP; tmp += cur; } else if ( cur == '=') { state = STATE::INEQ; tmp += cur; } else { state = STATE::DONE; assign = cur; continue; } break; case STATE::INID: if ( cur == '_') { state = STATE::INID; tmp += cur; } else if ( cur >= '0' && cur <= '9') { state = STATE::INID; tmp += cur; } else if ( ( cur >= 'a' && cur <= 'z') || ( cur >= 'A' && cur <= 'Z')) { state = STATE::INID; tmp += cur; } else { state = STATE::DONE; assign = cur; TYPE type_tmp = TYPE::IDENTIFIER; if ( tmp == "thread") { type_tmp = TYPE::THREAD; } else if ( tmp == "features") { type_tmp = TYPE::FEATURES; } else if ( tmp == "flows") { type_tmp = TYPE::FLOWS; } else if ( tmp == "properties") { type_tmp = TYPE::PROPERTIES; } else if ( tmp == "end") { type_tmp = TYPE::END; } else if ( tmp == "none") { type_tmp = TYPE::NONE; } else if ( tmp == "data") { type_tmp = TYPE::DATA; } else if ( tmp == "out") { type_tmp = TYPE::OUT; } else if ( tmp == "in") { type_tmp = TYPE::IN; } else if ( tmp == "port") { type_tmp = TYPE::PORT; } else if ( tmp == "event") { type_tmp = TYPE::EVENT; } else if ( tmp == "parameter") { type_tmp = TYPE::PARAMETER; } else if ( tmp == "flow") { type_tmp = TYPE::FLOW; } else if ( tmp == "source") { type_tmp = TYPE::SOURCE; } else if ( tmp == "path") { type_tmp = TYPE::PATH; } else if ( tmp == "constant") { type_tmp = TYPE::CONSTANT; } else if ( tmp == "access") { type_tmp = TYPE::ACCESS; } else if ( tmp == "sink") { type_tmp = TYPE::SINK; } else { type_tmp = TYPE::IDENTIFIER; } _tokens.push_back( token( tmp, type_tmp)); tmp.clear(); continue; } break; case STATE::INFIDECI: if ( cur <= '9' && cur >= '0') { state = STATE::INFIDECI; tmp += cur; } else if ( cur == '.') { state = STATE::INP; tmp += cur; } else { state = STATE::START; tmp += cur; ::std::cout << "[ERROR] Unexpected Token: \"" << tmp << "\" in line " << line << ::std::endl; tmp.clear(); rightflag = false; } break; case STATE::INSEDECI: if ( cur <= '9' && cur >= '0') { state = STATE::INSEDECI; tmp += cur; } else { state = STATE::DONE; assign = cur; _tokens.push_back( token( tmp, TYPE::DECIMAL)); tmp.clear(); continue; } break; case STATE::INPLUS: if ( cur <= '9' && cur >= '0') { state = STATE::INFIDECI; tmp += cur; } else if ( cur == '=') { state = STATE::INEQ; tmp += cur; } else { state = STATE::START; tmp += cur; ::std::cout << "[ERROR] Unexpected Token: \"" << tmp << "\" in line " << line << ::std::endl; tmp.clear(); rightflag = false; } break; case STATE::INEQ: if ( cur == '>') { state = STATE::START; tmp += cur; _tokens.push_back( token( tmp, TYPE::SYMBOL)); tmp.clear(); } else { state = STATE::START; tmp += cur; ::std::cout << "[ERROR] Unexpected Token: \"" << tmp << "\" in line " << line << ::std::endl; tmp.clear(); rightflag = false; } break; case STATE::INP: if ( cur >= '0' && cur <= '9') { state = STATE::INSEDECI; tmp += cur; } else { state = STATE::START; tmp += cur; ::std::cout << "[ERROR] Unexpected Token: \"" << tmp << "\" in line " << line << ::std::endl; tmp.clear(); rightflag = false; } break; case STATE::INMINUS: if ( cur == '>') { state = STATE::START; tmp += cur; _tokens.push_back( token( tmp, TYPE::SYMBOL)); tmp.clear(); } else if ( cur >= '0' && cur <= '9') { state = STATE::INFIDECI; tmp += cur; } else { state = STATE::START; tmp += cur; ::std::cout << "[ERROR] Unexpected Token: \"" << tmp << "\" in line " << line << ::std::endl; tmp.clear(); rightflag = false; } break; case STATE::INSP: if ( cur == ':') { state = STATE::START; tmp += cur; _tokens.push_back( token( tmp, TYPE::SYMBOL)); tmp.clear(); } else { state = STATE::DONE; assign = cur; _tokens.push_back( token( tmp, TYPE::SYMBOL)); tmp.clear(); continue; } break; case STATE::DONE: if ( assign == ' ' || assign == '\t' || assign == '\n' || assign == '\r') { state = STATE::START; } else if ( assign == ':') { state = STATE::START; continue; } else if (assign == '{' || assign == '}' || assign == ';') { state = STATE::START; ::std::string str = ""; str += assign; _tokens.push_back( token( str, TYPE::SYMBOL)); } else if ( assign <= '9' && assign >= '0') { state = STATE::START; continue; } else if ( ( assign >= 'a' && assign <= 'z') || ( assign >= 'A' && assign <= 'Z')) { state = STATE::START; continue; } else { state = STATE::START; ::std::cout << "[ERROR] Unexpected Token: \"" << assign << "\" in line " << line << ::std::endl; rightflag = false; } break; } cur = ::std::fgetc(fp); } _it = _tokens.begin(); scanflag = true;; return true; } void scanner::dump(const ::std::string& path) { json j; if ( !rightflag) { return; } ::std::ofstream outf(path.c_str()); ::std::cout << "[INFO] " << "Dump all Tokens to " << path << ::std::endl; ::std::cout << "[INFO] Token: Size: " << _tokens.size() << ::std::endl; int counter = 0; for(auto i = _tokens.begin(); i != _tokens.end(); ++i) { j[counter]["Token Val"] = i->getVal(); ::std::string type_str = ""; switch( i->getType()) { case THREAD: type_str = "THREAD"; break; case FEATURES: type_str = "FEATURES"; break; case FLOWS: type_str = "FLOWS"; break; case PROPERTIES: type_str = "PROPERTIES"; break; case END: type_str = "END"; break; case NONE: type_str = "NONE"; break; case NONES: type_str = "NONES"; break; case OUT: type_str = "OUT"; break; case DATA: type_str = "DATA"; break; case PORT: type_str = "PORT"; break; case EVENT: type_str = "EVENT"; break; case PARAMETER: type_str = "PARAMETER"; break; case FLOW: type_str = "FLOW"; break; case SOURCE: type_str = "SOURCE"; break; case PATH: type_str = "PATH"; break; case CONSTANT: type_str = "CONSTANT"; break; case ACCESS: type_str = "ACCESS"; break; case IDENTIFIER: type_str = "IDENTIFIER"; break; case DECIMAL: type_str = "DECIMAL"; break; case SYMBOL: type_str = "SYMBOL"; break; case SINK: type_str = "SINK"; break; case IN: type_str = "IN"; } j[counter++]["Token Type"] = type_str; } outf << ::std::setw(4) << j << std::endl; } void scanner::getTokenFromFile( const::std::string & fp) { ::std::ifstream inf(fp); if ( !inf) { ::std::cerr << "[ERROR] No such file" << ::std::endl; ::std::exit(1); } json j; inf >> j; _tokens.clear(); scanflag = false; for ( auto it = j.begin(); it != j.end(); ++it) { ::std::string tmp_str = (*it)["Token Val"]; ::std::string tmp_type = (*it)["Token Type"]; TYPE type; if ( tmp_type == "NONE") { type = TYPE::NONE; } else if ( tmp_type == "SYMBOL") { type = TYPE::SYMBOL; } else if ( tmp_type == "IDENTIFIER") { type = TYPE::IDENTIFIER; } else if ( tmp_type == "END") { type = TYPE::END; } else if ( tmp_type == "PROPERTIES") { type = TYPE::PROPERTIES; } else if ( tmp_type == "FLOW") { type = TYPE::FLOW; } else if ( tmp_type == "FLOWS") { type = TYPE::FLOWS; } else if ( tmp_type == "FEATURES") { type = TYPE::FEATURES; } else if ( tmp_type == "DATA") { type = TYPE::DATA; } else if ( tmp_type == "PORT") { type = TYPE::PORT; } else if ( tmp_type == "DECIMAL") { type = TYPE::DECIMAL; } else if ( tmp_type == "PATH") { type = TYPE::PATH; } else if ( tmp_type == "SINK") { type = TYPE::SINK; } else if ( tmp_type == "IN") { type = TYPE::IN; } else if ( tmp_type == "OUT") { type = TYPE::OUT; } else if ( tmp_type == "ACCESS") { type = TYPE::ACCESS; } else if ( tmp_type == "EVENT") { type = TYPE::EVENT; } else if ( tmp_type == "THREAD") { type = TYPE::THREAD; } else if ( tmp_type == "CONSTANT") { type = TYPE::CONSTANT; } else if ( tmp_type == "PARAMETER") { type = TYPE::PARAMETER; } else if ( tmp_type == "SOURCE") { type = TYPE::SOURCE; } _tokens.push_back( token(tmp_str, type)); } _it = _tokens.begin(); scanflag = true; } }
true
497a0ec9c43cc970edbf738162ac38d668fdfd51
C++
RhobanProject/Glue
/include/glue/Link.h
UTF-8
940
2.65625
3
[]
no_license
#ifndef _GLUE_LINK_H #define _GLUE_LINK_H #include "glue.h" #include "Tick.h" namespace Glue { class LinkBase : public Tick { public: int id; }; template<typename T> class Link : public LinkBase { public: Link(Node *from_, int from_index_, int from_subindex_, Node *to_, int to_index_, int to_subindex_) : from(from_), from_index(from_index_), from_subindex(from_subindex_), to(to_), to_index(to_index_), to_subindex(to_subindex_) { } void glue_tick(float elapsed) { T tmp = glue_getter<T>(from, from_index, from_subindex); glue_setter<T>(to, to_index, to_subindex, tmp); } Node *from; int from_index, from_subindex; Node *to; int to_index, to_subindex; }; } #endif
true
709351043a0491771ef1109cf72eb9f29036015a
C++
totemofwolf/redis-cerberus
/test/mock-server.cpp
UTF-8
1,788
2.515625
3
[ "MIT" ]
permissive
#include <functional> #include "mock-server.hpp" using namespace cerb; namespace { struct ServerManager { std::function<void(Server*)> const dtor; explicit ServerManager(std::function<void(Server*)> d) : dtor(d) {} ServerManager(ServerManager const&) = delete; ~ServerManager() { for (Server* s: allocated) { dtor(s); } } std::set<Server*> allocated; std::map<util::Address, Server*> addr_map; template <typename Constructor> Server* allocate(Constructor ctor) { Server* s = ctor(); this->allocated.insert(s); return s; } template <typename Constructor> Server* get(util::Address const& addr, Constructor ctor) { auto it = this->addr_map.find(addr); if (it != this->addr_map.end()) { return it->second; } return addr_map[addr] = allocate(ctor); } }; } static std::set<Server*> created; static std::set<Server*> closed; std::set<Server*> const& created_servers() { return ::created; } std::set<Server*> const& closed_servers() { return ::closed; } void clear_all_servers() { ::created.clear(); ::closed.clear(); } Server* Server::get_server(util::Address addr, Proxy*) { static ServerManager server_manager([](Server* s) { delete s; }); Server* s = server_manager.get(addr, []() { return new Server; }); s->addr = addr; ::created.insert(s); return s; } void Server::on_events(int) {} void Server::after_events(std::set<Connection*>&) {} std::string Server::str() const {return "";} void Server::close_conn() { ::closed.insert(this); }
true
00d8d7b115e192688a20862e84a67499c189dfce
C++
winshining/ngx_log_collection
/client/src/http_socket.cpp
UTF-8
10,233
2.65625
3
[ "BSD-2-Clause" ]
permissive
#include "http_socket.h" const int CHttpSocket::s_bufsize = 2048; CHttpSocket::CHttpSocket(const string& uuid, const string& host, const unsigned short port, const string& uri, const int loop, const int timeout) { Initialize(host, port, uri, loop, timeout); if (uuid.empty()) { Finalize(); cout << pthread_self() << ": empty uuid in construction" << endl; } else { m_uuid = uuid; m_inited = true; } } CHttpSocket::~CHttpSocket() { Finalize(); } size_t CHttpSocket::FormatRequestHeader(void) { m_req.clear(); m_req += "POST "; m_req += m_uri; m_req += " HTTP/1.1"; m_req += "\r\n"; m_req += "Host: "; m_req += m_host; m_req += "\r\n"; if (m_uuid.size() != 0) { m_req += "Client-UUID: "; m_req += m_uuid; m_req += "\r\n"; } m_req += "Accept: */*"; m_req += "\r\n"; m_req += "Connection: Keep-Alive"; m_req += "\r\n"; m_req += "Content-Type: application/x-www-form-urlencoded"; m_req += "\r\n"; m_req += "Content-Length: "; return (size_t) m_req.size(); } void CHttpSocket::StartWork() { int ret; if (!m_inited) { return; } FormatRequestHeader(); ret = pthread_create(&m_tid, NULL, CHttpSocket::DoWork, (void *)this); if (ret != 0) { cout << pthread_self() << ": create thread failed:" << strerror(errno) << endl; return; } m_hdrend = 0; m_pipeline = 0; cout << m_tid << " is running" << endl; } RespState CHttpSocket::CheckResponse(const string& buffer) { string::size_type pos = 0; string size; stringstream ss; RespState s = RESPONSE_START; if (buffer.empty()) { return (m_hdrend > 0) ? RESPONSE_START : RESPONSE_HEADER; } for ( ;; ) { if (m_hdrend > 0) { for ( ;; ) { /* Content-Length */ pos = buffer.find("Content-Length:", pos); if (pos == string::npos) { if (m_pipeline == 0) { m_hdrend = 0; pos = 0; break; } else { return RESPONSE_HEADER; } } else { m_pipeline++; if (m_pipeline > 2) { m_hdrend = 0; m_pipeline = 0; return RESPONSE_DONE; } } } for ( ;; ) { /* Transfer-Encoding */ pos = buffer.find("Transfer-Encoding:", pos); if (pos == string::npos) { if (m_pipeline == 0) { m_hdrend = 0; return RESPONSE_INVALID; } else { return RESPONSE_HEADER; } } else { m_pipeline++; if (m_pipeline > 2) { m_pipeline = 0; m_hdrend = 0; return RESPONSE_DONE; } } } } else { pos = buffer.find("\r\n\r\n", pos); if (pos != string::npos) { m_hdrend = (size_t) pos; s = RESPONSE_HEADER; } else { break; } } } return s; } void* CHttpSocket::DoWork(void *arg) { const string str = "content=This+is+a+test+string+in+the+log+collection+client" "+programm%2C+first+coded+on+2016.03.08+by+Xingyuan+Wang%2C" "+which+is+used+to+test+the+log+collection+server+module+in+" "nginx,+versions+1.2.6,+1.8.1+and+1.9.12+were+tested+on+2016" "-10-10-15.%0D%0AThe+following+blanks+is+intended+to+tested+" "the+urldecode+functionality+of+the+module: %0D%0A"; stringstream s; string size, req; ssize_t all, r = 0, delta_in = 0, delta_out = 0; int n, i, j; char buffer[s_bufsize]; struct epoll_event ev, events[10]; bool connected = false, done; pthread_t tid = pthread_self(); CHttpSocket* obj = (CHttpSocket*) arg; const string& reqh = obj->GetReqHeader(); s << str.size(); s >> size; req = reqh + size + "\r\n\r\n"; req += str; req += reqh + size + "\r\n\r\n"; req += str; req += reqh + size + "\r\n\r\n"; req += str; all = req.size(); signal(SIGPIPE, SIG_IGN); r = obj->SetNonBlockConnect(); if (r == -1 && errno != EINPROGRESS) { cout << "Set nonblock connect failed." << endl; return NULL; } const int& connfd = obj->GetConnectFd(); const int& epollfd = obj->GetEpollFd(); const int& timeout = obj->GetTimeout(); ev.events = EPOLLOUT | EPOLLET; ev.data.fd = connfd; n = epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &ev); if (n == -1) { cout << tid << ": Add the connect socket for write failed: " << strerror(errno) << endl; return NULL; } for (i = 0; i < obj->GetLoop(); i++) { done = false; for ( ;; ) { n = epoll_wait(epollfd, events, 10, timeout); if (n == -1) { if (errno != EINTR) { cout << tid << ": Epoll failed: " << strerror(errno) << endl; return NULL; } } else if (n > 0) { for (j = 0; j < n; j++) { /* only one fd, so we do not check it */ if (!connected) { if (!obj->CheckConnectError()) { cout << tid << ": Connect error happened." << endl; return NULL; } else { ev.events |= EPOLLIN; n = epoll_ctl(epollfd, EPOLL_CTL_MOD, connfd, &ev); if (n == -1 && errno != EINTR) { cout << tid << ": Add the connect socket for read failed: " << strerror(errno) << endl; return NULL; } connected = true; } } else { if (events[j].events & EPOLLOUT) { /* send */ while (delta_out < all) { r = send(connfd, req.c_str() + delta_out, req.size() - delta_out, 0); if (r == -1) { if (errno != EINTR && errno != EAGAIN) { cout << tid << ": Send error: " << strerror(errno) << endl; return NULL; } if (errno == EAGAIN) { delta_out = 0; break; } } else { if (delta_out >= all) { delta_out = 0; break; } delta_out += r; } } } if (events[j].events & EPOLLIN) { /* recv */ for ( ;; ) { r = recv(connfd, buffer + delta_in, s_bufsize - delta_in, 0); if (r == -1) { if (errno != EINTR && errno != EAGAIN) { cout << tid << ": Recv error: " << strerror(errno) << endl; return NULL; } else { break; } } else if (r == 0) { delta_in = 0; cout << tid << ": Peer closed the connection." << endl; if (!obj->ReInitialize(ev)) { return NULL; } connected = false; break; } else { delta_in += r; RespState s = obj->CheckResponse(string(buffer)); if (s == RESPONSE_DONE) { delta_in = 0; done = true; break; } } } } } } } else { if (done) { if (i == obj->GetLoop() - 1) { break; } delta_out = 0; while (delta_out < all) { r = send(connfd, req.c_str() + delta_out, req.size() - delta_out, 0); if (r == -1) { if (errno != EINTR && errno != EAGAIN) { cout << tid << ": Send error: " << strerror(errno) << endl; return NULL; } if (errno == EAGAIN) { continue; } } else { if (delta_out >= all) { delta_out = 0; break; } delta_out += r; } } break; } cout << tid << ": Epoll timeout." << endl; } } } return NULL; } void CHttpSocket::Initialize(const string& host, const unsigned short port, const string& uri, const int loop, const int timeout) { m_connfd = -1; m_inited = false; m_tid = 0; m_host = host.empty() ? "localhost" : host; stringstream s; s << port; s >> m_port; m_uri = uri.empty() ? "/" : uri; m_loop = (loop <= 0) ? 50 : loop; m_timeout = (timeout <= 0) ? 50 : timeout; m_epollfd = epoll_create(10); if (m_epollfd == -1) { Finalize(); } } bool CHttpSocket::ReInitialize(struct epoll_event& ev) { int r, n; pthread_t tid = pthread_self(); epoll_ctl(m_epollfd, EPOLL_CTL_DEL, m_connfd, NULL); close(m_connfd); m_connfd = -1; r = SetNonBlockConnect(); if (r == -1 && errno != EINPROGRESS) { cout << "Set nonblock connect failed." << endl; return false; } ev.events = EPOLLOUT | EPOLLET; ev.data.fd = m_connfd; n = epoll_ctl(m_epollfd, EPOLL_CTL_ADD, m_connfd, &ev); if (n == -1) { cout << tid << ": Add the connect socket for write failed: " << strerror(errno) << endl; return false; } return true; } void CHttpSocket::Finalize(void) { if (m_tid > 0) { pthread_join(m_tid, NULL); cout << m_tid << " joined" << endl; } if (m_epollfd >= 0) { if (m_connfd >= 0) { epoll_ctl(m_epollfd, EPOLL_CTL_DEL, m_connfd, NULL); } close(m_epollfd); m_epollfd = -1; } if (m_connfd >= 0) { close(m_connfd); m_connfd = -1; } m_inited = false; m_loop = 0; } bool CHttpSocket::ResolveServer(struct sockaddr *serv, size_t *servlen) { int r; struct addrinfo hints, *res, *ressave; bzero(&hints, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_family = AF_INET; r = getaddrinfo(m_host.c_str(), m_port.c_str(), &hints, &res); if (r != 0) { cout << pthread_self() << ": getaddrinfo error: " << gai_strerror(r) << endl; return false; } ressave = res; do { m_connfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (m_connfd > 0) { *servlen = res->ai_addrlen; bcopy(res->ai_addr, serv, *servlen); break; } } while((res = res->ai_next) != NULL); freeaddrinfo(ressave); if (res == NULL) { /* found nothing */ cout << pthread_self() << ": " << m_host << " " << m_port << " not found" << endl; return false; } return true; } int CHttpSocket::SetNonBlockConnect(void) { struct sockaddr srv; size_t addrlen; int r = -1; if (ResolveServer(&srv, &addrlen)) { int val = fcntl(m_connfd, F_GETFL, 0); if (fcntl(m_connfd, F_SETFL, val | O_NONBLOCK) != -1) { r = connect(m_connfd, &srv, addrlen); } } return r; } bool CHttpSocket::CheckConnectError(void) { int s = 1; socklen_t len = sizeof(s); if (getsockopt(m_connfd, SOL_SOCKET, SO_ERROR, (void *) &s, &len) == -1) { return false; } else { if (s != 0) { cout << pthread_self() << ": getsockopt for SO_ERROR failed." << endl; return false; } } return true; } const int& CHttpSocket::GetConnectFd(void) const { return m_connfd; } const int& CHttpSocket::GetEpollFd(void) const { return m_epollfd; } const string& CHttpSocket::GetReqHeader(void) const { return m_req; } const int& CHttpSocket::GetTimeout(void) const { return m_timeout; } const int& CHttpSocket::GetLoop(void) const { return m_loop; }
true
bc1e495a15065581acd91e341e8445ef7519f639
C++
AnnaKramarenko/PROC
/In_Figure_3D.cpp
WINDOWS-1251
1,545
3.046875
3
[]
no_license
#include "In_Figure_3D.h" #include "In_Sphere.h" #include "In_Parallelepiped.h" #include "In_Tetrahedron.h" Figure_3D* In_Figure_3D(ifstream& ifst) { Figure_3D *F = new Figure_3D; // int K; // ifst >> K; // if (K == 1) { // K == 1, F->K = SPHERE; // , F->Obj = In_Sphere(ifst); // } else if (K == 2) { // K == 2, F->K = PARALLELEPIPED; // , F->Obj = In_Parallelepiped(ifst); // e } else if (K == 3) { // K == 3, F->K = TETRAHEDRON; // , F->Obj = In_Tetrahedron(ifst); // } else { return 0; } ifst >> F->Density; // ifst >> F->Temperature; // / return F; }
true
4350cb26a6544f8841836d1651d22be10d64becf
C++
ashishbajaj91/BitPlanes
/finalcode/getParameters.h
UTF-8
1,589
2.65625
3
[]
no_license
#ifndef GETPARAMETERS_IS_INCLUDED #define GETPARAMETERS_IS_INCLUDED #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <math.h> void getWeights(int nrows, int ncols, double wts[8]) { wts[0] = 1.0; wts[1] = 1.0; wts[2] = 1.0204; wts[3] = 0.03125; wts[4] = 1.0313; wts[5] = 0.0204; wts[6] = 0.00055516; wts[7] = 0.00055516; double s = sqrt(double(nrows*ncols)) / 128.0; wts[2] = pow(wts[2],(1/s)); wts[3] /= s; wts[4] = pow(wts[4], (1 / s)); wts[5] /= s; wts[6] /= (s*s); wts[7] /= (s*s); } double getEpsilon() { return double(1e-4); } double getLambda() { return double(1e-6); } void getKeep(std::string method, int keep[8]) { for (int i = 0; i < 8; i++) keep[i] = 0; if (method == "translation") { keep[0] = 1; keep[1] = 1; } else if (method == "rigid") { keep[0] = 1; keep[1] = 1; keep[5] = 1; } else if (method == "similarity") { keep[0] = 1; keep[1] = 1; keep[2] = 1; keep[5] = 1; } else if (method == "affine") { keep[0] = 1; keep[1] = 1; keep[2] = 1; keep[3] = 1; keep[4] = 1; keep[5] = 1; } else if (method == "rotation") { keep[5] = 1; keep[6] = 1; keep[7] = 1; } else if (method == "projective") { keep[0] = 1; keep[1] = 1; keep[2] = 1; keep[3] = 1; keep[4] = 1; keep[5] = 1; keep[6] = 1; keep[7] = 1; } else { std::cout << "Invalid Method" << std::endl; } } int getNoOfParameters(int keep[]) { int nParameters = 0; for (int i = 0; i < 8; i++) if (keep[i]) nParameters++; return nParameters; } #endif
true
139492aef4fc214411b22d24c4a1965a3191cd77
C++
CS-Pacific-University/06polymorphism-jcorey1313
/06Polymorphism_Classes/Source.cpp
UTF-8
4,212
3.046875
3
[]
no_license
//**************************************************************************** // File name: Source.cpp // Author: James Corey // Date: 05/03/2021 // Class: CS250 // Assignment: Polymorphism // Purpose: Using polymorphism to create a simulation of a mail service // Hours: 9 //**************************************************************************** #include "Letter.h" #include "Postcard.h" #include "Overnight.h" #include <iomanip> #include <fstream> void printMenu (); int main () { const int PRINT = 1; const int INSURANCE = 2; const int RUSH = 3; const int DELIVER = 4; const int QUIT = 5; const int MAX_PARCELS = 25; const int TID_ADJUSTMENT = 1; const int DECIMAL_SPOTS = 2; const char LETTER = 'L'; const char OVERNIGHT_PACKAGE = 'O'; const char POSTCARD = 'P'; const string INPUT_FILE = "Parcel.txt"; ifstream inputFile; char whichParcel; Parcel* apcParcels [MAX_PARCELS] = { nullptr }; int numParcels = 0; int tID, menuChoice; double insuranceCost, rushCost; cout << "Mail Simulator!" << endl; inputFile.open (INPUT_FILE); if (!inputFile.is_open ()) { cout << "Could not open file."; return EXIT_FAILURE; } else { while (inputFile >> whichParcel) { if (whichParcel == LETTER) { apcParcels [numParcels] = new Letter; } else if (whichParcel == OVERNIGHT_PACKAGE) { apcParcels [numParcels] = new Overnight; } else if (whichParcel == POSTCARD) { apcParcels [numParcels] = new Postcard; } apcParcels [numParcels]->read (inputFile); apcParcels [numParcels]->setCost (); numParcels++; } do { printMenu (); do { cout << "Choice> "; cin >> menuChoice; cout << endl; } while (menuChoice != PRINT && menuChoice != INSURANCE && menuChoice != RUSH && menuChoice != DELIVER && menuChoice != QUIT); if (menuChoice == PRINT) { for (int i = 0; i < numParcels; i++) { if (apcParcels [i] != nullptr) { apcParcels [i]->print (cout); cout << endl; } } } else if (menuChoice == INSURANCE) { cout << "TID> "; cin >> tID; if (tID > 0 && tID <= numParcels) { insuranceCost = apcParcels [tID - TID_ADJUSTMENT]->addInsurance (); cout << "Added Insurance for $" << fixed << setprecision (DECIMAL_SPOTS) << insuranceCost << endl; apcParcels [tID - TID_ADJUSTMENT]->print (cout); cout << endl; } } else if (menuChoice == RUSH) { cout << "TID> "; cin >> tID; if (tID > 0 && tID <= numParcels) { rushCost = apcParcels [tID - TID_ADJUSTMENT]->addRush (); cout << "Added Rush for $ " << fixed << setprecision (DECIMAL_SPOTS) << rushCost << endl; apcParcels [tID - TID_ADJUSTMENT]->print (cout); cout << endl; } } else if (menuChoice == DELIVER) { cout << "TID> "; cin >> tID; if (tID > 0 && tID <= numParcels) { cout << "Delivered!" << endl; cout << apcParcels [tID - TID_ADJUSTMENT]->getDeliveryDay () << " Day, $" << fixed << setprecision (DECIMAL_SPOTS) << apcParcels [tID - TID_ADJUSTMENT]->getCost () << endl; apcParcels [tID - TID_ADJUSTMENT]->print (cout); delete apcParcels [tID - TID_ADJUSTMENT]; apcParcels [tID - TID_ADJUSTMENT] = nullptr; cout << endl; } } } while (menuChoice != QUIT); for (int i = 0; i < numParcels; i++) { delete apcParcels [i]; } inputFile.close(); return EXIT_SUCCESS; } } void printMenu() { const string OPTION_1_PRINT = "1. Print All"; const string OPTION_2_INSURANCE = "2. Add Insurance"; const string OPTION_3_RUSH = "3. Add Rush"; const string OPTION_4_DELIVER = "4. Deliver"; const string OPTION_5_QUIT = "5. Quit"; cout << endl << OPTION_1_PRINT << endl << OPTION_2_INSURANCE << endl << OPTION_3_RUSH << endl << OPTION_4_DELIVER << endl << OPTION_5_QUIT << endl << endl; }
true
5806e55c0e05a1a0b44e6fa90a8e9d228c249033
C++
opendarkeden/server
/src/Core/GCPartyError.h
UHC
3,014
2.703125
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Filename : GCPartyError.h // Written By : excel96 // Description : ////////////////////////////////////////////////////////////////////////////// #ifndef __GC_PARTY_ERROR_H__ #define __GC_PARTY_ERROR_H__ #include "Packet.h" #include "PacketFactory.h" ////////////////////////////////////////////////////////////////////////////// // Ƽ ڵ ////////////////////////////////////////////////////////////////////////////// enum { // Ƽ ԽŰų Żų ʴ´. GC_PARTY_ERROR_TARGET_NOT_EXIST = 0, // Ƽ ԽŰų Żų ٸ ̴. GC_PARTY_ERROR_RACE_DIFFER, // 밡 ƴϴ. GC_PARTY_ERROR_NOT_SAFE, // 볪 ¿ . GC_PARTY_ERROR_NOT_NORMAL_FORM, // ʴ ̸鼭 ʴ븦 Ϸ Ѵ. GC_TRADE_ERROR_ALREADY_INVITING, // ʴ ƴϸ鼭 ʴ뿡 Դ. GC_PARTY_ERROR_NOT_INVITING, // Ƽ ߹ ִ . GC_PARTY_ERROR_NO_AUTHORITY, // GC_TRADE_ERROR_UNKNOWN, GC_PARTY_ERROR_MAX }; ////////////////////////////////////////////////////////////////////////////// // class GCPartyError; ////////////////////////////////////////////////////////////////////////////// class GCPartyError : public Packet { public: GCPartyError() {}; ~GCPartyError() {}; void read(SocketInputStream & iStream) ; void write(SocketOutputStream & oStream) const ; void execute(Player* pPlayer) ; PacketID_t getPacketID() const { return PACKET_GC_PARTY_ERROR; } PacketSize_t getPacketSize() const { return szBYTE + szObjectID; } string getPacketName() const { return "GCPartyError"; } string toString() const ; public: BYTE getCode() const { return m_Code; } void setCode(BYTE code) { m_Code = code; } ObjectID_t getTargetObjectID(void) const { return m_TargetObjectID; } void setTargetObjectID(ObjectID_t id) { m_TargetObjectID = id; } private : ObjectID_t m_TargetObjectID; BYTE m_Code; // ڵ }; ////////////////////////////////////////////////////////////////////////////// // class GCPartyErrorFactory; ////////////////////////////////////////////////////////////////////////////// class GCPartyErrorFactory : public PacketFactory { public: Packet* createPacket() { return new GCPartyError(); } string getPacketName() const { return "GCPartyError"; } PacketID_t getPacketID() const { return Packet::PACKET_GC_PARTY_ERROR; } PacketSize_t getPacketMaxSize() const { return szBYTE + szObjectID; } }; ////////////////////////////////////////////////////////////////////////////// // class GCPartyErrorHandler; ////////////////////////////////////////////////////////////////////////////// class GCPartyErrorHandler { public: static void execute(GCPartyError* pPacket, Player* pPlayer) ; }; #endif
true
7f5c91e95b9c2cd97ae48d086772c2e2ee0cbcea
C++
tectronics/graphics-assignments
/p1/glwidget2.cpp
UTF-8
34,886
2.78125
3
[]
no_license
#include "glwidget2.h" #include <GL/glext.h> #include <GL/glx.h> #include <QtGui> #include <iostream> #include <algorithm> // std::min PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays2; PFNGLGENVERTEXARRAYSPROC glGenVertexArrays2; PFNGLBINDVERTEXARRAYPROC glBindVertexArray2; GLWidget2::GLWidget2(QWidget *parent) : QGLWidget(parent), level(5) { } GLWidget2::~GLWidget2() { //delete the vertex array and vertex buffer destroyDraw(); } void GLWidget2::initializeGL() { //load opengl functions that are not in QGLFunctions //on mac and linux use glXGetProcAddress //on windows use wglGetProcAddress and don't cast to const GLubyte* initializeDraw(); draw(); } void GLWidget2::initializeDraw(){ glDeleteVertexArrays2 = (PFNGLDELETEVERTEXARRAYSPROC)glXGetProcAddress((GLubyte*)"glDeleteVertexArrays"); glGenVertexArrays2 = (PFNGLGENVERTEXARRAYSPROC)glXGetProcAddress((GLubyte*)"glGenVertexArrays"); glBindVertexArray2 = (PFNGLBINDVERTEXARRAYPROC)glXGetProcAddress((GLubyte*)"glBindVertexArray"); //load opengl functions initializeGLFunctions(); //set the clear color to black glClearColor(0,0,0,1); //enable depth testing glEnable(GL_DEPTH_TEST); //load and initialize shaders //load the shaders, link the shader, and set the shader to be active shader = new QGLShaderProgram(); shader->addShaderFromSourceFile(QGLShader::Vertex, ":/basic.vert"); shader->addShaderFromSourceFile(QGLShader::Fragment, ":/basic.frag"); shader->link(); shader->bind(); } void GLWidget2::destroyDraw(){ //delete the vertex array and vertex buffer GLuint loc = glGetAttribLocation(shader->programId(), "position"); glDisableVertexAttribArray(loc); loc = glGetAttribLocation(shader->programId(), "color"); glDisableVertexAttribArray(loc); glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(1, &vertex_buffer); glBindVertexArray2(0); glDeleteVertexArrays2(1, &vertex_array); //delete the shaders shader->release(); shader->removeAllShaders(); delete shader; } void GLWidget2::paintGL() { //clear the color and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //draw the 3 points as a triangle or line loop glBindVertexArray2(vertex_array); glDrawArrays(GL_LINE_STRIP, 0, qlst1.size()/3 ); glBindVertexArray2(vertex_array2); glDrawArrays(GL_LINE_STRIP, 0, qlst2.size()/3 ); glBindVertexArray2(vertex_array3); glDrawArrays(GL_LINE_STRIP, 0, qlst3.size()/3 ); glBindVertexArray2(vertex_array4); glDrawArrays(GL_LINE_STRIP, 0, qlst4.size()/3 ); glBindVertexArray2(vertex_array5); glDrawArrays(GL_LINE_STRIP, 0, qlst5.size()/3 ); glBindVertexArray2(vertex_array6); glDrawArrays(GL_LINE_STRIP, 0, qlst6.size()/3 ); glBindVertexArray2(vertex_array7); glDrawArrays(GL_LINE_STRIP, 0, qlst7.size()/3 ); glBindVertexArray2(vertex_array42); glDrawArrays(GL_LINE_STRIP, 0, qlst42.size()/3 ); glBindVertexArray2(vertex_array52); glDrawArrays(GL_LINE_STRIP, 0, qlst52.size()/3 ); glBindVertexArray2(vertex_array43); glDrawArrays(GL_LINE_STRIP, 0, qlst43.size()/3 ); glBindVertexArray2(vertex_array44); glDrawArrays(GL_LINE_STRIP, 0, qlst44.size()/3 ); glBindVertexArray2(vertex_array45); glDrawArrays(GL_LINE_STRIP, 0, qlst45.size()/3 ); glBindVertexArray2(vertex_array53); glDrawArrays(GL_LINE_STRIP, 0, qlst53.size()/3 ); glBindVertexArray2(vertex_array54); glDrawArrays(GL_LINE_STRIP, 0, qlst54.size()/3 ); glBindVertexArray2(vertex_array55); glDrawArrays(GL_LINE_STRIP, 0, qlst55.size()/3 ); } void GLWidget2::resizeGL(int w, int h) { //set the viewing rectangle to be the entire window glViewport(0,0,w,h); } QSize GLWidget2::minimumSizeHint() const { return QSize(50, 50); } QSize GLWidget2::sizeHint() const { return QSize(500, 500); } void GLWidget2::draw() { qlst1.clear(); qcol1.clear(); qlst2.clear(); qcol2.clear(); qlst3.clear(); qcol3.clear(); qlst4.clear(); qcol4.clear(); qlst5.clear(); qcol5.clear(); qlst6.clear(); qcol6.clear(); qlst7.clear(); qcol7.clear(); qlst42.clear(); qcol42.clear(); qlst43.clear(); qcol43.clear(); qlst44.clear(); qcol44.clear(); qlst45.clear(); qcol45.clear(); qlst52.clear(); qcol52.clear(); qlst53.clear(); qcol53.clear(); qlst54.clear(); qcol54.clear(); qlst55.clear(); qcol55.clear(); for(float i=0.0;i<=1.2;i+=0.1) { qlst1.append(0.01); qlst1.append(i); qlst1.append(0.0); } for(float i=0.0;i<=1.2;i+=0.1) { qlst2.append(1.99); qlst2.append(i); qlst2.append(0.0); } //U qlst3.append(0.01); qlst3.append(0.0); qlst3.append(0.0); qlst3.append(0.01); qlst3.append(2.0); qlst3.append(0.0); qlst3.append(1.99); qlst3.append(2.0); qlst3.append(0.0); qlst3.append(1.99); qlst3.append(0.0); qlst3.append(0.0); //O qlst4.append(0.25); qlst4.append(1.15); qlst4.append(0.0); qlst4.append(0.25); qlst4.append(1.65); qlst4.append(0.0); qlst4.append(0.75); qlst4.append(1.65); qlst4.append(0.0); qlst4.append(0.75); qlst4.append(1.15); qlst4.append(0.0); qlst4.append(0.25); qlst4.append(1.15); qlst4.append(0.0); //||| qlst43.append(0.35); qlst43.append(1.53); qlst43.append(0.0); qlst43.append(0.30); qlst43.append(1.65); qlst43.append(0.0); qlst43.append(0.35); qlst43.append(1.75); qlst43.append(0.0); qlst44.append(0.45); qlst44.append(1.55); qlst44.append(0.0); qlst44.append(0.40); qlst44.append(1.70); qlst44.append(0.0); qlst44.append(0.45); qlst44.append(1.85); qlst44.append(0.0); qlst45.append(0.55); qlst45.append(1.58); qlst45.append(0.0); qlst45.append(0.60); qlst45.append(1.70); qlst45.append(0.0); qlst45.append(0.55); qlst45.append(1.83); qlst45.append(0.0); //||| qlst53.append(1.65); qlst53.append(1.53); qlst53.append(0.0); qlst53.append(1.70); qlst53.append(1.65); qlst53.append(0.0); qlst53.append(1.65); qlst53.append(1.75); qlst53.append(0.0); qlst54.append(1.55); qlst54.append(1.55); qlst54.append(0.0); qlst54.append(1.60); qlst54.append(1.70); qlst54.append(0.0); qlst54.append(1.55); qlst54.append(1.85); qlst54.append(0.0); qlst55.append(1.45); qlst55.append(1.58); qlst55.append(0.0); qlst55.append(1.40); qlst55.append(1.70); qlst55.append(0.0); qlst55.append(1.45); qlst55.append(1.83); qlst55.append(0.0); //O qlst5.append(1.25); qlst5.append(1.15); qlst5.append(0.0); qlst5.append(1.25); qlst5.append(1.65); qlst5.append(0.0); qlst5.append(1.75); qlst5.append(1.65); qlst5.append(0.0); qlst5.append(1.75); qlst5.append(1.15); qlst5.append(0.0); qlst5.append(1.25); qlst5.append(1.15); qlst5.append(0.0); //(___) qlst6.append(0.25); qlst6.append(0.5); qlst6.append(0.0); qlst6.append(0.25); qlst6.append(1.0); qlst6.append(0.0); qlst6.append(1.75); qlst6.append(1.0); qlst6.append(0.0); qlst6.append(1.75); qlst6.append(0.5); qlst6.append(0.0); qlst6.append(0.25); qlst6.append(0.5); qlst6.append(0.0); //. qlst42.append(0.48); qlst42.append(1.38); qlst42.append(0.0); qlst42.append(0.48); qlst42.append(1.42); qlst42.append(0.0); qlst42.append(0.52); qlst42.append(1.42); qlst42.append(0.0); qlst42.append(0.52); qlst42.append(1.38); qlst42.append(0.0); qlst42.append(0.48); qlst42.append(1.38); qlst42.append(0.0); //. qlst52.append(1.48); qlst52.append(1.38); qlst52.append(0.0); qlst52.append(1.48); qlst52.append(1.42); qlst52.append(0.0); qlst52.append(1.52); qlst52.append(1.42); qlst52.append(0.0); qlst52.append(1.52); qlst52.append(1.38); qlst52.append(0.0); qlst52.append(1.48); qlst52.append(1.38); qlst52.append(0.0); //--- /*for(float i=0.20;i<1.81;i+=0.1){ qlst7.append(i); qlst7.append(0.75); qlst7.append(0.0); }*/ qlst7.append(0.20); qlst7.append(0.75); qlst7.append(0.0); qlst7.append(0.30); qlst7.append(0.85); qlst7.append(0.0); qlst7.append(1.00); qlst7.append(0.75); qlst7.append(0.0); qlst7.append(1.70); qlst7.append(0.85); qlst7.append(0.0); qlst7.append(1.80); qlst7.append(0.75); qlst7.append(0.0); int i = abs(level-5); while(i-- > 0) { makeCurve(qlst1); makeCurve(qlst2); makeCurve(qlst3); makeCurve(qlst4); makeCurve(qlst5); makeCurve(qlst6); makeCurve(qlst7); makeCurve(qlst42); makeCurve(qlst52); makeCurve(qlst43); makeCurve(qlst44); makeCurve(qlst45); makeCurve(qlst53); makeCurve(qlst54); makeCurve(qlst55); } for (int i=0; i<qlst1.size(); i++) { qcol1.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array); //set the vertex array to be the active one glBindVertexArray2(vertex_array); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst1.size() + sizeof(GLfloat)*qcol1.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst1.size(), &(qlst1[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst1.size(), sizeof(GLfloat)*qcol1.size(), &(qcol1[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable GLuint loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst1.size()) ); for (int i=0; i<qlst2.size(); i++) { qcol2.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array2); //set the vertex array to be the active one glBindVertexArray2(vertex_array2); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer2); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer2); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst2.size() + sizeof(GLfloat)*qcol2.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst2.size(), &(qlst2[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst2.size(), sizeof(GLfloat)*qcol2.size(), &(qcol2[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst2.size()) ); for (int i=0; i<qlst3.size(); i++) { qcol3.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array3); //set the vertex array to be the active one glBindVertexArray2(vertex_array3); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer3); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer3); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst3.size() + sizeof(GLfloat)*qcol3.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst3.size(), &(qlst3[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst3.size(), sizeof(GLfloat)*qcol3.size(), &(qcol3[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst3.size()) ); for (int i=0; i<qlst4.size(); i++) { qcol4.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array4); //set the vertex array to be the active one glBindVertexArray2(vertex_array4); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer4); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer4); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst4.size() + sizeof(GLfloat)*qcol4.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst4.size(), &(qlst4[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst4.size(), sizeof(GLfloat)*qcol4.size(), &(qcol4[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst4.size()) ); for (int i=0; i<qlst5.size(); i++) { qcol5.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array5); //set the vertex array to be the active one glBindVertexArray2(vertex_array5); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer5); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer5); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst5.size() + sizeof(GLfloat)*qcol5.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst5.size(), &(qlst5[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst5.size(), sizeof(GLfloat)*qcol5.size(), &(qcol5[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst5.size()) ); for (int i=0; i<qlst6.size()/3; i++) { qcol6.append(1); qcol6.append(1); qcol6.append(0); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array6); //set the vertex array to be the active one glBindVertexArray2(vertex_array6); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer6); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer6); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst6.size() + sizeof(GLfloat)*qcol6.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst6.size(), &(qlst6[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst6.size(), sizeof(GLfloat)*qcol6.size(), &(qcol6[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst6.size()) ); for (int i=0; i<qlst7.size()/3; i++) { qcol7.append(1); qcol7.append(1); qcol7.append(0); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array7); //set the vertex array to be the active one glBindVertexArray2(vertex_array7); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer7); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer7); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst7.size() + sizeof(GLfloat)*qcol7.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst7.size(), &(qlst7[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst7.size(), sizeof(GLfloat)*qcol7.size(), &(qcol7[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst7.size()) ); for (int i=0; i<qlst42.size(); i++) { qcol42.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array42); //set the vertex array to be the active one glBindVertexArray2(vertex_array42); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer42); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer42); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst42.size() + sizeof(GLfloat)*qcol42.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst42.size(), &(qlst42[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst42.size(), sizeof(GLfloat)*qcol42.size(), &(qcol42[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst42.size()) ); for (int i=0; i<qlst52.size(); i++) { qcol52.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array52); //set the vertex array to be the active one glBindVertexArray2(vertex_array52); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer52); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer52); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst52.size() + sizeof(GLfloat)*qcol52.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst52.size(), &(qlst52[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst52.size(), sizeof(GLfloat)*qcol52.size(), &(qcol52[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst52.size()) ); for (int i=0; i<qlst43.size(); i++) { qcol43.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array43); //set the vertex array to be the active one glBindVertexArray2(vertex_array43); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer43); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer43); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst43.size() + sizeof(GLfloat)*qcol43.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst43.size(), &(qlst43[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst43.size(), sizeof(GLfloat)*qcol43.size(), &(qcol43[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst43.size()) ); for (int i=0; i<qlst53.size(); i++) { qcol53.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array53); //set the vertex array to be the active one glBindVertexArray2(vertex_array53); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer53); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer53); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst53.size() + sizeof(GLfloat)*qcol53.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst53.size(), &(qlst53[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst53.size(), sizeof(GLfloat)*qcol53.size(), &(qcol53[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst53.size()) ); for (int i=0; i<qlst44.size(); i++) { qcol44.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array44); //set the vertex array to be the active one glBindVertexArray2(vertex_array44); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer44); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer44); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst44.size() + sizeof(GLfloat)*qcol44.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst44.size(), &(qlst44[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst44.size(), sizeof(GLfloat)*qcol44.size(), &(qcol44[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst44.size()) ); for (int i=0; i<qlst45.size(); i++) { qcol45.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array45); //set the vertex array to be the active one glBindVertexArray2(vertex_array45); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer45); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer45); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst45.size() + sizeof(GLfloat)*qcol45.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst45.size(), &(qlst45[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst45.size(), sizeof(GLfloat)*qcol45.size(), &(qcol45[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst45.size()) ); for (int i=0; i<qlst43.size(); i++) { qcol43.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array43); //set the vertex array to be the active one glBindVertexArray2(vertex_array43); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer43); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer43); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst43.size() + sizeof(GLfloat)*qcol43.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst43.size(), &(qlst43[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst43.size(), sizeof(GLfloat)*qcol43.size(), &(qcol43[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst43.size()) ); for (int i=0; i<qlst54.size(); i++) { qcol54.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array54); //set the vertex array to be the active one glBindVertexArray2(vertex_array54); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer54); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer54); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst54.size() + sizeof(GLfloat)*qcol54.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst54.size(), &(qlst54[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst54.size(), sizeof(GLfloat)*qcol54.size(), &(qcol44[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst44.size()) ); for (int i=0; i<qlst55.size(); i++) { qcol55.append(1); } //get a unique id for the vertex array glGenVertexArrays2(1, &vertex_array55); //set the vertex array to be the active one glBindVertexArray2(vertex_array55); //get a unique id for the vertex buffer glGenBuffers(1, &vertex_buffer55); //set the vertex buffer to be active glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer55); //specify the size and type of the vertex buffer //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) + sizeof(colors), NULL, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst55.size() + sizeof(GLfloat)*qcol55.size(), NULL, GL_STATIC_DRAW); //load the vertex and color data into the vertex buffer (vertices in the first half, colors in the second half) glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(GLfloat)*qlst55.size(), &(qlst55[0]) ); glBufferSubData(GL_ARRAY_BUFFER, sizeof(GLfloat)*qlst55.size(), sizeof(GLfloat)*qcol55.size(), &(qcol55[0]) ); //set the size of the vertex (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "position"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, 0); //set the size of the color (3 component) and connect it to the correct shader variable loc = glGetAttribLocation(shader->programId(), "color"); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(GLfloat)*qlst55.size()) ); } void GLWidget2::increase() { level++; level%=9; makeCurrent(); draw(); updateGL(); } void GLWidget2::makeCurve(QVector<GLfloat> &old_qlst){ QVector<GLfloat> &new_qlst = *(new QVector<GLfloat>); for(int i=1;i<old_qlst.size()/3;i++){ GLfloat point1X = 3.0/4.0*old_qlst[i*3-3]+1.0/4.0*old_qlst[i*3+0]; GLfloat point2X = 1.0/4.0*old_qlst[i*3-3]+3.0/4.0*old_qlst[i*3+0]; GLfloat point1Y = 3.0/4.0*old_qlst[i*3-2]+1.0/4.0*old_qlst[i*3+1]; GLfloat point2Y = 1.0/4.0*old_qlst[i*3-2]+3.0/4.0*old_qlst[i*3+1]; new_qlst.append(point1X); new_qlst.append(point1Y); new_qlst.append(0); new_qlst.append(point2X); new_qlst.append(point2Y); new_qlst.append(0); } if((old_qlst[0]==old_qlst[old_qlst.size()-3]) &&(old_qlst[1]==old_qlst[old_qlst.size()-2])){ new_qlst.append(new_qlst[0]); new_qlst.append(new_qlst[1]); new_qlst.append(0); } new_qlst.swap(old_qlst); delete &new_qlst; }
true
8bc3465c69dba126bd21608437b2815de6f36792
C++
chulchultrain/FactoryHead
/EntryData/EntryData.cpp
UTF-8
843
2.953125
3
[]
no_license
#include <EntryData/EntryData.h> EntryData::EntryData(string x1, string x2, vector<string> &x3, string x4, string x5, vector<int> &x6) { ID = x1; DexID = x2; moveID = x3; item = x4; nature = x5; EV = x6; } EntryData::EntryData() { ID = ""; DexID = "001"; moveID.resize(4,""); nature = ""; item = ""; EV.resize(6,0); } bool operator == (const EntryData &lhs, const EntryData &rhs) { if(lhs.ID != rhs.ID) { // cout << "FAIL HERE\n"; return false; } if(lhs.DexID != rhs.DexID) { // cout << "FAIL HERE2\n"; return false; } if(lhs.moveID != rhs.moveID) { /// cout << "FAIL HERE3\n"; return false; } if(lhs.nature != rhs.nature) { // cout << "FAIL HERE4\n"; return false; } if(lhs.item != rhs.item) { return false; } if(lhs.EV != rhs.EV) { // cout << "FAIL HERE5\n"; return false; } return true; }
true
4e7e204a18be0174f4bcbcc7723b7ddd3f277161
C++
AzureZheng/movers_ms_chs
/Classes/Objects/Building.cpp
GB18030
2,097
2.875
3
[]
no_license
#include "Objects/Building.h" #include "Info/GameInfo.h" //ʼ bool Building::init() { if (!Node::init()) { return false; } m_highFloor = 0; m_maxStagesCache = 5; return true; } //һ void Building::addStage() { m_highFloor++; BuildingStage * bs = nullptr; if (m_highFloor == 1) { bs = BuildingStage::createFirstFloor(m_playerFlag == 1); } else { if (m_buildingStages.size() >= m_maxStagesCache) { removeBottomStage(); } bs = BuildingStage::createNormalFloor(m_highFloor); bs->setPosition(Vec2(0, m_buildingStages.back()->getPosition().y + m_buildingStages.back()->getStageSize().height)); //˫ģʽмĴ if ((GameInfo::getInstance()->getModeCode() == "A1" || GameInfo::getInstance()->getModeCode() == "A2") && m_playerFlag == 1) { auto wd = Sprite::createWithSpriteFrameName("building_windows.png"); wd->setPositionX(-313 - 173); bs->addChild(wd); } } m_buildingStages.pushBack(bs); addChild(bs); } //Ƴײ void Building::removeBottomStage() { if (m_buildingStages.empty()) return; auto iter = m_buildingStages.begin(); (*iter)->removeFromParent(); m_buildingStages.erase(iter); } //ȡ¥ const Vector<BuildingStage*> & Building::getBuildingStages() const { return m_buildingStages; } //¥ void Building::clearFloors() { if (m_buildingStages.empty()) return; for (auto i = m_buildingStages.begin(); i != m_buildingStages.end();) { (*i)->removeFromParent(); i = m_buildingStages.erase(i); } } //¥ƶ void Building::moveAllFloors(float height) { for (auto & i : m_buildingStages) { i->setPositionY(i->getPositionY() + height); } } //ȡ BuildingStage * Building::getThrowStage() { if (m_buildingStages.size() < m_maxStagesCache) { return m_buildingStages.at(0); } else { return m_buildingStages.at(1); } } //ȡֲ BuildingStage * Building::getRecvStage() { if (m_buildingStages.size() < m_maxStagesCache) { return m_buildingStages.at(1); } else { return m_buildingStages.at(2); } }
true
19e8548fb34ec8ff4944d40ddc9320e9c91b8acc
C++
Shubham230198/Foundation
/C++_code/sahu.cpp
UTF-8
1,030
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; long long ans = 0; void getMin(unordered_map<int, int>& umap) { for(int i = 1; i < 1000000001; i++) { if(umap.find(i) == umap.end()) { ans += i; ans %= 998244353; break; } } return; } void getSub(int n, int arr[], int i, unordered_map<int, int>& set) { if(i == n) { getMin(set); return; } getSub(n, arr, i + 1, set); if(set.find(arr[i]) == set.end()) { set.insert(make_pair(arr[i], 1)); } else { set[arr[i]] = set[arr[i]] + 1; } getSub(n, arr, i + 1, set); if(set[arr[i]] == 1) set.erase(arr[i]); else set[arr[i]] = set[arr[i]] - 1; } int main() { int t; cin>>t; while(t--) { ans = 0; int n; cin>>n; int arr[n]; for(int i = 0; i < n; i++) { cin>>arr[i]; } unordered_map<int, int> set; getSub(n, arr, 0, set); cout<<ans<<"\n"; } }
true
9f3d9f4ed74922d92626aac16fadf13dc64c3286
C++
KunalFarmah98/Interview-Questions
/maximal_square.cpp
UTF-8
2,297
2.90625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; class SolutionDP { public: int maximalSquare(vector<vector<char>>& matrix) { int rows = matrix.size(), cols = rows > 0 ? matrix[0].size() : 0; int dp[rows+1][cols+1]; memset(dp,0,sizeof(dp)); int maxsqlen = 0; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j++) { // checking last cell of each square if (matrix[i-1][j-1] == '1'){ dp[i][j] = min(min(dp[i][j - 1], min( dp[i - 1][j], dp[i - 1][j - 1])) + 1; maxsqlen = max(maxsqlen, dp[i][j]); } } } return maxsqlen * maxsqlen; } }; class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.empty())return 0; int n = matrix.size(); int m = matrix[0].size(); int c=0; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(matrix[i][j]=='1')++c; } } if(c==0)return 0; int maxlen=1; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ int len=0; for(int k=1;k<=min(n,m);k++){ bool ok=true; for(int x=i; x<i+k; x++){ if(x>=n){ ok = false; break; } if(!ok)break; for(int y=j; y<j+k; y++){ if(y>=m || matrix[x][y]=='0'){ ok=false; break; } } } if(ok){ len=k; maxlen=max(maxlen,len); } } } } return maxlen*maxlen; } }; int main(){ int n,m; cin>>n>>m; vector<vector<char> > mat; for(int i=0; i<n; i++) { vector<char> c; for (int j = 0; j < m; j++){ char ch; cin>>ch; c.push_back(ch); } mat.push_back(c); } Solution s; cout<<s.maximalSquare(mat); }
true
14db0cb2987cedec106b0a2aa8d7319c6362fe52
C++
VRER1997/leetcode
/Array/437.cpp
UTF-8
726
3.125
3
[]
no_license
// // Created by wokaka on 2018/8/15. // #include <bits/stdc++.h> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int dfs(TreeNode *node, int sum){ int ret = 0; if(node == NULL) return ret; if(sum == node->val) ret++; ret += dfs(node->left, sum-node->val); ret += dfs(node->right, sum-node->val); return ret; } int pathSum(TreeNode* root, int sum) { if(root == NULL) return 0; return dfs(root,sum) + pathSum(root->left, sum) + pathSum(root->right, sum); } };
true
7c1d3afc65034635f19c1d64a558ec8e7a6418f6
C++
niumeng07/code-dev
/test/cpp/share_varibles.cpp
UTF-8
629
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <time.h> using namespace std; std::vector<int> x; int main(int argc, char *argv[]) { x.reserve(100); clock_t start = clock(); for (int i = 0; i < 10000; i++) { x.push_back(i); if (i % 100 == 0) { x.erase(x.begin(), x.end()); } } clock_t end = clock(); std::cout << end - start << std::endl; std::vector<int> y; y.reserve(100); start = clock(); for (int i = 0; i < 10000; i++) { y.push_back(i); if (i % 100 == 0) { y.erase(y.begin(), y.end()); } } end = clock(); std::cout << end - start << std::endl; return 0; }
true
44dbf9bdbd28288cc2edda05b36df704c01652a0
C++
maksadbek/coursera
/data-structures/bst.cpp
UTF-8
3,310
3.625
4
[]
no_license
#include <iostream> template <typename Comparable> class BinarySearchTree { public: BinarySearchTree(); BinarySearchTree(const BinarySearchTree &tree); BinarySearchTree(BinarySearchTree &&tree); ~BinarySearchTree(); const Comparable & find_min() const; const Comparable & find_max() const; bool contains(const Comparable & x) const; bool is_empty() const; void print(ostream & out = cout) const; void make_empty(); void insert(const Comparable & x); void insert(Comparable & x); void remove(const Comparable & x); BinarySearchTree & operator=(const BinarySearchTree & tree); BinarySearchTree & operator=(BinarySearchTree && tree); private: struct BinaryNode { Comparable element; BinaryNode *left; BinaryNode *right; BinaryNode(const Comparable & element, BinaryNode * lt, BinaryNode * rt) { element = element; left = lt; right = rt; } BinaryNode(Comparable & element, BinaryNode * lt, BinaryNode * rt) { element = element; left = lt; right = rt; } }; BinaryNode *root; // insert creates a new node in the tree. void insert(const Comparable & x, BinaryNode * & t) { }; void insert(Comparable && x, BinaryNode * & t); void remove(const Comparable & x, BinaryNode * & t); // find_min returns the min elemetn in the tree. BinaryNode * find_min(BinaryNode *t) const { while(t->left != nullptr) { t = t->left; } return t; }; // find_max returns the max element in the tree. BinaryNode * find_max(BinaryNode *t) const; // contains tests if an item is in a subtree. bool contains(const Comparable & x, BinaryNode * t) const { if(t == nullptr) { return false; } else if (x < t->element) { return contains(x, t->left); } else if (t->element < x) { return contains(x, t->right); } return true; }; // make_empty removes all nodes from the tree. void make_empty(BinaryNode * & t); // print prints the tree to the given stream. void print(BinaryNode * t, ostream & out) const; // clone returns the copy of the tree. BinaryNode * clone(BinaryNode * t) const; }; int main() { return 0; }
true
dcf87d074bc03e29f85b9120ee224fc07898c601
C++
AndySuperME/Queue
/Queue_Array.cpp
UTF-8
1,420
3.984375
4
[]
no_license
#include <iostream> using std::cout; using std::endl; template <class T> class Queue { public: Queue() :size(10), front(-1), rear(-1) { array = new T[size]; }; ~Queue() { delete array; }; bool Full(); bool Empty(); void Push(T); T Pop(); void PrintQueue(); private: T *array; int size; int front; int rear; }; int main() { Queue<int> queue; queue.Push(10); queue.Push(11); queue.Push(12); queue.Pop(); queue.Push(13); queue.PrintQueue(); Queue<char> queue1; queue1.Push('A'); queue1.Push('B'); queue1.Push('C'); queue1.Pop(); queue1.Push('D'); queue1.PrintQueue(); system("pause"); return 0; } template <class T> bool Queue<T>::Full() { if (rear + 1 == size) { return true; } else { return false; }; } template <class T> bool Queue<T>::Empty() { if (rear == -1) { return true; } else { return false; }; } template <class T> void Queue<T>::Push(T x) { if (Full() == true) { size++; } array[++rear] = x; front++; } template <class T> T Queue<T>::Pop() { if (Empty() == true) { cout << "Queue is empty!!" << endl;} else { T tmp = array[front--]; for (int i = 0; i < rear; i++) { array[i] = array[i + 1]; } rear--; return tmp; } } template <class T> void Queue<T>::PrintQueue() { for (int i = 0; i <= rear; i++) { cout << array[i] << " "; } cout << endl; }
true
d15c76c12a779dd1c29ee4e408c4e870b4f1f64e
C++
lakizoli/mineon
/mineon/Statistic.cpp
UTF-8
1,924
2.734375
3
[]
no_license
#include "stdafx.h" #include "Statistic.hpp" Statistic::Statistic () : mSubmittedCount (0) { } void Statistic::NewJobArrived (const std::string& jobID) { std::cout << std::endl; std::cout << "Got a new job! (jobID: " << jobID << ")" << std::endl; } void Statistic::ScanStarted (uint32_t threadIndex, const std::string& jobID, std::chrono::system_clock::time_point scanStart, uint32_t startNonce, uint32_t endNonce) { std::cout << std::endl; std::cout << "Thread " << threadIndex << " (" << jobID << "): scan started (start nonce: " << startNonce << ", end nonce: " << endNonce << ")" << std::endl; } void Statistic::ScanStepEnded (uint32_t threadIndex, const std::string& jobID, uint32_t nonce) { //TODO: ... static uint32_t cnt = 0; ++cnt; #ifdef _DEBUG if (cnt % 100 == 0) { #else //_DEBUG if (cnt % 1000 == 0) { #endif //_DEBUG std::cout << "Thread " << threadIndex << " (" << jobID << "): step ended -> nonce: " << nonce << " \r"; } } void Statistic::ScanEnded (uint32_t threadIndex, const std::string& jobID, std::chrono::system_clock::duration duration, uint32_t hashesScanned, bool foundNonce, uint32_t nonce) { double secs = (double) std::chrono::duration_cast<std::chrono::seconds> (duration).count (); double velocity = secs == 0 ? 0 : (double) hashesScanned / secs / 1000.0; std::cout << std::endl; std::cout << "Thread " << threadIndex << " (" << jobID << "): scan ended (duration: " << secs << " sec, velocity: " << velocity << " kH/sec, hash count: " << hashesScanned << ", found: " << (foundNonce ? "true" : "false") << ", nonce: " << nonce << ")" << std::endl; if (foundNonce) { ++mSubmittedCount; std::cout << "Submitted work count: " << mSubmittedCount; } } void Statistic::Error (const std::string& error) { std::cout << "Error: " << error << std::endl; } void Statistic::Message (const std::string& msg) { std::cout << "Message: " << msg << std::endl; }
true