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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3c39d13b289261512b15713fc29ce84e7906ab26 | C++ | Adrian925492/DataStructuresAndSearchAlgorithms | /Source/SortByChoose/SortByChoose.hpp | UTF-8 | 1,864 | 3.84375 | 4 | [] | no_license | #include <iostream>
/*
Sort by choose algorithm:
(min to max sort)
As in bouble algorithm, the algorithm divides array into two places - sorted and unsorted yet part.
Sorted part is on tle left side (in that case). The algorithm goes threw each element
of input array looking for minimum value and swapping it to be placed on the first place of unsorted part of
array. The minnimum value id is initially assigned to first element of unsirted part of array. If, during
going threw array, the algorithm find less value, it is swaped and id is assigned to new minimum.
//Step1:
Start looking for min value of the array. Assign id of min value on the first place (id == 0).
//Step2: Go threw each element of unsorted part of array (whole arrayat the begining). If any element is less than element
pointed by id of min value, swap it with 1st element of unsorted part of array and assign its id as min id.
//Step3: After goint to end of array at the first place we have min value. Consider 1st element as sorted part of array
and continue steps 1-3 on unsorted part of array, untill whole array will be sorted.
*/
namespace sortByChoose{
template <typename T>
void Sort(T array[], int arraySize)
{
int minIndex; //Index of currently known minimum value from array
for (int i = 0; i < arraySize - 1; ++i)
{
minIndex = i; //Assign minimum index - first element of unsorted part of array
for (int j = i + 1; j < arraySize; ++j) //Iterate threw unsorted array to find nim index
{
if (array[j] < array[minIndex]) //If element is < than element with index minIndex
{
minIndex = j; //Assig new minIndex
std::swap(array[i], array[minIndex]); //Swap found element with first from unsirted sublist
}
}
}
}
} | true |
8477c298f881853346e1373cbb9dc11c95f36ac6 | C++ | felipe0610/Proyecto02 | /main.cpp | UTF-8 | 2,878 | 2.984375 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include "Asiento.h"
#include "graderiaPreferencial.h"
#include "nodoAsiento.h"
using namespace std;
//Hileras de la gradería preferencial
//(PILAS)
//----------------------------------------------------------------
graderiaPreferencial *a = new graderiaPreferencial();
graderiaPreferencial *b = new graderiaPreferencial();
graderiaPreferencial *c = new graderiaPreferencial();
graderiaPreferencial *d = new graderiaPreferencial();
graderiaPreferencial *e = new graderiaPreferencial();
//-----------------------------------------------------------------
//Método para agregar butaca en la localidad de gradería preferencial
bool comprobarGraderiaPref(Asiento *pasiento){
if(!a->esLlena()){
a->agregar(pasiento);
return true;
}else{
if(!b->esLlena()){
b->agregar(pasiento);
return true;
}else{
if(!c->esLlena()){
c->agregar(pasiento);
return true;
}else{
if(!d->esLlena()){
d->agregar(pasiento);
return true;
}else{
if(!e->esLlena()){
e->agregar(pasiento);
return true;
}else{
return false;
}
}
}
}
}
}
//Método prara el procesamiento de las opciones del menú
void procesar(int popcion){
switch(popcion){
case 1:
int localidad;
cout<<"En qué localidad desea reservar?"<<endl;
cout<<"1-VIP\n2-Gradería Preferencial\n3-General"<<endl;
cin>>localidad;
switch(localidad){
case 1:
cout<<"Reservando en VIP. . ."<<endl;
break;
//Aquí va el código para reservar en VIP
case 2:
Asiento *asiento = new Asiento(5500,'R');
if(!comprobarGraderiaPref(asiento)){
cout<<"La localidad de Gradería Preferencial se encuentra llena"<<endl;
}else{
cout<<"Butaca reservada"<<endl;
}
break;
}
break;
case 2:
cout<<"Ha salido."<<endl;
break;
}
}
//Menú principal
void mostrarMenu(){
int opcion;
do{
cout << "Menú principal" <<endl;
cout<< "1- Reservar una butaca."<<endl;
cout<< "2- Salir."<<endl;
cin>>opcion;
procesar(opcion);
}while(opcion != 2);
}
int main(int argc, char** argv){
mostrarMenu();
return 0;
} | true |
ab086d1f9e4361399dfc88520dc34d3ac96f3f4d | C++ | blee1710/QwirklesqueGame | /LinkedList.cpp | UTF-8 | 2,851 | 3.578125 | 4 | [] | no_license |
#include "LinkedList.h"
LinkedList::LinkedList() :
head(nullptr),
tail(nullptr)
{
size = 0;
}
LinkedList::~LinkedList() {
// clear();
// delete head;
// delete tail;
}
void LinkedList::addFront(Tile* tile) {
Node* temp = new Node(tile, head, nullptr);
if (head == nullptr) {
head = temp;
tail = temp;
} else {
head = temp;
}
size++;
}
void LinkedList::addBack(Tile* tile) {
Node* temp = new Node(tile, nullptr, tail);
if (head == nullptr){
head = temp;
tail = temp;
temp = nullptr;
} else {
tail->next = temp;
tail = temp;
}
size++;
}
void LinkedList::deleteFront() {
Node* temp = head;
head = head->next;
delete temp;
size--;
}
//code to delete back of list... faster if double linked list is implemented?
void LinkedList::deleteBack() {
Node* temp = tail;
tail = tail->prev;
delete temp;
size--;
}
//code to return nodes as a string
std::string LinkedList::toString() {
std::string listString;
Node* curr = head;
if(size > 0){
for(int i = 0; i < size; i++) {
listString += (curr->getTile()->toString() + " ");
curr = curr->next;
}
}
return listString;
}
std::string LinkedList::toString2() {
std::string listString;
Node* curr = head;
if(size > 0){
for(int i = 0; i < size - 1 ; i++) {
listString += (curr->getTile()->toString2() + ",");
curr = curr->next;
}
listString += curr->getTile()->toString2();
}
return listString;
}
void LinkedList::deleteAt(int pos)
{
if (pos > size)
{
return;
}
if (pos == 0)
{
deleteFront();
}
else if (pos == size - 1)
{
deleteBack();
}
else
{
Node *curr = head;
for (int i = 0; i < pos; i++)
{
curr = curr->next;
}
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
delete curr;
size--;
}
}
//Getters
int LinkedList::getSize() {
return size;
}
//returns node, used for replacing tiles?? will possibly need to adj
// to remove from the list as well
Node* LinkedList::getNode(Tile* tile) {
Node* foundNode = nullptr;
Node* curr = head;
while(curr != nullptr && foundNode == nullptr){
if (curr->getTile() == tile){
foundNode = curr;
}
curr = curr->next;
}
return foundNode;
}
Node* LinkedList::getNodeAt(int index){
Node* foundNode = nullptr;
Node* curr = head;
int i = 0;
while (i < index){
curr = curr->next;
i++;
}
foundNode = curr;
return foundNode;
}
Tile* LinkedList::getTileAt(int index)
{
int i = 0;
Node *curr = head;
Tile *tile;
while (i < index)
{
curr = curr->next;
i++;
}
tile = curr->getTile();
return tile;
}
void LinkedList::clear(){
while(this->head != nullptr){
Node* toDelete = this-> head;
head = toDelete->next;
delete toDelete;
}
tail = nullptr;
}
| true |
c5f0ca0fb4ad57c29d589c9f1d20ab36a38defa9 | C++ | jjzhang166/MessageWait | /include/AsyncWaitMsg.h | UTF-8 | 2,103 | 2.578125 | 3 | [] | no_license |
#ifndef AsyncWaitMsg_INCLUDED
#define AsyncWaitMsg_INCLUDED
#include <map>
#include <vector>
#include <list>
#include "Poco/Timer.h"
#include "boost/function.hpp"
#include "boost/make_shared.hpp"
typedef boost::function<void (int msg, int param1, int param2)> MsgCallback;
typedef boost::function<void (int msg)> MsgTimeOutCallback;
enum CallbackType
{
Always,
Once
};
const long Infinity = 0xffffffff;
class CallbackItemBase
{
public:
CallbackItemBase()
:_callback(NULL), _timeOutCallback(NULL), _timeout(1000)
{}
virtual ~CallbackItemBase() {}
MsgCallback _callback;
MsgTimeOutCallback _timeOutCallback;
signed long _timeout; // will be changed in RegMsgTimeOutCallback function.
};
class NormalCallbackItem :public CallbackItemBase
{
public:
NormalCallbackItem()
:_type(Always), _msg(0)
{}
virtual ~NormalCallbackItem() {}
CallbackType _type;
int _msg;
};
class MutiCallbackItem :public CallbackItemBase
{
public:
MutiCallbackItem() {}
virtual ~MutiCallbackItem() {}
std::vector<int> _msgVec;
};
class AsyncWaitMsg
{
public:
static AsyncWaitMsg& instance()
{
static AsyncWaitMsg mc;
return mc;
}
bool RemoveListener(int msg, boost::shared_ptr<CallbackItemBase>);
void RegMsgTimeOutCallback(int msg, boost::shared_ptr<CallbackItemBase> pCallbackItem);
void Dispatch(int msg, int param1, int param2);
void MsgTimeOutChecking(Poco::Timer& timer);
bool AddListener(boost::shared_ptr<MutiCallbackItem>);
bool AddListener(boost::shared_ptr<NormalCallbackItem>);
void Reset();
void Stop();
private:
AsyncWaitMsg();
AsyncWaitMsg(const AsyncWaitMsg&);
AsyncWaitMsg& operator= (const AsyncWaitMsg&);
bool AddListener(int msg, boost::shared_ptr<CallbackItemBase>);
typedef std::vector<boost::shared_ptr<CallbackItemBase> > CallbackItemVec;
typedef std::map<int, CallbackItemVec> CallbackMap;
CallbackMap _callbackMap; // message dispatch map
typedef std::list<boost::shared_ptr<CallbackItemBase> > TimeOutCallbackItemList;
TimeOutCallbackItemList _timeoutCallbackList; // timeout callback function list
};
#endif // AsyncWaitMsg_INCLUDED
| true |
0dc5a29c5b99ff4c204ab03382d5554440c5d0fa | C++ | DoniDub/HomeWork | /Vehicle(CrossRoad)/Vehicle/Bicycle.h | UTF-8 | 382 | 2.734375 | 3 | [] | no_license | #pragma once
#include "GroundVehicle.h"
class Bicycle :
public GroundVehicle
{
public:
void stop();
void start();
Bicycle(std::string color, std::string model, int max_speed, int number_of_seats, int engine_power, std::string typeOfSeat);
std::string getTypeOfSeat();
void setTypeOfSeat(std::string typeOfSeat);
void info();
private:
std::string typeOfSeat;
}; | true |
b558f4ee222bce497b59d1a08649471b38c817d9 | C++ | saigowri/OpenCV-with-CUDA | /displayImage.cpp | UTF-8 | 727 | 2.546875 | 3 | [] | no_license | #include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include "opencv2/core/utility.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat src=imread("image.jpg",0); //load image from file
cuda::GpuMat d_src(src); // cpu -> gpu
cuda::GpuMat d_dst;
Mat dst;
d_dst.download(dst); //gpu -> cpu
imwrite("out.jpg", dst); //save image to file
if(!dst.data){
cout<<"Image cannot be displayed";
}
else
{
namedWindow( "Display window", WINDOW_AUTOSIZE ); //open display window
imshow( "Display window", dst);
waitKey(0); // Wait for a keystroke in the window
// since param is 0, wait forever.
}
return 0;
}
| true |
576593b7ffab3d7a0b3e218af447c323051fef64 | C++ | peitaosu/Logger | /Cpp/Logger/LogEvent.cpp | UTF-8 | 1,525 | 2.8125 | 3 | [
"Zlib",
"MIT"
] | permissive | //---------------------------------------------------//
// MIT License //
// Copyright @ 2018-2020 Tony Su All Rights Reserved //
// https://github.com/peitaosu/Logger //
//---------------------------------------------------//
#include "LogEvent.h"
LogEventException::LogEventException() {
}
LogEventException::LogEventException(std::string summary)
{
this->summary = summary;
}
LogEventException::LogEventException(std::string summary, std::string detail)
{
this->summary = summary;
this->detail = detail;
}
std::string LogEventException::GetSummary() {
return this->summary;
}
std::string LogEventException::GetDetail() {
return this->detail;
}
LogEvent::LogEvent() {
}
LogEvent::LogEvent(LogEventLevel level, std::string message) {
auto time = std::time(nullptr);
auto tm = *std::localtime(&time);
this->timestamp = tm;
this->level = level;
this->message = message;
}
LogEvent::LogEvent(LogEventLevel level, std::string message, LogEventException exception) {
auto time = std::time(nullptr);
auto tm = *std::localtime(&time);
this->timestamp = tm;
this->level = level;
this->message = message;
this->exception = exception;
}
std::tm LogEvent::GetTimestamp() {
return this->timestamp;
}
LogEventLevel LogEvent::GetLevel() {
return this->level;
}
std::string LogEvent::GetMessage() {
return this->message;
}
LogEventException LogEvent::GetException() {
return this->exception;
}
| true |
b7466876d179a1f96f493fcb937561cbdfefbc87 | C++ | jcayzac/random-stuff | /win-infographie/ray.cpp | UTF-8 | 717 | 2.59375 | 3 | [] | no_license | #include "ray.h"
#include "commode.h"
// Create a new Ray. When it's not iterated yet, it is endless.
CRay::CRay(const SMLVec3f& origin, const SMLVec3f& direction):
SMLRay(origin, direction,infinity) {
}
bool CRay::intersection(CRadPatch* patch) {
float nv_dot = patch->norm.Dot(direction);
// direction is parallel to plane
if (fabs(nv_dot) == .0f) return false;
float ti = - ((patch->norm.Dot(patch->vert[0]) + patch->norm.Dot(start))/nv_dot);
// intersection is behind ray origin
if (ti<=.0f) return false;
// a closer intersection already exists
if (ti>length) return false;
// ray has a length equal to ti
length = ti;
end = start+direction*ti;
return true;
}
| true |
084d59ed631b7d02b782f2942206078482ea3593 | C++ | wlike/sfcpp | /src/geo/ConvexPolytope.cpp | UTF-8 | 3,189 | 2.578125 | 3 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | /* Copyright 2017 The sfcpp Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "ConvexPolytope.hpp"
#include "QuickHullAlgorithm.hpp"
#include <strings/strings.hpp>
#include <iostream>
namespace sfcpp {
namespace geo {
ConvexPolytope::ConvexPolytope(size_t d) : faces(d + 1) {}
std::shared_ptr<ConvexPolytope> ConvexPolytope::convexHull(Eigen::MatrixXd points) {
auto hull = QuickHullAlgorithm(points).createPolytope();
hull->sort();
return hull;
}
std::ostream &operator<<(std::ostream &stream, ConvexPolytope::Face const &face) {
stream << face.vertices;
//<< "/" << strings::toString(face.childIndexes, ",") << "/"
//<< strings::toString(face.parentIndexes, ",");
return stream;
}
bool ConvexPolytope::tryFindFace(size_t dim, const math::NatSet &vertexSet,
size_t &faceIndex) const {
for (size_t i = 0; i < faces[dim].size(); ++i) {
auto &face = faces[dim][i];
if (face.vertices == vertexSet) {
faceIndex = i;
return true;
}
}
return false;
}
std::ostream &operator<<(std::ostream &stream, ConvexPolytope const &polytope) {
stream << "[" << strings::toString(polytope.faces, "]\n[", "; ") << "]";
return stream;
}
void ConvexPolytope::sort() {
size_t bound = faces[0].size() - 1;
for (size_t dim = 0; dim < faces.size(); ++dim) {
// sort faces in dimension dim
std::sort(faces[dim].begin(), faces[dim].end(), [&](Face const &first, Face const &second) {
auto f1 = first.vertices;
auto f2 = f1.reverseAt(bound);
auto s1 = second.vertices;
auto s2 = s1.reverseAt(bound);
auto f = f1.compare(f2) < 0 ? f1 : f2;
auto s = s1.compare(s2) < 0 ? s1 : s2;
auto result = f.compare(s);
if (result == 0) {
// faces are opposite to each other
return f1.compare(s1) < 0;
}
return result < 0;
});
if (dim >= 1) {
// renew parents of children
for (auto &child : faces[dim - 1]) {
child.parentIndexes.clear();
}
}
if (dim + 1 < faces.size()) {
for (auto &parent : faces[dim + 1]) {
parent.childIndexes.clear();
}
}
for (size_t i = 0; i < faces[dim].size(); ++i) {
auto &elem = faces[dim][i];
for (auto &pIndex : elem.parentIndexes) {
faces[dim + 1][pIndex].childIndexes.push_back(i);
}
for (auto &cIndex : elem.childIndexes) {
faces[dim - 1][cIndex].parentIndexes.push_back(i);
}
}
}
}
size_t ConvexPolytope::getDimension() { return faces.size() - 1; }
} /* namespace geo */
} /* namespace sfcpp */
| true |
7bfddac27fa62f64e8565661c0893a1106bed811 | C++ | Girl-Code-It/Beginner-CPP-Submissions | /Rishika/MILESTONE 12/PASSING FUNCTION 2D.cpp | UTF-8 | 963 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
void inp(int*a, int*m, int*n)
{
cout<<endl;
cout<<"Enter the number of rows :- ";
cin>>*m;
cout<<"Enter the number of columns :- ";
cin>>*n;
cout<<"Enter elements in the matrix :- "<<endl;
for(int i=0;i<*m;i++)
{
for(int j=0;j<*n;j++)
{
cin>>*(a + ( i * (*n)) + j);
}
}
}
void disp(int*a, int*m, int*n)
{
cout<<"Elements of matrix are :- ";
for(int i=0;i<*m;i++)
{
cout<<endl;
for(int j=0;j<*n;j++)
{
cout<<*(a + ( i * (*n)) + j)<<" ";
}
}
}
int main()
{
int a[10][10],m,n,ch;
do{
cout<<endl<<"-----MENU-----"<<endl<<"1. INPUT "<<endl<<"2. DISPLAY "<<endl<<"3. END "<<endl;
cin>>ch;
switch(ch)
{
case 1: inp(*a, &m, &n);
break;
case 2: disp(*a, &m, &n);
break;
case 3: exit(0);
break;
default: cout<<"Wrong";
break;
}
}while(ch!=3);
return 0;
}
| true |
db1a78484d91632aa3a8b80931fefbedbc6e59d1 | C++ | docici/cpp-test | /src/cti/test_cti_list.h | UTF-8 | 1,574 | 3 | 3 | [] | no_license | /*!
* 数据结构与算法分析(C++描述)_第3版
* @author hongjun.liao <docici@126.com>, @date 2017//05/05/18
* 双链表
* */
//////////////////////////////////////////////////////////////////////////
#ifndef TEST_CRACKING_THE_CODING_INTERVIEW_LIST
#define TEST_CRACKING_THE_CODING_INTERVIEW_LIST
#include <cstdio>
#include <cstdlib>
template<typename Key>
class list_node{
public:
typedef Key value_type;
public:
Key key_;
list_node * prev_, * next_;
public:
list_node(Key const& k = Key()): key_(k), prev_(NULL), next_(NULL) {}
};
template<typename Key>
class my_list{
public:
list_node<Key> * head_;
public:
my_list(): head_(NULL){}
};
//带哨兵的list
template<typename Key>
class list_with_sentinel{
public:
list_node<Key> nil_;
public:
list_with_sentinel();
};
//
template class list_node<int>;
template class my_list<int>;
//
template class list_with_sentinel<int>;
//
//双链表查找
template<typename Key>
list_node<Key>* list_search(my_list<Key> const& lst, Key const& k);
//双链表插入
template<typename Key>
void list_insert(my_list<Key> & lst, list_node<Key> const& node);
//双链表删除
template<typename Key>
void list_delete(my_list<Key> & lst, Key const& k);
//带哨兵的list的操作
template<typename Key>
list_node<Key>* list_search(list_with_sentinel<Key> const& lst, Key const& k);
template<typename Key>
void list_insert(list_with_sentinel<Key> & lst, list_node<Key> const& node);
template<typename Key>
void list_delete(list_with_sentinel<Key> & lst, Key const& k);
#endif /* TEST_CRACKING_THE_CODING_INTERVIEW_LIST */
| true |
886635944c4fa827b80059700496df03af2db087 | C++ | dementrock/acm | /poj/Archives/new/7070645_RE.cpp | UTF-8 | 2,348 | 2.765625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct sbt
{
int l,r,s,w,id;
} t[100001];
int data[100001],tot,root;
void rightrotate(int &k)
{
int p=t[k].l;
t[k].l=t[p].r;
t[p].r=k;
t[p].s=t[k].s;
t[k].s=t[t[k].l].s+t[t[k].r].s+1;
k=p;
}
void leftrotate(int &k)
{
int p=t[k].r;
t[k].r=t[p].l;
t[p].l=k;
t[p].s=t[k].s;
t[k].s=t[t[k].l].s+t[t[k].r].s+1;
k=p;
}
void maintain(int &k, int flag)
{
if(flag)
{
if(t[t[t[k].l].l].s>t[t[k].r].s)
rightrotate(k);
else if(t[t[t[k].l].r].s>t[t[k].r].s)
{
leftrotate(t[k].l);
rightrotate(k);
}
else return;
}
else
{
if(t[t[t[k].r].r].s>t[t[k].l].s)
leftrotate(k);
else if(t[t[t[k].r].l].s>t[t[k].l].s)
{
rightrotate(t[k].r);
leftrotate(k);
}
else return;
}
maintain(t[k].l,false);
maintain(t[k].r,true);
maintain(k,false);
maintain(k,true);
}
void insert(int &now, int w, int id)
{
if(!now)
{
t[++tot].l=0;
t[tot].r=0;
t[tot].s=1;
t[tot].w=w;
t[tot].id=id;
now=tot;
return;
}
if(w<t[now].w) insert(t[now].l,w,id);
else insert(t[now].r,w,id);
t[now].s=t[t[now].l].s+t[t[now].r].s+1;
maintain(now,w<t[now].w);
}
int del(int &now, int w)
{
--t[now].s;
if(w==t[now].w
||w<t[now].w&&!t[now].l
||w>=t[now].w&&!t[now].r)
{
int tmp=t[now].w;
if(!t[now].l||!t[now].r)
now=t[now].l+t[now].r;
else
t[now].w=del(t[now].l,w+1);
return tmp;
}
else
if(w<t[now].w)
return del(t[now].l,w);
else return del(t[now].r,w);
}
int select(int now, int p)
{
if(p==t[t[now].l].s+1)
return now;
else if(p<t[t[now].l].s+1)
return select(t[now].l,p);
else return select(t[now].r,p-1-t[t[now].l].s);
}
int main()
{
int type,k,p,counter=0;
while(1)
{
scanf("%d",&type);
if(!type) break;
if(type==2)
{
if(!counter)
printf("0\n");
else
{
int now=select(root,counter);
printf("%d\n",t[now].id);
if(counter) --counter;
del(root,t[now].w);
}
}
else if(type==3)
{
if(!counter)
printf("0\n");
else
{
int now=select(root,1);
printf("%d\n",t[now].id);
if(counter) --counter;
del(root,t[now].w);
}
}
else
{
++counter;
scanf("%d%d",&k,&p);
data[k]=p;
insert(root,p,k);
}
}
return 0;
}
| true |
a3bf17749328760754e2c3001a4a802b83f70e5c | C++ | vizzuhq/vizzu-lib | /src/chart/options/autoparam.h | UTF-8 | 1,465 | 3.046875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | #ifndef AUTOPARAM_H
#define AUTOPARAM_H
#include <optional>
#include <stdexcept>
#include <string>
#include "base/conv/parse.h"
#include "base/conv/tostring.h"
namespace Vizzu::Base
{
template <typename Type> struct AutoParam
{
public:
AutoParam() : autoSet(true) {}
explicit AutoParam(const Type &value) : value(value) {}
explicit AutoParam(std::optional<Type> value) :
value(std::move(value))
{}
explicit AutoParam(const std::string &s)
: autoSet(s == "auto")
{
if (!autoSet)
value = Conv::parse<std::optional<Type>>(s);
}
explicit operator std::string() const
{
if (autoSet)
return "auto";
if (!value)
return "null";
return Conv::toString(*value);
}
explicit operator bool() const { return static_cast<bool>(value); }
const Type &operator*() const { return *value; }
[[nodiscard]] bool isAuto() const { return autoSet; }
void setAuto(std::optional<Type> value)
{
if (isAuto()) this->value = std::move(value);
}
[[nodiscard]] Type getValue(const Type &autoValue) const
{
return isAuto() ? autoValue : *value;
}
[[nodiscard]] std::optional<Type> getValue() const
{
return isAuto() ? std::nullopt : value;
}
bool operator==(const Type &other) const
{
return value == other;
}
bool operator==(const AutoParam &other) const
{
return value == other.value && autoSet == other.autoSet;
}
private:
bool autoSet{};
std::optional<Type> value;
};
using AutoBool = AutoParam<bool>;
}
#endif
| true |
c4f13f54b0c3854bf5cae8591f90f6c990402acc | C++ | VitalyGrachev/Nsu-computer-graphics | /Life/model/life_impacts.h | UTF-8 | 637 | 3.109375 | 3 | [] | no_license | #ifndef LIFE_IMPACTS_H
#define LIFE_IMPACTS_H
#include <vector>
#include <cstdint>
class LifeImpactField {
public:
using Row = std::vector<double>;
LifeImpactField(uint32_t cols, uint32_t rows);
Row & operator[](uint32_t row);
const Row & operator[](uint32_t row) const;
bool is_contained(int col, int row);
void clear();
private:
std::vector<Row> impacts;
};
inline LifeImpactField::Row & LifeImpactField::operator[](uint32_t row) {
return impacts[row];
}
inline const LifeImpactField::Row & LifeImpactField::operator[](uint32_t row) const {
return impacts[row];
}
#endif //LIFE_IMPACTS_H
| true |
a8f099d765da5f7c4a35925eb0077b6ab6328a26 | C++ | Zhenghao-Liu/LeetCode_problem-and-solution | /0143.重排链表/solution2_deque.cpp | UTF-8 | 988 | 3.3125 | 3 | [] | no_license | //[deque介绍](https://www.cnblogs.com/linuxAndMcu/p/10260124.html)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if (head==NULL)
return;
deque<ListNode*> list_deque;
ListNode* p=head;
while (p!=NULL)
{
list_deque.push_back(p);
p=p->next;
}
p=list_deque.front();
list_deque.pop_front();
int index=0;
while (!list_deque.empty())
{
if (index==0)
{
p->next=list_deque.back();
list_deque.pop_back();
}
else
{
p->next=list_deque.front();
list_deque.pop_front();
}
p=p->next;
index=index^1;
}
p->next=NULL;
}
};
| true |
aeae448643446b551009642e6cb973f0b65ffb9d | C++ | jerryhanhuan/test-code-backup | /WTL/DecryptionDLP/show/memorymap/stkmutex/stk/os/SysMemory.cpp | UTF-8 | 2,364 | 2.984375 | 3 | [] | no_license | #include "SysMemory.h"
namespace STK
{
CSysMemory::CSysMemory(size_t nSize, const wchar_t *pszName)
: m_pMemory (NULL)
, m_hMemory (NULL)
, m_eMemoryType (eMemoryInvalid)
{
Create(nSize, pszName);
}
CSysMemory::~CSysMemory()
{
Release();
}
bool CSysMemory::Create(size_t nSize, const wchar_t *pszName)
{
//Check the size
if (nSize <= 0)
{
return false;
}
Release();
//If the name is NULL, allocate from the main memory
if ((pszName == NULL) || (pszName[0] == NULL))
{
//From main memory
m_pMemory = (void*) new (std::nothrow) BYTE [nSize];
if (m_pMemory == NULL)
{
return false;
}
memset(m_pMemory, 0, nSize);
m_eMemoryType = eMemoryHeap;
return true;
}
ULARGE_INTEGER qwSize;
qwSize.QuadPart = nSize;
//Try to create the view
m_hMemory = CreateFileMappingW(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE,
qwSize.HighPart, qwSize.LowPart, pszName);
//Get the error code
DWORD dwLastError = GetLastError();
if (m_hMemory == 0)
{
return false;
}
//Map the view
m_pMemory = MapViewOfFile(m_hMemory, FILE_MAP_ALL_ACCESS, 0, 0, nSize);
if (m_pMemory == 0)
{
Release();
return false;
}
if (dwLastError == ERROR_ALREADY_EXISTS)
{
m_eMemoryType = eMemoryShareOpen;
}
else
{
m_eMemoryType = eMemoryShareCreate;
memset(m_pMemory, 0, nSize);
}
return true;
}
bool CSysMemory::Release()
{
if (m_pMemory)
{
if (m_eMemoryType == eMemoryInvalid)
{
return false;
}
else if (m_eMemoryType == eMemoryHeap)
{
delete [] m_pMemory;
}
else
{
CloseHandle(m_hMemory);
UnmapViewOfFile(m_pMemory);
}
m_hMemory = NULL;
m_pMemory = NULL;
m_eMemoryType = eMemoryInvalid;
}
return true;
}
bool CSysMemory::GetMemory(void **pMemory)
{
if (m_eMemoryType == eMemoryInvalid)
{
return false;
}
*pMemory = m_pMemory;
return true;
}
MemoryType CSysMemory::GetMemoryType()
{
return m_eMemoryType;
}
} | true |
d7b5431e3c3c32687c75da7fc93aef8b7c49a8f6 | C++ | qhdwight/frc-go | /frc/phoenix/include/ctre/phoenix/motorcontrol/InvertType.h | UTF-8 | 1,523 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #pragma once
#include <string>
namespace ctre {
namespace phoenix {
namespace motorcontrol {
/**
* Choose the invert type of the motor controller.
* None is the equivalent of SetInverted(false), where positive request yields positive voltage on M+.
* InvertMotorOutput is the equivelant of SetInverted(true), where positive request yields positive voltage on M-.
* FollowMaster/OpposeMaster will match/oppose a master Talon/Victor. This requires device to be configured as a follower.
*/
enum class InvertType {
None = 0, //!< Same as SetInverted(false)
InvertMotorOutput = 1, //!< Same as SetInverted(true)
FollowMaster = 2, //!< Follow the invert of the master this MC is following.
OpposeMaster = 3, //!< Opposite of the invert of the master this MC is following.
};
/**
* Choose the invert type for a Talon FX based integrated motor controller.
* CCW is the equivalent of SetInverted(false), CW is the equivalent of SetInverted(true).
* FollowMaster/OpposeMaster will match/oppose a master Talon/Victor. This requires device to be configured as a follower.
*/
enum class TalonFXInvertType {
CounterClockwise = 0, //!< Same as SetInverted(false)
Clockwise = 1, //!< Same as SetInverted(true)
FollowMaster = 2, //!< Follow the invert of the master this MC is following.
OpposeMaster = 3, //!< Opposite of the invert of the master this MC is following.
};
} // namespace motorcontrol
} // namespace phoenix
} // namespace ctre
| true |
fecf92279f6bbb476c6b5f885a9f3df8f17ca6f8 | C++ | AlekhinKirill/C-_labs | /queues_&_stacks/Queue.cpp | UTF-8 | 1,329 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Cell
{
int value;
Cell* next_ptr;
};
struct Queue
{
int length;
Cell* first;
Cell* last;
};
Queue create_empty()
{
Queue list;
list.length = 0;
list.first = nullptr;
list.last = nullptr;
return list;
}
Queue enqueue(Queue queue, int value)
{
Cell* cell = new Cell;
cell->value = value;
cell->next_ptr = nullptr;
if (queue.length == 0)
{
queue.first = cell;
queue.last = cell;
}
else
{
queue.last->next_ptr = cell;
queue.last = cell;
}
queue.length += 1;
return queue;
}
Queue dequeue(Queue queue)
{
queue.first = queue.first->next_ptr;
queue.length -= 1;
return queue;
}
void print(Queue queue)
{
Cell* element_ptr;
element_ptr = queue.first;
cout << queue.first->value << " ";
while (element_ptr->next_ptr != nullptr)
{
cout << element_ptr->next_ptr->value << " ";
element_ptr = element_ptr->next_ptr;
}
cout << endl;
}
int main()
{
Queue queue;
queue = create_empty();
queue = enqueue(queue, 5);
queue = enqueue(queue, 12);
queue = enqueue(queue, 17);
queue = enqueue(queue, 1);
queue = dequeue(queue);
queue = enqueue(queue, 8);
queue = enqueue(queue, 11);
queue = enqueue(queue, 7);
queue = dequeue(queue);
print(queue);
} | true |
d9e93b0e561c6bf026de4024c05fe451abd33ee2 | C++ | kernight/ayitoj | /old/Windows/control/control/src/log.cpp | GB18030 | 2,313 | 3.171875 | 3 | [
"MIT"
] | permissive | /* Author:steve-liu
*blog:http://blog.csdn.net/liuxucoder/
*git:http://git.ykgzs.com
*/
#include "../include/log.h"
/* ַʽʱϢ */
stringstream string_stream;
/* ־Ϣȶ */
priority_queue<Info_Log> Que_Log;
/* ʼ־Ϣ */
Info_Log::Info_Log(int pri, string datail_info)
{
m_priori = pri;
m_detail = datail_info;
time_t now = time(NULL);
tm *tm_now = new tm;
localtime_s(tm_now, &now);
string temp = "";
/* ʽϢ */
string_stream.clear();
string_stream<<tm_now->tm_year+1900<<" "
<<tm_now->tm_mon+1<<" "
<<tm_now->tm_mday;
m_date = "";
while (string_stream >> temp){
m_date += temp;
m_date += "-";
}
m_date[m_date.length()-1]='\0';
/* ʽʱϢ */
string_stream.clear();
string_stream << tm_now->tm_hour << " "
<< tm_now->tm_min << " "
<< tm_now->tm_sec;
m_time = "";
while (string_stream >> temp){
m_time += temp;
m_time += ":";
}
m_time[m_time.length() - 1] = '\0';
delete(tm_now);
tm_now = NULL;
}
ostream & operator <<(ostream &out,Info_Log info)
{
out << "[ Date ] : " <<info.m_date << "[ Time ] : " << info.m_time << endl;
out << "[ Info ] : " << info.m_detail << endl;
out << endl;
return out;
}
bool operator <(Info_Log info_a, Info_Log info_b)
{
return info_a.m_priori < info_b.m_priori;
}
/* Ӽ¼ */
OJ_ERROR Log::log(Info_Log info)
{
Que_Log.push(info);
action(info);
save();
return OJ_ERROR_NULL;
}
/* Լ¼ϵͳ쳣Ƶȵ */
OJ_ERROR Log::action(Info_Log info)
{
return OJ_ERROR_NULL;
}
/* ־ļ */
OJ_ERROR Log::save()
{
while (false == Que_Log.empty())
{
Info_Log info = Que_Log.top();
Que_Log.pop();
string file_name = "";
if (LOG_ERROR == info.m_priori){
file_name += PH_LOG+"Error-";
}
else{
file_name += PH_LOG+"Normal-";
}
file_name = file_name + info.m_date + ".log";
ofstream fout(file_name.c_str(), ios::app);
try{
cout << info << endl;
if (false == fout.is_open()){
throw (OJ_ERROR)OJ_LOG_FILE;
}
fout << info;
fout.close();
}
catch (OJ_ERROR INFO){
if(OJ_LOG_FILE == INFO){
cerr << "־ļ" << endl;
fout.close();
}
}
}
return OJ_ERROR_NULL;
} | true |
4b32d25aeb29b2b24cef38905e49d60a2fe001de | C++ | Novacane01/Traphouse | /LinkedMap.h | UTF-8 | 2,686 | 2.765625 | 3 | [] | no_license | #pragma once
#include "SFML/Graphics.hpp"
#include "ctime"
#include "cstdlib"
#include <random>
#include <iostream>
#include "Player.h"
#include "Chest.h"
class Player;
class LinkedMap {
public:
struct hallway{
sf::RectangleShape floor;
sf::RectangleShape wallTop, wallRight, wallBottom, wallLeft;
};
struct room {
std::string name;
bool bIsVisited;
bool playerIsInside;
bool isCleared = false;
int neighbors = 0;
room* neighbor1;
room* neighbor2;
room* neighbor3;
room* previous;
sf::RectangleShape floor;
sf::RectangleShape wallTop, wallRight, wallBottom, wallLeft;
LinkedMap::hallway* hallway;
};
sf::Texture wallTexture;
sf::Texture floorTexture;
const int hallwayWidth = 150;
LinkedMap(int,int);
room* head;
Chest* chest1;
Chest* chest2;
void displayChestUI(Player*, sf::RenderWindow&);
void doesCollide(Player *);
bool doesIntersect(LinkedMap::room* current);
void addRooms(int rooms,room* current, sf::RenderWindow &);
void displayMap(room* current, sf::RenderWindow &window);
void displayCurrentRoom(room *, sf::RenderWindow &window, bool);
void printRoomNames(room* current);
LinkedMap::room* getCurrentRoom();
LinkedMap::room* getHead();
LinkedMap::room* getLevelUpRoom();
void findCurrentRoom(LinkedMap::room*, Player* player);
//Gets room on map that will contain staircase to level up
void findStairRoom(room* current);
//Spawns staircase in level up room
void placeStairs();
bool displayStairs(sf::RenderWindow &window, Player* player);
void placeLevelUpText();
void findChestRoom(room* current);
void placeChests();
void placeChestText();
bool displayChest1(sf::RenderWindow &window, Player* player,bool);
bool displayChest2(sf::RenderWindow &window, Player* player,bool);
LinkedMap::room* getChestRoom1();
LinkedMap::room* getChestRoom2();
Chest* getChest1();
Chest* getChest2();
private:
//list of all rectangle shapes added to check for intersections as rooms are made
std::vector<sf::RectangleShape> positions;
sf::Sprite stairs;
int level;
room* current = nullptr;
room* levelUpRoom = nullptr;
room* chestRoom = nullptr;
room* chestRoom2 = nullptr;
//counts
int roomsToAdd;
int count = 0; //helps show rooms added
int endRoomCount = 0; //number of rooms with no neighbors = number of map branches
//Text, Textures and Fonts
sf::Texture stairTexture;
sf::Texture chestTexture;
sf::Text levelUpText;
sf::Text chestText;
sf::Font font;
bool createRoom(LinkedMap::room* current, std::string, sf::RenderWindow &);
};
| true |
e5dba3495026a23023b62c5adf0094b0362c7089 | C++ | ayush2512/Interview-Questions | /revAltLL.cpp | UTF-8 | 818 | 3.4375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node
{
struct node *next;
int data;
};
void push(struct node **head,int data)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next = *head;
*head = temp;
}
void printLL(struct node *head)
{
struct node *temp = head;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
void reverseAlt(struct node *head)
{
struct node *curr=head;
while(curr!=NULL && curr->next!=NULL)
{
int temp = curr->data;
curr->data = curr->next->data;
curr->next->data = temp;
curr = curr->next->next;
}
}
int main()
{
struct node *head = NULL;
push(&head,9);
push(&head,7);
push(&head,5);
push(&head,3);
push(&head,1);
printLL(head);
reverseAlt(head);
printLL(head);
return 0;
} | true |
176e0d6b83ec23e6bb220286c87942e680b58cbf | C++ | frikkfossdal/improved-garbanzo | /src/Node.cpp | UTF-8 | 1,887 | 2.59375 | 3 | [] | no_license | //
// Node.cpp
// phd_sketch2
//
// Created by Frikk Fossdal on 31.01.2018.
//
// Redo this and make it as a thread
#include "Node.hpp"
Node::Node(){
}
Node::Node(ofVec3f initPos){
setup();
pos = initPos;
timeIndex = 0;
}
void Node::show(){
ofNoFill();
ofSetColor(100);
//ofDrawBox(pos->x, 0, 0, 30, 800, 50);
ofTranslate(0, 0,60);
ofDrawBox(pos.x,pos.y,pos.z,50,50,100);
ofTranslate(0,0,-60);
ofSetColor(255, 0, 0);
ofDrawCircle(pos.x, pos.y, borderRad);
contour.draw();
}
void Node::goTo(){
float distToTarget = target.distance(pos);
//ofSetColor(255);
//ofDrawLine(_target.x, _target.y, pos.x, pos.y);
//pos.interpolate(target, 0.0001);
}
void Node::setTarget(ofVec3f _target){
target = _target;
}
void Node::update(){
}
void Node::abortMove(){
}
void Node::borderCollisionCheck(){
if(pos.x > 900){
}
if(pos.x < 0){
}
if(pos.y > 400){
}
if(pos.y < 0){
}
}
void Node::createShape(){
ofVec2f p( 1.f, 0.f );
int angle = 360 / numVertices;
contour.clear();
for(int i = 0; i < numVertices; i++){
p.rotate( angle * ( 1.f + 0.5f * ofRandomf() ) );
contour.addVertex( ofVec2f( 200.f, 200.f ) + p * ofRandom( 300.f, 400.f ) );
}
contour.setClosed(true);
}
// ---------------------THREADING-------------------------
void Node::threadedFunction(){
while(isThreadRunning()){
float totalLength = contour.getLengthAtIndex(numVertices-1);
if(timeIndex == 500000){
timeIndex = 0;
length += 1.f;
if(length >=totalLength) length -=totalLength;
pos = contour.getPointAtLength(length);
}
timeIndex++;
timeIndex2++;
}
}
void Node::startNode(){
if(contour.size() > 10){
startThread();
}
}
void Node::stopNode(){
stopThread();
}
//private methods
| true |
bc734fd5f38607a1a87d1e8b11176181bac20168 | C++ | seanxwzhang/leetcode-1 | /122 Best Time to Buy and Sell Stock II/best_time_to_buy_sell_stock_2.cpp | UTF-8 | 441 | 3.203125 | 3 | [] | no_license | /*
* LeetCode Submissions by Xinyu Chen
* Best Time to Buy and Sell Stock II
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
* Runtime: 8 ms
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
int diff = prices[i] - prices[i - 1];
profit += diff > 0 ? diff : 0;
}
return profit;
}
}; | true |
ca0ecad98e35ae98f88689161a104a27d9fe34ff | C++ | axelcinco/Programacion2 | /trabajo27_cap9.cpp | UTF-8 | 298 | 3.046875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<string_view>
using namespace std;
int main()
{
string_view sv{"pelota"};
sv.remove_suffix(3);
string str{sv};
auto szNullTerminated{str.c_str()};
cout<<"Tiene "<<strlen(szNullTerminated)<<" Letra(s)"<<endl;
return 0;
}
| true |
adf36d3cb0bd9a6244f79eb1d65803e4547b093a | C++ | hushaobao/vcf2csv | /src/meta/any.hpp | UTF-8 | 326 | 2.546875 | 3 | [] | no_license | #pragma once
// std
#include <initializer_list>
namespace vcf {
namespace meta {
template <typename T, typename ...Args>
constexpr bool any(T&& t, Args&&... args)
{
bool match{false};
(void)std::initializer_list<bool>{(match = match || t == args)...};
return match;
}
} // namepace meta
} // namespace vcf
| true |
fd466cd4cd0c2ad6ae24e8f100c87b33423d7552 | C++ | Adnn/Graphics-archived | /src/libs/Math/Vector-impl.h | UTF-8 | 1,698 | 3.015625 | 3 | [] | no_license | /*
* Vector implementation
*/
template <class T_derived, int N_dimension, class T_number>
T_number & Vector<T_derived, N_dimension, T_number>::operator[](std::size_t aColumn)
{
return this->at(aColumn);
}
template <class T_derived, int N_dimension, class T_number>
T_number Vector<T_derived, N_dimension, T_number>::operator[](std::size_t aColumn) const
{
return this->at(aColumn);
}
template <class T_derived, int N_dimension, class T_number>
T_derived & Vector<T_derived, N_dimension, T_number>::operator*=(
const Matrix<N_dimension, N_dimension, T_number> &aRhs)
{
(*this) = (*this) * aRhs;
return *this->derivedThis();
}
template <class T_derived, int N_dimension, class T_number>
T_derived operator*(const Vector<T_derived, N_dimension, T_number> aLhs,
const Matrix<N_dimension, N_dimension, T_number> &aRhs)
{
return multiplyBase<T_derived>(aLhs, aRhs);
}
template <class T_derived, int N_dimension, class T_number>
T_number Vector<T_derived, N_dimension, T_number>::dot(const Vector &aRhs) const
{
T_number result = 0;
for(std::size_t col = 0; col != N_dimension; ++col)
{
result += (*this)[col] * aRhs[col];
}
return result;
}
/*
* Vec3Base implementation
*/
template <class T_derived, class T_number>
T_derived & Vec3Base<T_derived, T_number>::crossAssign(const Vec3Base &aRhs)
{
*this = this->cross(aRhs);
return *this->derivedThis();
}
template <class T_derived, class T_number>
T_derived Vec3Base<T_derived, T_number>::cross(const Vec3Base &aRhs)
{
return {
y()*aRhs.z() - z()*aRhs.y(),
z()*aRhs.x() - x()*aRhs.z(),
x()*aRhs.y() - y()*aRhs.x(),
};
}
| true |
07110815f114e09fdc176c3ce68685a609d69b45 | C++ | heyzqq/Cpp-Back-Syntax | /3Class/35 - 异常 .cpp | UTF-8 | 1,458 | 3.875 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*
异常:
try catch throw
异常类型:
* 数字
* 字符串
* 对象
*/
// 传统方式
double div(double n1, double n2)
{
if (0 == n2)
{
return 1;
}
return n1 / n2;
}
// 异常: 数字
double div2(double n1, double n2)
{
if (0 == n2)
{
// return 1;
throw 1;
}
return n1 / n2;
}
// 类
class ErrorType{};
void test(int *t)
{
if (NULL == t)
throw ErrorType(); // 抛出类异常
else
cout << "Nothding was done!" << endl;
}
int main()
{
// 传统处理
cout << "Classic: " << div(56, 8) << endl;
cout << "Classic: " << div(56, 0) << endl;
try
{
// 有可能出现异常的代码
cout << "Exception: " << div2(8, 3) << endl;
cout << "Exception: " << div2(8, 5) << endl;
// 不同的异常类型需要多个catch
test(NULL);
}
catch (int error) // int: 异常类型
{
// 处理异常
cout << "异常代码: " << error << endl;
}
catch (ErrorType e)
{
// catch是有序的, 遇到异常执行catch之后就结束了,不会继续执行
cout << "2nd Catch !" << endl;
}
catch (...)
{
// 任意, 太多个异常了
// 尽量把重要的异常放前面单独catch
cout << "这里抓的是漏网之鱼!" << endl;
}
return 0;
}
| true |
7bfbbeab30b10d61681e3fc0bb9012bbf18ca506 | C++ | ailyanlu/acm-code | /2014-training/0512_map/B.cc | UTF-8 | 1,359 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <cstring>
using namespace std;
map<string, int> m;
map<string, int>::iterator iter, end;
map<char, char> t;
int main()
{
t['A'] = t['B'] = t['C'] = '2';
t['D'] = t['E'] = t['F'] = '3';
t['G'] = t['H'] = t['I'] = '4';
t['J'] = t['K'] = t['L'] = '5';
t['M'] = t['N'] = t['O'] = '6';
t['P'] = t['R'] = t['S'] = '7';
t['T'] = t['U'] = t['V'] = '8';
t['W'] = t['X'] = t['Y'] = '9';
int n;
scanf("%d", &n);
while (n--)
{
char s[100];
string p = "";
scanf("%s", s);
int len = strlen(s);
for (int i = 0; i < len; ++i)
{
if (isdigit(s[i]))
p += s[i];
else if (isalpha(s[i]))
{
if (s[i] == 'Q' || s[i] == 'Z')
continue;
p += t[s[i]];
}
}
p.insert(3, "-");
m[p]++;
}
bool flag = true;
iter = m.begin();
end = m.end();
while (iter != end)
{
if ((iter->second) > 1)
{
flag = false;
cout << iter->first << " " << iter->second << endl;
// printf("%s %d\n", iter->first, iter->second);
}
++iter;
}
if (flag)
printf("No duplicates.\n");
return 0;
} | true |
d00cdf2508429a1320180fc26cd02f045bccabc5 | C++ | cuiwenzhe/BackSwipe | /BackSwipeApp/app/src/main/cpp/internal/base/quantizer.cc | UTF-8 | 1,474 | 2.640625 | 3 | [] | no_license | #include <cmath>
#include "quantizer.h"
#include <android/log.h>
Quantizer::Quantizer() : max_(1.f), nbits_(1) {};
Quantizer::Quantizer(float max, int nbits) : max_(max), nbits_(nbits) {};
void Quantizer::init(float max, int nbits) {
max_ = max;
nbits_ = nbits;
}
Quantizer::~Quantizer() {}
float Quantizer::max() const {
return max_;
}
int Quantizer::nbits() const {
return nbits_;
}
EqualSizeBinQuantizer::EqualSizeBinQuantizer() : max_encoded_(1), encoding_const_(1.f) {};
EqualSizeBinQuantizer::EqualSizeBinQuantizer(float max, int nbits)
: Quantizer(max, nbits){
max_encoded_ = static_cast<uint32>(pow(2, nbits) - 1);
encoding_const_ = max / max_encoded_;
};
void EqualSizeBinQuantizer::init(float max, int nbits) {
max_ = max;
nbits_ = nbits;
max_encoded_ = static_cast<uint32>(pow(2, nbits) - 1);
encoding_const_ = max / max_encoded_;
};
uint32 EqualSizeBinQuantizer::Encode(float f) const {
if (f < 0.f) {
return 0;
}
for(int i = 0; i < max_encoded_; i ++){
if(f >= (i - 0.5f) * encoding_const_ && f < (i + 0.5f) * encoding_const_){
return static_cast<uint32>(i);
}
}
return max_encoded_;
}
float EqualSizeBinQuantizer::Decode(uint32 i) const {
//__android_log_print(ANDROID_LOG_INFO, "#####", "Quantizer ~~~ Decode");
if(i > max_encoded_)
return max();
float norm_value = static_cast<float>(i) * encoding_const_;
return norm_value;
}; | true |
17983dd26222b26929f636a4effba73ebe5997de | C++ | pizisuan/Algorithm-Problem | /Uncommon_Words_from_Two_Sentences.cpp | UTF-8 | 1,747 | 3.765625 | 4 | [] | no_license | /*
* Problem Description
* We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)
* A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
* Return a list of all uncommon words. You may return the list in any order.
*
* Example 1
* Input: A = "this apple is sweet", B = "this apple is sour"
* Output: ["sweet","sour"]
*
* Example 2
* Input: A = "apple apple", B = "banana"
* Output: ["banana"]
*
*/
class Solution
{
public:
vector<string> uncommonFromSentences(string A, string B)
{
string s = A + " " + B;
vector<string> words;
string word;
for (auto letter : s)
{
if (letter != ' ')
{
word += letter;
}
else
{
if (!word.empty())
{
words.push_back(word);
word = "";
}
}
}
if (!word.empty())
{
words.push_back(word);
}
int count = 0;
vector<string> res;
for (auto word : words)
{
for (auto item : words)
{
if (item == word)
{
count++;
}
}
if (count == 1)
{
res.push_back(word);
}
count = 0;
}
return res;
}
};
// 实际上可用采用下面的函数完成字符串的按空格分隔
// 按照空格分隔字符串
vector<string> split(string& words)
{
stringstream ss(words);
string word;
vector<string> res;
while (ss >> word)
{
res.push_back(word);
}
return res;
}
| true |
52c0701da327b6b72f2f94bcc2fdf13d7aa859b8 | C++ | artisth/YoloMouse | /source/YoloMouse/Share/Cursor/CursorInfo.cpp | UTF-8 | 965 | 2.640625 | 3 | [
"Unlicense"
] | permissive | #include <YoloMouse/Share/Cursor/CursorInfo.hpp>
namespace Yolomouse
{
// public
//-------------------------------------------------------------------------
CursorInfo::CursorInfo( CursorType type_, CursorId id_, CursorVariation variation_, CursorSize size_ ):
type (type_),
id (id_),
variation(variation_),
size (size_)
{
}
//-------------------------------------------------------------------------
Bool CursorInfo::IsValid() const
{
// validate type and associated parameters
switch( type )
{
case CURSOR_TYPE_BASIC:
case CURSOR_TYPE_OVERLAY:
return id < CURSOR_ID_COUNT && variation < CURSOR_VARIATION_COUNT && size >= CURSOR_SIZE_MIN && size < CURSOR_SIZE_COUNT;
case CURSOR_TYPE_CLONE:
return size >= CURSOR_SIZE_MIN && size < CURSOR_SIZE_COUNT;
default:
return false;
}
}
}
| true |
00200ee308ae867cf2ec3ca8880df4d8a0f885ff | C++ | ydl0715/yuan | /moshi/Factory.h | UTF-8 | 1,365 | 2.8125 | 3 | [] | no_license | //
// Factory.h
// moshi
//
// Created by Sudent on 14-9-25.
// Copyright (c) 2014年 Sudent. All rights reserved.
//
#ifndef __moshi__Factory__
#define __moshi__Factory__
#include <iostream>
//using namespace std;
//static const double PI=3.14;
//
//class Shape {
//public:
// virtual double Area()=0;
// virtual ~Shape(){}
//};
//
//class Rectangle:public Shape
//{
//public:
// Rectangle(int width,int height)
// {
// _width=width;
// _height=height;
// }
//
//
//public:
// double Area()
// {
// return _width*_height;
// }
//private:
// int _width;
// int _height;
//};
//
//class Circle:public Shape
//{
//
//
//public:
// Circle(int radius)
// {
// _radius=radius;
// }
// double Area()
// {
// return PI*_radius*_radius;
// }
//private:
// int _radius;
//
//};
//
//class Creator {
//public:
// virtual Shape* CreateShape()=0;
// virtual ~Creator(){};
//};
//
//class RectCreator:public Creator {
//public:
// Shape* CreateShape()
// {
// Rectangle* rect=new Rectangle(10,20);
// return rect;
// }
//};
//
//class CircleCreator:public Creator
//{
//public:
// Shape* CreateShape()
// {
// Circle* circle=new Circle(10);
// return circle;
// }
//
//};
#endif /* defined(__moshi__Factory__) */
| true |
a0b60456c5998d550079b754111b8c28e35d8d0b | C++ | edjo93/p3lab3_EddasCarrasco | /Cola.cpp | UTF-8 | 499 | 2.671875 | 3 | [] | no_license | #ifndef COLA_CPP
#define COLA_CPP
#include<string>
using namespace std;
class Cola{
private:
int largo;
string peluda;
public: Cola(){
}
public: int getLargo() {
return largo;
}
public: void setLargo(int largo) {
this->largo = largo;
}
public: string getPeluda() {
return peluda;
}
public: void setPeluda(string peluda) {
this->peluda = peluda;
}
~Cola(){
}
};
#endif
| true |
886b0161119739618da98afc70d5f6ac88cda2da | C++ | vifactor/AnalyticalMisfitInterface | /tests/test_analytical_interface_cub_bx.cpp | UTF-8 | 1,924 | 2.640625 | 3 | [] | no_license | //============================================================================
// Name : test_analytical_interface_cub_bx.cpp
// Author : Viktor Kopp
// Version :
// Copyright : Your copyright notice
// Description : Tests for cubic interface class with bx component dislocations
//============================================================================
#include "AnalyticalMisfitInterfaceCub.h"
#include <gtest/gtest.h>
namespace {
class AnalyticalMisfitInterfaceCubBxTest : public ::testing::Test {
protected:
virtual void SetUp()
{
/*dummy parameters used in Mathematica file*/
double rho = 0.1;
double bx = 1.0;
double by = 0.0;
double bz = 0.0;
double Qx = 2.2;
double Qy = 3.3;
double Qz = 4.4;
double phi = M_PI / 9;
double nu = 1.0 / 3;
double d = 12;
double z = 2;
/**values obtained in the Mathematica*/
wxx = 0.195903;
wyy = 0.173499;
wzz = 0.150516;
wxy = 0.0187993;
wxz = -0.175359;
wyz = -0.263038;
interface = new AnalyticalMisfitInterfaceCub(rho, bx, by, bz, Qx, Qy,
Qz, phi, nu, d);
interface->init(z);
}
virtual void TearDown()
{
if(interface)
delete interface;
interface = NULL;
}
double wxx, wyy, wzz, wxy, wxz, wyz;
AnalyticalMisfitInterfaceCub * interface;
};
// Tests wij methods
TEST_F(AnalyticalMisfitInterfaceCubBxTest, wxx)
{
EXPECT_NEAR(interface->wxx(), wxx, 1e-2);
}
TEST_F(AnalyticalMisfitInterfaceCubBxTest, wzz)
{
EXPECT_NEAR(interface->wzz(), wzz, 1e-2);
}
TEST_F(AnalyticalMisfitInterfaceCubBxTest, wxz)
{
EXPECT_NEAR(interface->wxz(), wxz, 1e-2);
}
TEST_F(AnalyticalMisfitInterfaceCubBxTest, wyy)
{
EXPECT_NEAR(interface->wyy(), wyy, 1e-2);
}
TEST_F(AnalyticalMisfitInterfaceCubBxTest, wxy)
{
EXPECT_NEAR(interface->wxy(), wxy, 1e-2);
}
TEST_F(AnalyticalMisfitInterfaceCubBxTest, wyz)
{
EXPECT_NEAR(interface->wyz(), wyz, 1e-2);
}
} // namespace
| true |
3d0acb964e8772301471230ac1688b43fb04ce9d | C++ | tihonov-e/cpp_stepik | /Algorithms/Source/pairs_sort.cpp | WINDOWS-1251 | 1,870 | 3.078125 | 3 | [] | no_license | //1.12 STL
// algorithm.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
/**
. ,
. utility.
, .
.
*/
int main()
{
int n = 0;
cin >> n;
vector <pair <int, int>> a(n);
for (int i = 0; i < n; i++) {
int temp = 0;
cin >> temp;
a[i] = { temp, i };
}
sort(a.begin(), a.end());
for (auto now : a) cout << now.second << " ";
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
b60ff10ec3d5b0b109ca15075d2c84568d2a1ba5 | C++ | Zepyhrus/CPP-Primer | /src/chapter5/e5.1.cpp | UTF-8 | 545 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using namespace std;
/* Exercise of section 5.1, including:
* 5.1
* 5.2
* 5.3
*/
int main(int argc, char** argv) {
cout << "5.1 An empty sentence with single semicolon." << endl;
cout << "5.2 A few statements compounded by curly braces.\n"
<< "\tUsed in somewhere grammaticaly one statement,\n"
<< "\thowever, multiple statements are necessary logisticaly" << endl;
int sum = 0, val = 0;
while (val <= 10) sum += val++;
cout << sum << endl;
return 0;
} | true |
33877959a3829776392d025de387ac44f7d52317 | C++ | ewalasagas/university_directory | /Student.h | UTF-8 | 720 | 2.5625 | 3 | [] | no_license | /*********************************************************************
** Program name: Lab4
** Author: Elaine Alasagas
** Date: 2/4/2019
** Description: CS162_400_WINTER2019 - Student.hpp class
*********************************************************************/
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
#include <vector>
#include <limits>
#include <cmath>
#include <algorithm>
#include <fstream>
#include "Person.h"
using namespace std;
class Student : public Person {
private:
double GPA;
protected:
public:
Student();
Student(string sname, int sage, double g);
void setGPA(double g);
double getGPA() const;
void print();
string toString();
void do_work();
~Student();
};
#endif
| true |
54d25882bb51e99e18ff1bc5406e9508425f9b1f | C++ | utec-ads-2019-2/spreadsheet-196-rvmosquera | /main.cpp | UTF-8 | 5,193 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
const int CANT_ROWS = 1000;
const int CANT_COL = 18279;
using namespace std;
struct node {
int col = 0;
int row = 0;
node *next = nullptr;
void killSelf() {
if (next) {
next->killSelf();
}
delete this;
}
};
bool isCalculated[CANT_ROWS][CANT_COL];
int spreadsheet[CANT_ROWS][CANT_COL];
node formula[CANT_ROWS][CANT_COL];
int calculateCellContent(int row, int col) {
int sum = 0;
if (isCalculated[row][col])
return spreadsheet[row][col];
auto nodeAux = formula[row][col].next;
if (nodeAux) {
while (nodeAux->next != nullptr) {
auto row2 = nodeAux->row;
auto col2 = nodeAux->col;
if (isCalculated[row2][col2]) {
sum = sum + spreadsheet[row2][col2];
} else {
spreadsheet[row2][col2] = calculateCellContent(row2, col2);
sum = sum + spreadsheet[row2][col2];
}
nodeAux = nodeAux->next;
}
if (nodeAux) {
auto row2 = nodeAux->row;
auto col2 = nodeAux->col;
if (isCalculated[row2][col2]) {
sum = sum + spreadsheet[row2][col2];
} else {
spreadsheet[row2][col2] = calculateCellContent(row2, col2);
sum = sum + spreadsheet[row2][col2];
}
}
} else {
auto row2 = formula[row][col].row;
auto col2 = formula[row][col].col;
if (isCalculated[row2][col2]) {
sum = sum + spreadsheet[row2][col2];
} else {
sum = sum + calculateCellContent(row2, col2);
}
}
isCalculated[row][col] = true;
return sum;
}
void print2(int array[][CANT_COL], int rows, int cols) {
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
if (!isCalculated[j][k]) {
array[j][k] = calculateCellContent(j, k);
cout << array[j][k] << " ";
} else
cout << array[j][k] << " ";
}
cout << endl;
}
}
pair<int, int> get_row_and_col(string cell) {
auto len = cell.length();
string numbers;
int col = 0;
int row = 0;
int count = 0;
int ascii = 0;
for (int i = len - 1; i >= 0; i--) {
if (isdigit(cell[i])) {
numbers = cell[i] + numbers;
} else {
ascii = (int) cell[i] - 65;
col = col + ascii + (ascii + 1) * 26 * count;
count++;
}
}
row = stoi(numbers);
row--;
return make_pair(row, col);
}
void getFormula(int j, int k, string cell) {
string delimiter = "+";
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string operandStr;
char first = 'Y';
if (cell[0] == '=')
cell = cell.substr(1, cell.length());
formula[j][k].next = nullptr;
while ((pos_end = cell.find(delimiter, pos_start)) != string::npos) {
operandStr = cell.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
auto cell_operand = get_row_and_col(operandStr);
node *newNode = new node();
auto row = cell_operand.first;
auto col = cell_operand.second;
newNode->row = row;
newNode->col = col;
if (first == 'Y') {
formula[j][k].next = newNode;
first = 'N';
} else {
auto aux = formula[j][k].next;
while (aux->next != nullptr) {
aux = aux->next;
}
aux->next = newNode;
}
}
auto cell_operand = get_row_and_col(cell.substr(pos_start));
auto newNode = new node();
auto row = cell_operand.first;
auto col = cell_operand.second;
newNode->row = row;
newNode->col = col;
auto aux = formula[j][k].next;
if (aux) {
while (aux->next != nullptr) {
aux = aux->next;
}
aux->next = newNode;
} else {
formula[j][k].next = newNode;
}
}
int main(int argc, char *argv[]) {
int number;
int cols, rows;
string cell;
string line;
cin >> number;
for (int i = 0; i < number; i++) {
cin >> cols >> rows; // >> line;
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
cin >> cell;
formula[j][k].row = j;
formula[j][k].col = k;
auto firstChar = cell[0];
if (isdigit(firstChar)) {
spreadsheet[j][k] = atoi(cell.c_str());
isCalculated[j][k] = true;
} else {
if (firstChar == '-') //Negative
{
spreadsheet[j][k] = atoi(cell.c_str());
isCalculated[j][k] = true;
} else {
isCalculated[j][k] = false;
getFormula(j, k, cell);
}
}
}
}
print2(spreadsheet, rows, cols);
}
return EXIT_SUCCESS;
}
| true |
adceabb2ff7a82af1b055a6b2536574546e87dff | C++ | martinv/pdekit | /src/common/ArrayShape.hpp | UTF-8 | 5,110 | 3.078125 | 3 | [] | no_license | #ifndef PDEKIT_Common_Array_Shape_hpp
#define PDEKIT_Common_Array_Shape_hpp
#include "common/PDEKit.hpp"
#include <ostream>
namespace pdekit
{
namespace common
{
template <Uint DIM, typename SizeType>
class ArrayShape;
template <Uint DIM, typename SizeType>
bool operator==(const ArrayShape<DIM, SizeType> &lhs, const ArrayShape<DIM, SizeType> &rhs);
template <Uint DIM, typename SizeType>
bool operator!=(const ArrayShape<DIM, SizeType> &lhs, const ArrayShape<DIM, SizeType> &rhs);
template <Uint DIM, typename SizeType>
class ArrayShape
{
public:
/// TYPEDEFS
using size_type = SizeType;
/// Default constructor
ArrayShape();
/// Construct from sizes in each dimension
template <typename... Ts>
ArrayShape(Ts... args);
/// Copy constructor
ArrayShape(const ArrayShape &other);
/// Destructor
~ArrayShape();
/// Assigment operator
ArrayShape &operator=(const ArrayShape &rhs);
/// Get the size in one dimension
SizeType size(const Uint dim) const;
/// Return the number of dimensions in shape
constexpr Uint nb_dims() const;
/// Check if two shapes are the same
friend bool operator==
<DIM, SizeType>(const ArrayShape<DIM, SizeType> &lhs, const ArrayShape<DIM, SizeType> &rhs);
/// Check if two shapes are the same
friend bool operator!=
<DIM, SizeType>(const ArrayShape<DIM, SizeType> &lhs, const ArrayShape<DIM, SizeType> &rhs);
private:
/// TYPES
struct PosIdx
{
Uint value;
SizeType *dim_storage;
};
/// FUNCTIONS
template <typename LastSize>
void process_params(PosIdx &pos_idx, LastSize size)
{
pos_idx.dim_storage[pos_idx.value] = size;
}
template <typename Size, typename... OtherSizes>
void process_params(PosIdx &pos_idx, Size size, OtherSizes... sizes)
{
pos_idx.dim_storage[pos_idx.value] = size;
pos_idx.value++;
process_params(pos_idx, sizes...);
}
/// DATA
SizeType m_sizes[DIM];
};
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
ArrayShape<DIM, SizeType>::ArrayShape()
{
for (Uint dim = 0; dim < DIM; ++dim)
{
m_sizes[dim] = SizeType{};
}
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
template <typename... Ts>
ArrayShape<DIM, SizeType>::ArrayShape(Ts... args)
{
static_assert(sizeof...(args) <= DIM, "ArrayShape constructor: too many arguments");
for (Uint dim = 0; dim < DIM; ++dim)
{
m_sizes[dim] = 0;
}
PosIdx pos_idx;
pos_idx.value = 0;
pos_idx.dim_storage = &m_sizes[0];
process_params(pos_idx, args...);
/*
std::cout << "Constructed values of array shape:" << std::endl;
for (Uint dim = 0; dim < DIM; ++dim)
{
std::cout << "[" << dim << "] = " << m_sizes[dim] << std::endl;
}
*/
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
ArrayShape<DIM, SizeType>::ArrayShape(const ArrayShape &other)
{
for (Uint dim = 0; dim < DIM; ++dim)
{
m_sizes[dim] = other.m_sizes[dim];
}
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
ArrayShape<DIM, SizeType>::~ArrayShape()
{
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
ArrayShape<DIM, SizeType> &ArrayShape<DIM, SizeType>::operator=(const ArrayShape &rhs)
{
for (Uint dim = 0; dim < DIM; ++dim)
{
m_sizes[dim] = rhs.m_sizes[dim];
}
return *this;
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
inline SizeType ArrayShape<DIM, SizeType>::size(const Uint dim) const
{
return m_sizes[dim];
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
inline constexpr Uint ArrayShape<DIM, SizeType>::nb_dims() const
{
return DIM;
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
std::ostream &operator<<(std::ostream &os, const ArrayShape<DIM, SizeType> &arr_shape)
{
os << "[";
for (Uint d = 0; d < DIM; ++d)
{
os << " " << arr_shape.size(d);
}
os << " ]";
return os;
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
bool operator==(const ArrayShape<DIM, SizeType> &lhs, const ArrayShape<DIM, SizeType> &rhs)
{
for (Uint d = 0; d < DIM; ++d)
{
if (lhs.m_sizes[d] != rhs.m_sizes[d])
{
return false;
}
}
return true;
}
// ----------------------------------------------------------------------------
template <Uint DIM, typename SizeType>
bool operator!=(const ArrayShape<DIM, SizeType> &lhs, const ArrayShape<DIM, SizeType> &rhs)
{
return !operator==(lhs, rhs);
}
// ----------------------------------------------------------------------------
} // Namespace common
} // Namespace pdekit
#endif // PDEKIT_Common_Array_Shape_hpp
| true |
887145650b5f7fd67f4aa146e3a9ba4b6221c74f | C++ | B-Matt/algoritmi-labosi | /ConsoleApplication1/LV3.cpp | UTF-8 | 2,709 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | #include "pch.h"
//#include <stdio.h>
//#include <stdlib.h>
//#include <conio.h>
//
//// Povrh s povezanim popisom
//struct cvor
//{
// int x;
// struct cvor* next;
//};
//
//struct cvor* push(struct cvor* glava, int data)
//{
// struct cvor* p = (struct cvor*) malloc(sizeof(cvor));
// if (p == NULL)
// {
// printf("Heap Overflow!\n");
// return NULL;
// }
//
// p->x = data;
// p->next = glava;
// glava = p;
// return glava;
//}
//
//struct cvor* pop(struct cvor* glava, int *data)
//{
// struct cvor* p = glava;
// *data = glava->x;
// glava = glava->next;
// //free(p);
// return glava;
//}
//
//int is_empty(struct cvor* glava)
//{
// return glava == NULL ? 0 : 1;
//}
//
//int PovrhStogLista(struct cvor* stack1, struct cvor* stack2, int a, int b)
//{
// stack1 = push(stack1, a);
// stack2 = push(stack2, b);
// int povrh = 0;
// do
// {
// int n = 0, m = 0;
// pop(stack1, &n);
// pop(stack2, &m);
//
// if (m == n || m == 0) povrh = povrh + 1;
// else
// {
// stack1 = push(stack1, n - 1);
// stack2 = push(stack2, m - 1);
// stack1 = push(stack1, n - 1);
// stack2 = push(stack2, m);
// }
// } while (!is_empty(stack1));
// return povrh;
//}
//
//// Povrh s stogom
//int const MAX = 10;
//int stack1[MAX], sp1 = -1;
//int stack2[MAX], sp2 = -1;
//
//void push(int array[], int &sp, int a)
//{
// if (sp == (MAX - 1))
// {
// printf("Stack Overflow!\n");
// return;
// }
// sp++;
// array[sp] = a;
//}
//
//int pop(int array[], int &sp)
//{
// if (sp == -1)
// {
// printf("Stack Undeflow\n");
// return -1;
// }
// int a = array[sp];
// array[sp] = 0;
// sp--;
// return a;
//}
//
//bool is_empty(int sp)
//{
// if (sp == -1)
// {
// return true;
// }
// return false;
//}
//
//int PovrhStog(int a, int b)
//{
// push(stack1, sp1, a);
// push(stack2, sp2, b);
// int povrh = 0;
//
// do
// {
// int n = pop(stack1, sp1);
// int m = pop(stack2, sp2);
//
// if (m == n || m == 0) povrh = povrh + 1;
// else
// {
// push(stack1, sp1, n - 1);
// push(stack2, sp2, m - 1);
// push(stack1, sp1, n - 1);
// push(stack2, sp2, m);
// }
// } while (!is_empty(sp1));
// return povrh;
//}
//
//// Povrh s rekurzijom
//int Povrh(int n, int r)
//{
// if (r == 0 || r == n) return 1;
// return Povrh(n - 1, r - 1) + Povrh(n - 1, r);
//}
//
//
//// MAIN
//int main()
//{
// int n = 0, m = 0;
// struct cvor* stack1 = NULL;
// struct cvor* stack2 = NULL;
//
// printf("Unesite n: ");
// scanf_s("%d", &n);
// printf("Unesite m: ");
// scanf_s("%d", &m);
//
// /*printf("Povrh (rekurzija): %d\n", Povrh(n, m));
// printf("Povrh (stog): %d\n", PovrhStog(n, m));*/
// printf("Povrh (stog preko lista): %d\n", PovrhStogLista(stack1, stack2, n, m));
// _getch();
// return 0;
//}
| true |
01315b95f355e7272c4bbb99df492170cdb0655b | C++ | heroinetty/ACM | /C++/code/类运算符.cpp | GB18030 | 1,053 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <typeinfo>
using namespace std;
class op
{
int a = 0, b = 0;
public :
op(int x, int y) : a(x), b(y) {}
~op() {}
int Add()
{
return a + b;
}
int Sub()
{
return a - b;
}
};
class A
{
public :
int Add(int a, int b)
{
cout << "Add call" << endl;
return a + b;
}
};
int main()
{
op op1(1, 2);
op1.Add();
op *p = new op(1, 2);
p -> Add();
A a;
a.Add(1, 2);
cout << typeid(a).name() << endl; // class A
// cout << typeid(a.Add).name() << endl; // int_cdecl<int, int> ͨú
cout << typeid(&A :: Add).name()<< endl; // int<__thiscall A::*><int, int> ֱӷ
int ( A :: *pf)(int, int) = &A :: Add; // һָָԱ
A *pmy = &a;
cout << (a.*pf)(1, 2) << endl;
cout << (pmy ->* pf)(11, 2) << endl;
// Աָʱָ ->* .*
return 0;
}
| true |
1b8e0ba133809d471ab75165071afff95ca8546d | C++ | zyhustgithub/leetcode | /hard/128.最长连续序列.cpp | UTF-8 | 2,026 | 3.015625 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=128 lang=cpp
*
* [128] 最长连续序列
*/
// @lc code=start
// class Solution {
// public:
// int longestConsecutive(vector<int>& nums) {
// if (nums.empty()) {
// return 0;
// }
// for (int n : nums) {
// st[n] = n;
// cnt[n] = 1;
// }
// int ans = 1;
// for (int n : nums) {
// if (st.count(n + 1) > 0) {
// ans = max(ans, Merge(n, n + 1));
// }
// }
// return ans;
// }
// int FindParent(int x)
// {
// if (st[x] == x) {
// return x;
// }
// st[x] = st[FindParent(st[x])];
// return st[x];
// }
// int Merge(int x, int y)
// {
// x = FindParent(x);
// y = FindParent(y);
// if (x == y) {
// return cnt[x];
// }
// st[y] = st[x];
// cnt[x] += cnt[y];
// return cnt[x];
// }
// private:
// unordered_map<int, int> st;
// unordered_map<int, int> cnt;
// };
// class Solution {
// public:
// int longestConsecutive(vector<int>& nums) {
// unordered_set<int> st(nums.begin(), nums.end());
// int res = 0;
// for (int n : st) {
// if (st.count(n - 1) == 0) {
// int cnt = 1;
// while (st.count(n + 1)) {
// ++cnt;
// ++n;
// }
// res = (res < cnt) ? cnt : res;
// }
// }
// return res;
// }
// };
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> dp;
int res = 0;
for (int x: nums) {
if (!dp[x]) {
dp[x] = dp[x - 1] + dp[x + 1] + 1;
dp[x - dp[x - 1]] = dp[x];
dp[x + dp[x + 1]] = dp[x];
}
res = max(res, dp[x]);
}
return res;
}
};
// @lc code=end
| true |
5c6df4b874d03d0dd702b134ccc0a2d8874587f3 | C++ | github11/Renderman-Tests | /capi/anim/main.cpp | UTF-8 | 2,891 | 2.53125 | 3 | [] | no_license | #include <ri.h>
#include <cmath>
#include <cstdlib>
#include <iostream>
void doFrame(int fNum, char *fName);
int main(int argc, char *argv[])
{
if (argc<2) {
std::cerr << "No filename given.\n";
return 1;
}
int i;
RiBegin(RI_NULL);
for (i=1;i<=360; ++i) {
doFrame(i, argv[1]);
}
RiEnd();
}
void doFrame(int fNum, char *fName) {
RtPoint points[4] = {-0.5,0,-0.5,
-0.5,0,0.5,
0.5,0,0.5,
0.5,0,-0.5};
RiFrameBegin(fNum); {
static RtColor Color = {.2, .4, .6} ;
RtFloat radius=1.0,
zmin = -1.0,
zmax = 1.0,
thetamax=360;
char buffer[256];
std::sprintf(buffer, "images/%s%03d.tif", fName, fNum);
// std::cout << buffer << "\n";
RiDisplay(buffer,(char*)"file",(char*)"rgba",RI_NULL);
RiFormat(800, 600, 1.3);
RiLightSource((char*)"distantlight",RI_NULL);
RiProjection((char*)"perspective",RI_NULL);
RiTranslate(0.0,0.0,8.5);
RiRotate(-40.0, 1.0,0.0,0.0);
RiRotate(-40.0, 0.0,1.0,0.0);
RtColor bgcolor = {0.9,0.9,0.9};
RiImager((char*)"background", (char*)"color bgcolor", &bgcolor, RI_NULL);
RiWorldBegin(); {
RiColor(Color);
RtFloat roughness = 0.03;
int trace = 1;
//RtFloat km = .3;
//RtFloat maxKm = 1.0;
// RtFloat opac[] = {0.4,0.4,0.4};
RtFloat color[] = {0.9,0.9,0.9};
const char *texName = "texture2.tx";
RiColor(color);
RiSurface((char*)"paintedplastic", (char*)"texturename", &texName, RI_NULL);
RiRotate(fNum, 0,1,0);
RiAttributeBegin(); {
RiTranslate(-5.0,2.5,0.0);
RiSphere(2.0,-2.0,2.0,360.0,RI_NULL);
} RiAttributeEnd();
RiAttributeBegin(); {
RiTranslate(0.0,2.5,0.0);
RiCylinder(2.0,-2.0,2.0,360.0,RI_NULL);
}RiAttributeEnd();
RiAttributeBegin(); {
RiTranslate(5.0,2.5,0.0);
RiCone(4.0,2.0,360.0,RI_NULL);
} RiAttributeEnd();
RiAttributeBegin(); {
RiTranslate(-5.0,-2.5,0.0);
RiParaboloid(4.0,0.0,4.0,360.0,RI_NULL);
} RiAttributeEnd();
RtPoint p1 = {-1,-1,-4};
RtPoint p2 = {4,2,4};
RiAttributeBegin(); {
RiTranslate(0.0,-2.5,0.0);
RiHyperboloid(p1, p2, 360.0,RI_NULL);
} RiAttributeEnd();
RiAttributeBegin(); {
RiTranslate(5.0,-2.5,0.0);
RiTorus(2.0,0.5,0,360,360,RI_NULL);
} RiAttributeEnd();
} RiWorldEnd();
} RiFrameEnd();
}
| true |
af5a9e40e7d4f14dd294e67ad29a183f79bfffdc | C++ | yqbeyond/Algorithms | /uva/uva1225_fast.cpp | UTF-8 | 1,370 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int len(int n)
{
int res = 0;
if (n == 0)
return 1;
while(n)
{
n /= 10;
res++;
}
return res;
}
void print(long long *times)
{
for (int i = 0 ; i < 9; i++)
printf("%lld ", times[i]);
printf("%lld\n", times[9]);
}
int main()
{
long long times[10][10] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
for (int i = 2; i < 10; i++)
{
times[i][0] = times[i-1][0] + times[i-1][1] * 9;
for (int j = 1; j <= 9; j++)
times[i][j] = (long long)(pow(10, i - 1)) + times[i - 1][j] * 10;
}
int T;
scanf("%d", &T);
while(T--)
{
int n;
scanf("%d", &n);
int _len = len(n);
long long res[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int tmp = 9;
for (int i = 1; i < _len; i++)
{
res[0] += tmp * i;
tmp *= 10;
}
res[0] += (n - (long long)(pow(10, _len-1)) + 1) * _len;
while(n)
{
int first = n / (long long)(pow(10, _len - 1));
for (int i = 1; i < 10; i++)
{
res[i] += times[_len - 1][i] * first;
if (i < first)
res[i] += (long long)(pow(10, _len - 1));
if (i == first)
res[i] += 1;
}
n %= (long long)(pow(10, _len - 1));
if (first != 0)
res[first] += n;
_len -= 1;
}
for (int i = 1; i < 10; i++)
{
res[0] -= res[i];
}
print(res);
}
return 0;
}
| true |
e6505bcac98dcef8163ecbf1880d14e7b2313594 | C++ | brinkqiang2cpp/cpp-validator | /include/dracosha/validator/validate.hpp | UTF-8 | 4,480 | 2.53125 | 3 | [
"BSL-1.0"
] | permissive | /**
@copyright Evgeny Sidorov 2020
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
/****************************************************************************/
/** @file validator/validate.hpp
*
* Defines validate() helper.
*
*/
/****************************************************************************/
#ifndef DRACOSHA_VALIDATOR_VALIDATE_HPP
#define DRACOSHA_VALIDATOR_VALIDATE_HPP
#include <stdexcept>
#include <dracosha/validator/error.hpp>
#include <dracosha/validator/validators.hpp>
#include <dracosha/validator/adapters/default_adapter.hpp>
#include <dracosha/validator/adapters/reporting_adapter.hpp>
#include <dracosha/validator/adapters/prevalidation_adapter.hpp>
DRACOSHA_VALIDATOR_NAMESPACE_BEGIN
/**
* @brief Implementation of a helper to invoke validate() as a single callable.
*/
struct validate_t
{
/**
* @brief Validate object with validator and put result to the last argument.
* @brief obj Object to validate.
* @brief validator Validator.
* @brief err Error to put validation result to.
*/
template <typename ObjectT, typename ValidatorT>
void operator() (
ObjectT&& obj,
ValidatorT&& validator,
error& err
) const
{
err.set_value(validator.apply(std::forward<ObjectT>(obj)));
}
/**
* @brief Validate object with validator and put validation result with error description to the last argument.
* @brief obj Object to validate.
* @brief validator Validator.
* @brief err Error to put validation result to.
*/
template <typename ObjectT, typename ValidatorT>
void operator() (
ObjectT&& obj,
ValidatorT&& validator,
error_report& err
) const
{
err.reset();
err.set_value(validator.apply(
make_reporting_adapter(
std::forward<ObjectT>(obj),
err._message
)
));
}
/**
* @brief Validate object with validator and throw validation_error if operation fails.
* @brief obj Object to validate.
* @brief validator Validator.
*
* @throws validation_error if validation fails.
*/
template <typename ObjectT, typename ValidatorT>
void operator() (
ObjectT&& obj,
ValidatorT&& validator
) const
{
error_report err;
(*this)(std::forward<ObjectT>(obj),std::forward<ValidatorT>(validator),err);
if (err)
{
throw validation_error(err);
}
}
/**
* @brief Pre-validate object's member with validator and put validation result with error description to the last argument.
* @brief member Path of the member to validate.
* @brief obj Object to validate.
* @brief validator Validator.
*/
template <typename MemberT, typename ValueT, typename ValidatorT>
void operator() (
MemberT&& member,
ValueT&& val,
ValidatorT&& validator,
error_report& err
) const
{
err.reset();
err.set_value(validator.apply(
make_prevalidation_adapter(
std::forward<MemberT>(member),
std::forward<ValueT>(val),
err._message
)
));
}
/**
* @brief Pre-validate object's member with validator and throw validation_error if operation fails.
* @brief member Path of the member to validate.
* @brief obj Object to validate.
* @brief validator Validator.
*
* @throws validation_error if validation fails.
*/
template <typename MemberT, typename ValueT, typename ValidatorT>
void operator() (
MemberT&& member,
ValueT&& val,
ValidatorT&& validator
) const
{
error_report err;
(*this)(std::forward<MemberT>(member),std::forward<ValueT>(val),std::forward<ValidatorT>(validator),err);
if (err)
{
throw validation_error(err);
}
}
};
/**
* @brief Helper to invoke validate() as a single callable.
*/
constexpr validate_t validate{};
DRACOSHA_VALIDATOR_NAMESPACE_END
#endif // DRACOSHA_VALIDATOR_VALIDATE_HPP
| true |
509d2fa6ad7a1be5aba58b1caddd4c16016667f2 | C++ | timothyschoen/CSD2 | /CSD2d/Opdr1-ADSR/Source/Generator.cpp | UTF-8 | 764 | 2.875 | 3 | [] | no_license | #include <unistd.h>
#include <iostream>
#include <cmath>
#include "Generator.h"
//Constructor
Generator::Generator() {
frequency = 0;
}
//Constructor
Generator::~Generator() {
}
//Function we can overwrite for the filter, will do nothing on an oscillator subclass
void Generator::setPitch(int pitch) {
frequency = mtof(pitch+transpose);
// This will trigger a recalculation of the filter, it will execute an empty virtual function for other classes
calc();
}
void Generator::setTranspose(float amount) {
transpose = amount;
}
double Generator::getSample(float amplitude) {
return output * amplitude;
}
//Midi to Frequency function
double Generator::mtof(int input) {
float freq = 440 * pow(2, ((float)input - 49) / 12);
return freq;
}
| true |
959fc5bc00331ebd11afdbfd5c55d4836fba92e4 | C++ | hamsham/LightUtils | /include/lightsky/utils/NetServer.hpp | UTF-8 | 2,782 | 2.65625 | 3 | [
"BSD-2-Clause"
] | permissive |
#ifndef LS_UTILS_NETWORK_SERVER_HPP
#define LS_UTILS_NETWORK_SERVER_HPP
#include <cstdint>
#include <vector>
#include "lightsky/utils/NetNode.hpp"
#include "lightsky/utils/NetConnection.hpp"
namespace ls
{
namespace utils
{
/*-----------------------------------------------------------------------------
* UDP Server
-----------------------------------------------------------------------------*/
class NetServer final : public NetNode
{
private:
std::vector<NetConnection> mClients;
public:
~NetServer() noexcept override;
NetServer() noexcept;
NetServer(const NetServer&) = delete;
NetServer(NetServer&&) noexcept;
NetServer& operator=(const NetServer&) = delete;
NetServer& operator=(NetServer&&) noexcept;
int connect(
uint32_t ip,
uint16_t port,
size_t maxClients,
uint8_t maxChannels = (uint32_t)NetConnection::CHANNEL_COUNT_LIMITLESS,
uint32_t inBps = (uint32_t)NetConnection::CONNECTION_BYTES_PER_SEC_LIMITLESS,
uint32_t outBps = (uint32_t)NetConnection::CONNECTION_BYTES_PER_SEC_LIMITLESS
) noexcept;
void disconnect(uint32_t clientIp) noexcept;
void disconnect() noexcept override;
int broadcast(const void* pData, size_t numBytes, uint8_t channelId) noexcept;
int send(size_t clientId, const void* pData, size_t numBytes, uint8_t channelId) noexcept;
NetEventInfo poll(NetEvent* pNetInfo, uint32_t timeoutMillis) noexcept override;
const std::vector<NetConnection>& clients() const noexcept;
const NetConnection& client(size_t clientId) const noexcept;
NetConnection& client(size_t clientId) noexcept;
};
/*-------------------------------------
* Send data to a specific client
-------------------------------------*/
inline int NetServer::send(size_t clientId, const void* pData, size_t numBytes, uint8_t channelId) noexcept
{
if (clientId >= mClients.size())
{
return -1;
}
return mClients[clientId].send(pData, numBytes, channelId);
}
/*-------------------------------------
* Get the currently connected clients.
-------------------------------------*/
inline const std::vector<NetConnection>& NetServer::clients() const noexcept
{
return mClients;
}
/*-------------------------------------
* Get a client connection (const)
-------------------------------------*/
inline const NetConnection& NetServer::client(size_t clientId) const noexcept
{
return mClients[clientId];
}
/*-------------------------------------
* Get a client connection
-------------------------------------*/
inline NetConnection& NetServer::client(size_t clientId) noexcept
{
return mClients[clientId];
}
} // end utils namespace
} // end ls namespace
#endif /* LS_UTILS_NETWORK_SERVER_HPP */
| true |
da921004d7fcebce82e72b117cc668d94404985c | C++ | alvinquach/cs5550 | /Labs/Lab01/Lab01.cpp | UTF-8 | 3,878 | 3.015625 | 3 | [] | no_license | // Computer Graphics
// change accordingly
#include <windows.h>
#include <math.h> // included for random number generation
#include <gl/Gl.h>
#include "glut.h"
#define PI 3.14159265
const int screenWidth = 500;
const int screenHeight = 500;
struct GLintPoint {
GLint x, y;
};
GLintPoint pts[4];
int NoOfPts = 0;
int pointIndex = 0;
bool drawRect = true;
bool resetRectOnNextClick = false;
void myInit(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0); // background color is white
glColor3f(0.0f, 0.0f, 0.0f); // drawing color is black
glMatrixMode(GL_PROJECTION); // set "camera shape"
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble)screenWidth, 0.0, (GLdouble)screenHeight);
}
/// <summary>Helper method for resetting polygon point counters.</summary>
void resetPointCount() {
NoOfPts = 0;
pointIndex = 0;
resetRectOnNextClick = false;
}
/// <summary>Helper method for generating a random float between 0.0 and 1.0.</summary>
float randomFloat() {
return (float)rand() / RAND_MAX;
}
/// <summary>Helper method for drawing the rectangle.</summary>
void drawRectangle(GLenum mode) {
glBegin(mode);
for (int i = 0; i < NoOfPts; i++) {
glVertex2d(pts[i].x, pts[i].y);
}
glEnd();
}
void myMouse(int button, int state, int x, int y)
{
// Only do something if only the left or right button was pushed down (don't do anything if button was released).
if (state != GLUT_DOWN || (button != GLUT_LEFT_BUTTON && button != GLUT_RIGHT_BUTTON)) {
return;
}
// Reset point count and point index on this click if needed.
if (resetRectOnNextClick) {
resetPointCount();
}
// Set point based on mouse coordinates.
pts[pointIndex].x = x;
pts[pointIndex].y = screenHeight - y;
// If the point index exceeds 3, then wrap it back to 0.
if (++pointIndex > 3) {
pointIndex = 0;
}
// Increment number of points by one if it is less than 4.
NoOfPts += NoOfPts < 4 ? 1 : 0;
// If right clicked, reset point count and point index on next click.
if (button == GLUT_RIGHT_BUTTON) {
resetRectOnNextClick = true;
}
drawRect = true;
glutPostRedisplay();
}
void myKeyboard(unsigned char theKey, int mouseX, int mouseY)
{
switch (theKey) {
case 'c':
glClearColor(randomFloat(), randomFloat(), randomFloat(), 1.0);
break;
case 'p':
drawRect = false;
resetPointCount();
break;
default:
break; // do nothing
}
glutPostRedisplay(); // implicitly call myDisplay
}
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
// Draw polygon
if (drawRect) {
drawRectangle(GL_POLYGON);
// Not required.
drawRectangle(GL_POINTS);
drawRectangle(GL_LINE_LOOP);
}
// Draw cosine
else {
glBegin(GL_POINTS);
for (GLdouble x = 0; x < screenWidth; x++) {
GLdouble x1 = 2 * PI * x / screenWidth;
GLdouble y = cos(x1);
glVertex2d(x, screenHeight * (0.25 * y + 0.5));
}
glEnd();
}
glFlush();
}
//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(screenWidth, screenHeight); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Computer Graphics - Lab1"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
glutMouseFunc(myMouse);
glutKeyboardFunc(myKeyboard);
myInit();
glutMainLoop(); // go into a perpetual loop
}
/* C++ code segment to generate random numbers: between 1 and 50
#include <ctime>
...
srand((unsigned)time(0));
int randomInt = rand()%50 + 1;
float randomFloat = (float)rand()/RAND_MAX;
cout << "Random Integer between 1 and 50 = " << randomInt << endl;
cout << "Random Float between 0 and 1 = " << randomFloat << endl;
*/ | true |
306ff923ab0b8b45c31bc98cc2b3e1150f46540e | C++ | talesm/glBoilerplate | /src/util/fastMath.hpp | UTF-8 | 897 | 3.328125 | 3 | [
"MIT"
] | permissive | #pragma once
/**
* @brief Get an always positive module
*
* The number returned is the number you have to subtract from the quotient to
* get the previous divisible quotient.
*
* @param q the quotient
* @param d the divisor
* @return int the module
*/
inline int
floorMod(int q, int d)
{
return q > 0 ? q % d : d + q % d;
}
/**
* @brief The classic fast inverse square root.
*
* @param number The number to get square root from
* @return float the result
*/
inline float
rsqrt(float number)
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = *(long*)&y; // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1); // what the fuck?
y = *(float*)&i;
y = y * (threehalfs - (x2 * y * y)); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration,
return y;
}
| true |
6d87f4c35577b1d66f92c096a8bba7d92310948b | C++ | zahidford/C-plus-plus-Procedural-Programming-Knowlege | /Pointer_to_functios/main.cpp | UTF-8 | 459 | 3.46875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void double_value(int *int_ptr)
{
*int_ptr *=2;
}
int main()
{
int value {10};
int *int_ptr {nullptr};
cout << "value is " << value << endl;
double_value(&value);
cout << "value :" << value << endl;
cout << "............................" << endl;
int_ptr = &value;
double_value(int_ptr);
cout << "Value" << value << endl;
cout << endl;
return 0;
}
| true |
e70b8b8ced6db83687c08a81b85a3ec4e44cf0e3 | C++ | CrazyIEEE/algorithm | /OnlineJudge/LeetCode/第1个进度/143.重排链表.cpp | UTF-8 | 2,068 | 3.703125 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=143 lang=cpp
*
* [143] 重排链表
*
* https://leetcode-cn.com/problems/reorder-list/description/
*
* algorithms
* Medium (55.03%)
* Likes: 271
* Dislikes: 0
* Total Accepted: 33.8K
* Total Submissions: 60K
* Testcase Example: '[1,2,3,4]'
*
* 给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
* 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
*
* 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
*
* 示例 1:
*
* 给定链表 1->2->3->4, 重新排列为 1->4->2->3.
*
* 示例 2:
*
* 给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
*
*/
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
void reorderList(ListNode *head)
{
head = new ListNode(0, head);
ListNode *c = head, *cc = head;
while (cc->next)
{
c = c->next;
cc = cc->next;
if (cc->next)
cc = cc->next;
else
break;
}
cc = new ListNode();
while (c->next)
{
ListNode *t = c->next;
c->next = t->next;
t->next = cc->next;
cc->next = t;
}
c = head->next;
while (cc->next)
{
ListNode *t = cc->next;
cc->next = t->next;
t->next = c->next;
c->next = t;
c = c->next->next;
}
delete cc;
ListNode *t = head;
head = head->next;
delete t;
}
};
// @lc code=end
| true |
3de77a932bf6534f29bd09fb2c6fcca0808c7516 | C++ | zachdavids/Wolfenstein3D | /Source/Private/Camera.cpp | UTF-8 | 869 | 2.828125 | 3 | [] | no_license | #include "Camera.h"
#include "WindowManager.h"
#include <GLM/gtc/matrix_transform.hpp>
Camera::Camera(glm::vec3 const& position, glm::vec3 const& rotation)
{
m_Position = position;
m_Rotation = rotation;
}
void Camera::Move(glm::vec3 const& movement)
{
Translate(movement);
m_bViewHasChanged = true;
}
void Camera::Aim(float x)
{
Rotate(glm::vec3(0, x, 0));
m_bViewHasChanged = true;
}
glm::mat4& Camera::GetViewMatrix()
{
if (m_bViewHasChanged)
{
m_ViewMatrix = GetRotationMatrix() * glm::inverse(glm::translate(glm::mat4(), GetPosition()));
}
return m_ViewMatrix;
}
glm::mat4& Camera::GetProjectionMatrix()
{
if (m_bProjectionHasChanged)
{
float aspect_ratio = (float)(WindowManager::Get()->s_Width / WindowManager::Get()->s_Height);
m_ProjectionMatrix = glm::perspective(s_FOV, aspect_ratio, s_Near, s_Far);
}
return m_ProjectionMatrix;
} | true |
eba77525825858b481a33445cfacca081f259047 | C++ | Dongsu-h/BAEKJOON | /07. 함수/#15596.cpp | UTF-8 | 241 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
long long sum(std::vector<int> &a)
{
int count = a.size();
int sum_data = 0;
for (int i=0; i < count; i++)
sum_data += a.at(i);
return (long long)sum_data;
}
int main()
{
} | true |
0cae07a50ea6c3dd18596e61d7ba26888bb8b1b5 | C++ | arthurhauer/arno-fan-controller | /src/ArnoController.cpp | UTF-8 | 2,309 | 2.6875 | 3 | [] | no_license | #include "ArnoController.h"
ArnoController::ArnoController(byte pin, byte device) {
this->pin = pin;
this->device = device;
init();
} // ArnoController
int hex2int (char c) {
if (c >= '0' && c <= '9')
return c - '0' ;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
} // hex2int
void ArnoController::init() {
pinMode(pin, OUTPUT);
} // sendRaw
void ArnoController::setDevice(int device) {
this->device = device;
} // setDevice
void ArnoController::sendRaw (const char code[]) {
sendRaw (code, 3);
} // sendRaw
void ArnoController::sendRaw (const char code[], int repeat) {
init();
int length = strlen (code);
digitalWrite(pin, LOW);
delayMicroseconds(500);
//
for (int i=0; i<repeat; i++) {
for (int j=0; j<length; j++) {
int converted = hex2int (code [j]);
//
digitalWrite(pin, (converted & B1000) > 0 ? HIGH : LOW);
delayMicroseconds(500);
digitalWrite(pin, (converted & B0100) > 0 ? HIGH : LOW);
delayMicroseconds(500);
digitalWrite(pin, (converted & B0010) > 0 ? HIGH : LOW);
delayMicroseconds(500);
digitalWrite(pin, (converted & B0001) > 0 ? HIGH : LOW);
delayMicroseconds(500);
}
}
// Clear transmission
pinMode(pin, DISABLED);
} // sendRaw
void ArnoController::send(Command cmd) {
const char * code;
switch (cmd) {
default:
case LIGHT: code = light_code; break;
case FAN: code = fan_code; break;
case LESS: code = less_code; break;
case MORE: code = more_code; break;
case SLEEP: code = sleep_code; break;
case MODE: code = mode_code; break;
case TIMER: code = timer_code; break;
}
// Concatenate preffix and code
strcpy(buffer,preffix_code);
int device_code = (int)device;
strcat(buffer,((device_code & B1000) > 0 ? "7" : "1"));
strcat(buffer,((device_code & B0100) > 0 ? "7" : "1"));
strcat(buffer,((device_code & B0010) > 0 ? "7" : "1"));
strcat(buffer,((device_code & B0001) > 0 ? "7" : "1"));
strcat(buffer,code);
//
sendRaw (buffer);
} // send
| true |
f654efec6fe92a0d1c9940b7c4b8ad02e94e3963 | C++ | Ahn-Ssu/Class_DataStructure | /기말/L33_Graphs02.cpp | UTF-8 | 2,159 | 3.15625 | 3 | [] | no_license | /**
* < Spanning trees >
* Graph G의 spanning tree
* : G의 모든 vertex를 연결하는 Cycle이 없는 subgraph, Spanning tree는 n-1개의 edge를 갖는다.
* (모든 것을 연결'만' 수행)
*
* 1. 종류
* DFS spanning tree // serch 과정이랑 똑같음
* BFS spanning tree
* < Biconnected components >
* : articulation point를 갖지 않는 connected graph
*
* + Articulation point
* : 해당 vertex를 삭제 했을 떄, 원래의 graph가 두 개 이상의
* biconnected component로 분리되는 vertex
*
* < Minimum cost spanning tree >
* : Weighted(가중) graph에서 cost의 합이 최소인 spanning tree를 찾는 문제
*
* 1. that's Algorithm
* i) Kruskal's Algorithm
* : 전체 edge 집합을 cost 순서로 sort하고, cost 순서대로 edge를 판단
* ii) Prim's Algorithm
* : Start vertex에서 시작하여 현재 유지되고 있는 connected component와 연결된 edge를 고려
* iii) Sollin's Algorithm
* : 각 node를 개별 connected component로 고려하여, 한 개씩 edge를 선택하여 추가\
*
*
*
*
* I) Kruskal
* a. 전체 edge의 집합을 cost 순서로 sorting
* b. Cost 순서로, 해당 edge가 cycle을 이루지 않으면 선택 // 오름차순으로 선택, cycle 되면 버리고 다음꺼 수행
* c. (n-1)개의 edge가 선택될 때까지 반복
*
* II) Prim
* a. start vertex로 부터 시작
* b. 현재 구성되는 connected component와 (외부로) 연결된 edge 중에서 최소 cost edge를 선택
* c. (n-1)개의 edge가 선택될 때 까지 반복
*
* III) Sollin
* a. 각 vertex를 서로 다른 connected component로 고려
* b. 각 connected component에 대하여 최소 cost edge를 한 개씩 추가
* c. 전체가 한 개의 connected component가 되면 종료
*/ | true |
ceb67c579aa21d770a19b5ac30b729a9570d4217 | C++ | umer-amjad/Baby-Wolf | /Function.cpp | UTF-8 | 2,546 | 3.34375 | 3 | [
"MIT"
] | permissive | //
// Function.cpp
// BabyWolf
//
//
#include <algorithm>
#include "Function.hpp"
#include "Argument.hpp"
#include "Constant.hpp"
#include "Unary.hpp"
#include "Variadic.hpp"
Function::Function() : f(new Argument()) {}
Function::Function(double value) : f(new Constant(value)) {}
Function::Function(OperationType op, Function fn) : f(new Unary(op, fn)) {}
Function::Function(OperationType op, std::vector<Function> fns) : f(new Variadic(op, fns)) {}
const Function Function::simplify() const {
const Function simplified = this->wrap().flatten().collapse().flatten();
//userFunctions.push_back(simplified);
return simplified;
}
std::string Function::getName() const {
return name;
}
bool Function::setName(std::string name){
this->name = name;
auto userFnIter = userFunctions.find(name);
if (userFnIter != userFunctions.end()){
userFunctions.erase(userFnIter);
return true;
}
return false;
}
std::ostream& operator<<(std::ostream& o, const Function& fn){
std::string name = fn.name;
if (name == ""){
name = "unnamed";
}
if (AbstractFunction::opts.prefix){
o << "(define (" << name << " x) " << fn.getPrefixString() << ")\n";
}
if (AbstractFunction::opts.infix){
o << name << "(x) = " << fn.getInfixString() << '\n';
}
return o;
}
//compare simplified functions
bool operator<(const Function& f1, const Function& f2){
if (f1.getType() != f2.getType()) {
return f1.getType() < f2.getType();
} else if (f1.getType() == FunctionType::CONSTANT) {
return f1.getValue() < f2.getValue();
} else if (f1.getType() == FunctionType::ARGUMENT) {
return false; //arguments are always equal
} else if (f1.getType() == FunctionType::UNARY) {
if (f1.getOperation() == f2.getOperation()) {
return f1.getFns().first < f2.getFns().first;
} else {
return f1.getOperation() < f2.getOperation();
}
} else if (f1.getType() == FunctionType::VARIADIC) {
if (f1.getOperation() == f2.getOperation()) {
//lexicographical comparison
const std::vector<Function>& fns1 = f1.getFns().second;
const std::vector<Function>& fns2 = f2.getFns().second;
return std::lexicographical_compare(fns1.begin(), fns1.end(), fns2.begin(), fns2.end());
} else {
return f1.getOperation() < f2.getOperation();
}
}
} | true |
4af7658b6db33b4c8b3d5a24bf19cf24c98473fe | C++ | bubbercn/LeetCode | /C++/Solved/234_PalindromeLinkedList.h | UTF-8 | 1,931 | 3.625 | 4 | [] | no_license | #pragma once
#include "Common.h"
// Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool isPalindrome(ListNode *head)
{
if (!head || !head->next)
return true;
ListNode *fast = head;
ListNode *slow = head;
while (fast->next)
{
fast = fast->next;
if (!fast->next)
{
break;
}
else
{
fast = fast->next;
}
slow = slow->next;
}
ListNode* tempHead = reverseList(slow->next);
bool result = true;
for (fast = head, slow = tempHead; slow != nullptr; slow = slow->next, fast = fast->next)
{
if (fast->val != slow->val)
{
result = false;
break;
}
}
reverseList(tempHead);
return result;
}
ListNode *reverseList(ListNode *head)
{
if (head == nullptr)
return nullptr;
stack<ListNode *> nodeStack;
while (head->next != nullptr)
{
nodeStack.emplace(head);
head = head->next;
}
ListNode *curNode = head;
while (!nodeStack.empty())
{
curNode->next = nodeStack.top();
curNode = curNode->next;
nodeStack.pop();
}
curNode->next = nullptr;
return head;
}
};
void Test()
{
Solution solution;
vector<int> values = {1,2,2,1};
vector<unique_ptr<ListNode>> nodes;
for (auto i = values.begin(); i != values.end(); i++)
{
nodes.emplace_back(new ListNode(*i));
}
for (int i = 0; i < nodes.size() - 1; i++)
{
nodes[i]->next = nodes[i+1].get();
}
solution.isPalindrome(nodes[0].get());
} | true |
423ad96a597fb48d04425a73db3e6395b1acb339 | C++ | ck-leo/c_plus_plus | /my_exp/main.cpp | UTF-8 | 343 | 2.984375 | 3 | [] | no_license | #include "MyExp.hpp"
#include <iostream>
using namespace std;
int main()
{
try
{
string a("MyExp2");
throw MyExp2(a);
}
catch (const MyExp2 & e)
{
cout << e.what() << endl;
}
catch (const exception& e)
{
cout << e.what() << endl;
}
return 0;
} | true |
6a2efe3b7841b9a8a97db0daed3da6d76a2b2f99 | C++ | qinzhiqiang163/RayTraceGroundUp | /include/light/PointLight.h | UTF-8 | 2,521 | 2.90625 | 3 | [] | no_license | #ifndef POINTLIGHT_H
#define POINTLIGHT_H
#include "Light.h"
#include "Vector3D.h"
#include "RGBColor.h"
#include "World.h" // you will need this later on for shadows
#include "ShadeRec.h"
class PointLight : public Light
{
public:
PointLight(void);
PointLight(const PointLight& pl);
virtual Light*
clone(void) const;
PointLight&
operator= (const PointLight& rhs);
virtual
~PointLight(void);
void
scale_radiance(const float b);
void
set_color(const float c);
void
set_color(const RGBColor& c);
void
set_color(const float r, const float g, const float b);
void
set_location(Point3D l);
void
set_location(float lx, float ly, float lz);
virtual Vector3D
get_direction(ShadeRec& sr);
virtual RGBColor
L(ShadeRec& sr);
virtual bool
in_shadow(const Ray& ray, const ShadeRec& sr) const;
virtual void
set_cast_shadow(bool cs);
virtual bool
get_cast_shadow(void);
// public:
// bool cast_shadow;
private:
float ls;
RGBColor color;
Point3D location;
};
// inlined access functions
// ------------------------------------------------------------------------------- scale_radiance
inline void
PointLight::scale_radiance(const float b) {
ls = b;
}
// ------------------------------------------------------------------------------- set_color
inline void
PointLight::set_color(const float c) {
color.r = c; color.g = c; color.b = c;
}
// ------------------------------------------------------------------------------- set_color
inline void
PointLight::set_color(const RGBColor& c) {
color = c;
}
// ------------------------------------------------------------------------------- set_color
inline void
PointLight::set_color(const float r, const float g, const float b) {
color.r = r; color.g = g; color.b = b;
}
// ---------------------------------------------------------------------- set_direction
inline void
PointLight::set_location(Point3D l) {
location = l;
}
// ---------------------------------------------------------------------- set_direction
inline void
PointLight::set_location(float lx, float ly, float lz) {
location.x = lx; location.y = ly; location.z = lz;
}
// ---------------------------------------------------------------------- set_cast_shadow
inline void
PointLight::set_cast_shadow(bool cs) {
cast_shadow = cs;
}
#endif // POINTLIGHT_H
| true |
e5dec873880f8e71ad0bca308f6484e30db93e43 | C++ | jiewaikexue/linux | /第三单元全部结束45个文件夹/3_test/314/314.cpp | UTF-8 | 312 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
vector<int>vInt;
int i;
cout << "输入Q退出" << endl;
while (cin >> i)
{
if (i == 'q')
{
break;
}
vInt.push_back(i);
}
for (auto a : vInt)
cout << a;
return 0;
}
| true |
43b5bf7070304eb31fec3e4dbc50259beb192f8b | C++ | AnkangH/LeetCode | /二分查找/035. 搜索插入位置.cpp | UTF-8 | 1,263 | 3.515625 | 4 | [] | no_license | /*
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int size=nums.size();
int l=0,r=size-1;//左右指针
while(l<=r)//搜索时 为防止跳过 左右指针最后一次可相同
{
int mid=(r-l)/2+l;//向下取整 每次mid都在靠左一侧
if(nums[mid]<target)
l=mid+1;
else if(nums[mid]>target)
r=mid-1;
else
return mid;//若找到target 返回索引
}
nums.emplace(nums.begin()+l,target);//若未找到target 在最后搜索位置插入target
return l;//返回插入的索引
}
};
| true |
874933253a9a84fdea5f96427557b1d53079e622 | C++ | ExayDX/OpenGL4Viewer | /OpenGL4Viewer/OpenGL4Viewer/Viewer.h | UTF-8 | 1,240 | 2.609375 | 3 | [] | no_license | #ifndef VIEWER_H
#define VIEWER_H
#include <GLFW/glfw3.h>
#include "GLM/glm/glm.hpp"
#include "GLM/glm/gtc/matrix_transform.hpp"
// Forward declarations
class Camera;
class Scene;
class Viewer
{
public :
void error_callback_impl(int error, const char* description);
void key_callback_impl(GLFWwindow* window, int key, int scancode, int action, int mods);
void window_size_callback_impl(GLFWwindow* window, int width, int height);
void mouse_callback_impl(GLFWwindow* window, double xpos, double ypos);
void mouse_button_callback_impl(GLFWwindow* window, int button, int action, int mods);
void scroll_callback_impl(GLFWwindow* window, double xoffset, double yoffset);
static Viewer* getInstance();
void Destroy();
void loop();
private :
// Ctors/Dtors
Viewer();
~Viewer();
void createWindow();
void setCallbacks();
void moveCamera();
void setupViewport();
static Viewer* m_instance;
GLFWwindow* m_window;
Camera* m_camera;
Scene* m_scene;
bool m_keys[1024]; // All the keys that can be pressed
glm::vec2 m_lastMousePosition;
GLfloat m_deltaTime;
GLfloat m_lastFrameTime;
bool m_firstClick;
GLfloat m_width;
GLfloat m_height;
bool m_wireFrameEnabled;
bool m_mouseIsClicked;
};
#endif
| true |
612811b42a14016a1ba9ac8bb4ed858960b8e011 | C++ | rykermcintyre/DataStructuresFinalProject | /testsepchain.cpp | UTF-8 | 531 | 2.609375 | 3 | [] | no_license | #include "project.h"
int main() {
SepChain sc;
string keys[] = {"k", "kieran", "ryker", "kiernan", "r", "reichurr", "bob"};
string vals[] = {"kieran", "ryker", "kiernan", "reichurr", "rayyan", "q", "kie"};
for (int n = 0; n < 7; n++) {
sc.insert(keys[n], vals[n]);
}
for (int n = 0; n < 6; n++) {
Entry s = sc.search(keys[n]);
if (s == EMPTY) {
cout << "Error: " << keys[n] << " not found in table!" << endl;
return 1;
}
}
sc.dump(std::cout, DUMP_KEY_VALUE);
return 0;
}
| true |
d398887c4be4bd90f28fd411ee7fbed9989deb9c | C++ | Barrymantelo/Attack-of-the-Unidead | /level.cpp | UTF-8 | 513 | 2.671875 | 3 | [] | no_license | #include "level.h"
#include "globals.h"
#include <SOIL.h>
void Map::create(int width, int height) {
this->width = width;
this->height = height;
map = new int[width * height];
}
void Map::load(char* path) {
}
void Map::save(char* path) {
}
void Map::draw(int xPos, int yPos) {
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
drawTexture(tiles[map[x + y * width]], (x * TILE_SIZE) + xPos, (y * TILE_SIZE) + yPos);
}
void Map::dispose() {
delete map;
}
| true |
25eb5bb35dfcfaaba3893251a35022b56000d068 | C++ | RaniAgus/ayed-tp-2018-mundial | /AED-D20-PARTE2/ejercicio-2-3/codigo.cpp | UTF-8 | 7,427 | 2.875 | 3 | [] | no_license | #include "../utils/utils.hpp"
#include "listas.hpp"
#include "estructuras.hpp"
#include "arboles.hpp"
#define CANTEQUIPOS 32
#define CANTPARTIDOS 7
#define imprimirFecha(fecha) \
(fecha) % 100 << "/" << ((fecha) / 100) % 100 << "/" << (fecha) / 10000
Nodo<Jugador> *partidos[CANTEQUIPOS][CANTPARTIDOS] = {NULL};
void liberarPartidos();
void cargarArchivo(const char *ruta);
Gol leerSiguiente(FILE *f, Gol anterior, int *partido, int *equipo);
void golesPorEquipo();
void goleadores();
Nodo<Jugador> *agregarGolesAJugador(Nodo<Jugador> *jugadores, Jugador jug);
void goleadoresPorFecha();
Nodo<Fecha> *agregarJugadorAFecha(Nodo<Fecha> *fechas, Jugador jugador);
int main()
{
int menu = 1;
while (true)
{
switch (menu)
{
case 1:
liberarPartidos();
cargarArchivo("../goles.dat");
break;
case 2:
golesPorEquipo();
break;
case 3:
goleadores();
break;
case 4:
goleadoresPorFecha();
break;
case 0:
liberarPartidos();
return 0;
}
std::cout << "GOLES DEL MUNDIAL 2018" << std::endl;
std::cout << "1: Volver a cargar los datos" << std::endl;
std::cout << "2: Ver cantidad de goles por equipo" << std::endl;
std::cout << "3: Ver tabla de goleadores" << std::endl;
std::cout << "4: Ver los goleadores de cada fecha" << std::endl;
std::cout << "0: Salir" << std::endl;
std::cin >> menu;
system("clear");
}
return 0;
}
/**
* @NAME liberarPartidos
* @DESC Libera la matriz global de partidos y su contenido
*/
void liberarPartidos()
{
for (int i = 0; i < CANTEQUIPOS; i++)
{
for (int j = 0; j < CANTPARTIDOS; j++)
{
liberarLista<Jugador>(partidos[i][j]);
partidos[i][j] = NULL;
}
}
}
/**
* @NAME cargarArchivo
* @DESC Carga la matriz global de partidos a partir de un archivo de estructuras
* Gol, ordenado por equipo y por partido.
*/
void cargarArchivo(const char *ruta)
{
liberarPartidos();
int partido = 0, equipo = 0;
FILE *f = open(ruta, "rb+");
Gol lectura = read<Gol>(f);
while (!feof(f))
{
if (strcmp(lectura.nombre_jugador, ""))
{
Nodo<Jugador> *aux = buscarEnLista<Jugador, Gol>(partidos[equipo][partido], lectura, criterioJugadorGol);
if (aux == NULL)
{
agregarNodo<Jugador>(partidos[equipo][partido], crearJugador(lectura));
}
else
{
aux->info.goles++;
}
}
lectura = leerSiguiente(f, lectura, &partido, &equipo);
}
fclose(f);
std::cout << "Datos cargados correctamente." << std::endl;
}
/**
* @NAME leerSiguiente
* @DESC Lee el siguiente Gol desde el archivo y lo compara con la lectura
* anterior para verificar en dónde ubicarlo
*/
Gol leerSiguiente(FILE *f, Gol anterior, int *partido, int *equipo)
{
Gol lectura = read<Gol>(f);
if (anterior.cod_equipo != lectura.cod_equipo)
{
*partido = 0;
(*equipo)++;
}
else if (anterior.id_partido != lectura.id_partido)
{
(*partido)++;
}
return lectura;
}
/**
* @NAME golesPorEquipo
* @DESC A partir de la matriz cargada, obtiene la cantidad de goles que convirtió
* un cada equipo para luego guardarlo en un árbol, para luego imprimir por pantalla
* el resultado obtenido.
*/
void golesPorEquipo()
{
Arbol<Equipo> *raiz = NULL;
for (int equipo = 0; equipo < CANTEQUIPOS; equipo++)
{
int goles = 0;
for (int partido = 0; partido < CANTPARTIDOS; partido++)
{
for (Nodo<Jugador> *jug = partidos[equipo][partido]; jug != NULL; jug = jug->sig)
{
goles += jug->info.goles;
}
}
insertarEnArbol<Equipo>(raiz, crearEquipo(equipo, goles), criterioEquipo);
}
std::cout << std::left << std::setw(15) << "PAIS" << std::setw(5) << "GOLES" << std::endl;
recorrerArbolInorden<Equipo>(raiz, [](Equipo e) -> void {
std::cout << std::left << std::setw(15) << e.nombre << std::setw(5) << e.goles << std::endl;
});
liberarArbol(raiz);
}
/**
* @NAME goleadores
* @DESC A partir de la matriz cargada, obtiene una lista de jugadores ordenada
* según la cantidad de goles convertidos (separando los goles en contra), para luego
* imprimir por pantalla el resultado obtenido.
*/
void goleadores()
{
Nodo<Jugador> *jugadores = NULL;
int enContra = 0;
for (int equipo = 0; equipo < CANTEQUIPOS; equipo++)
{
for (int partido = 0; partido < CANTPARTIDOS; partido++)
{
for (Nodo<Jugador> *jug = partidos[equipo][partido]; jug != NULL; jug = jug->sig)
{
if (!esEnContra(jug->info))
{
jugadores = agregarGolesAJugador(jugadores, jug->info);
}
else
{
enContra++;
}
}
}
}
std::cout << std::left << std::setw(20) << "JUGADOR" << std::setw(5) << "GOLES" << std::endl;
for (Nodo<Jugador> *jug = jugadores; jug != NULL; jug = jug->sig)
{
std::cout << std::left << std::setw(20) << jug->info.nombre_jugador << std::setw(3) << jug->info.goles << std::endl;
}
std::cout << std::left << std::setw(20) << "GOLES EN CONTRA" << enContra << std::endl;
liberarLista<Jugador>(jugadores);
}
/**
* @NAME agregarGolesAJugador
* @DESC Dado un jugador, lo busca en la lista recibida por parámetro.
* En caso de encontrarlo, le suma la cantidad de goles y vuelve a ordenar la
* lista. Sino, crea uno nuevo y lo agrega a la misma.
*/
Nodo<Jugador> *agregarGolesAJugador(Nodo<Jugador> *jugadores, Jugador jug)
{
Nodo<Jugador> *jugEnc = buscarEnLista<Jugador, Jugador>(jugadores, jug, criterioJugador);
if (jugEnc == NULL)
{
agregarNodo<Jugador>(jugadores, jug);
}
else
{
jugEnc->info.goles += jug.goles;
ordenarLista<Jugador>(jugadores, criterioGoles);
}
return jugadores;
}
/**
* @NAME goleadoresPorFecha
* @DESC A partir de la matriz cargada, obtiene una lista de fechas, cada una con
* una lista de los jugadores que convirtieron ese día. Luego, imprime por pantalla
* el resultado obtenido.
*/
void goleadoresPorFecha()
{
Nodo<Fecha> *fechas = NULL;
for (int partido = 0; partido < CANTPARTIDOS; partido++)
{
for (int equipo = 0; equipo < CANTEQUIPOS; equipo++)
{
for (Nodo<Jugador> *jug = partidos[equipo][partido]; jug != NULL; jug = jug->sig)
{
fechas = agregarJugadorAFecha(fechas, jug->info);
}
}
}
for (Nodo<Fecha> *aux = fechas; aux != NULL; aux = aux->sig)
{
std::cout << "GOLES DEL DIA " << imprimirFecha(aux->info.fecha) << ": " << std::endl;
std::cout << std::left << std::setw(20) << "JUGADOR" << std::setw(5) << "GOLES" << std::endl;
for (Nodo<Jugador> *jug = aux->info.jugadores; jug != NULL; jug = jug->sig)
{
std::cout << std::left << std::setw(20) << jug->info.nombre_jugador << std::setw(5) << jug->info.goles << std::endl;
}
}
liberarLista<Fecha>(fechas);
}
/**
* @NAME agregarJugadorAFecha
* @DESC Dado un jugador, busca la fecha en la que convirtió en la lista recibida
* por parámetro. En caso de encontrarla, inserta al jugador según la cantidad de
* goles convertidos ese día. Sino, crea una nueva con el jugador en cuestión y la
* agrega a la misma.
*/
Nodo<Fecha> *agregarJugadorAFecha(Nodo<Fecha> *fechas, Jugador jugador)
{
Nodo<Fecha> *encontrado = buscarEnLista<Fecha, Jugador>(fechas, jugador, criterioFechaJugador);
if (encontrado != NULL)
insertarOrdenado<Jugador>(encontrado->info.jugadores, jugador, criterioGoles);
else
insertarOrdenado<Fecha>(fechas, crearFecha(jugador), criterioFecha);
return fechas;
} | true |
1b89fa8648a6d5c15d88ecd5d8f9f5e7aad0ce16 | C++ | Dvmenasalvas/EDA | /Juez/1er cuatri/VA-04.cpp | ISO-8859-1 | 2,035 | 3.5 | 4 | [] | no_license | // Daniel Valverde Menasalvas
// Comentario general sobre la solucin,
// explicando cmo se resuelve el problema
#include <iostream>
#include <vector>
using namespace std;
// funcin que resuelve el problema
// comentario sobre el coste, O(f(N)), donde N es ...
void funcionariosVA(int k, int &valor, int &mejorValor, vector<vector<int>> const & funcionarios, vector<bool> &asignado, vector<int> const & minimos, int &cotaInferior) {
for (int j = 0; j < funcionarios.size(); j++) {
if (!asignado[j]) {
valor += funcionarios[k][j];
cotaInferior -= minimos[j];
if (valor + cotaInferior < mejorValor) {
//Marcamos
asignado[j] = true;
//Tratamos
if (k == funcionarios.size() - 1) mejorValor = valor;
else funcionariosVA(k + 1, valor, mejorValor, funcionarios, asignado, minimos, cotaInferior);
//Desmarcamos
asignado[j] = false;
}
cotaInferior += minimos[j];
valor -= funcionarios[k][j];
}
}
}
// Resuelve un caso de prueba, leyendo de la entrada la
// configuracin, y escribiendo la respuesta
bool resuelveCaso() {
int N;
cin >> N;
vector<vector<int>> funcionarios;
for (int i = 0; i < N; i++) {
vector<int> funcionario;
int entrada;
for (int j = 0; j < N; j++) {
cin >> entrada;
funcionario.push_back(entrada);
}
funcionarios.push_back(funcionario);
}
if (N == 0) return false;
vector<bool> asignado(N);
int valor = 0, mejorValor = 0;
for (int i = 0; i < N; i++) {
asignado[i] = false; //Ponemos asignados en false
mejorValor += funcionarios[i][i]; //Damos un valor factible para poder comparar desde el principio
}
vector<int> minimos;
int cotaInferior = 0;
for (int j = 0; j < N; j++) {
int minimo = funcionarios[0][j];
for (int i = 1; i < N; i++)
if (funcionarios[i][j] < minimo) minimo = funcionarios[i][j];
minimos.push_back(minimo);
cotaInferior += minimo;
}
funcionariosVA(0, valor, mejorValor, funcionarios, asignado, minimos, cotaInferior);
cout << mejorValor << '\n';
return true;
}
int main() {
while (resuelveCaso());
return 0;
} | true |
572de3110e7fad33906133b17bb945bb4c453661 | C++ | RoutingKit/RoutingKit | /src/test_id_set_queue.cpp | UTF-8 | 1,306 | 3.015625 | 3 | [
"BSD-2-Clause"
] | permissive | #include <routingkit/id_set_queue.h>
#include "expect.h"
#include <iostream>
using namespace RoutingKit;
using namespace std;
int main(){
try{
IDSetMinQueue q(100);
EXPECT_CMP(q.id_count(), ==, 100);
EXPECT(q.empty());
q.push(3);
q.push(8);
q.push(77);
q.push(2);
q.push(15);
q.push(66);
EXPECT(q.contains(77));
EXPECT(!q.contains(78));
EXPECT_CMP(q.peek(), ==, 2); EXPECT_CMP(q.pop(), ==, 2);
EXPECT_CMP(q.peek(), ==, 3); EXPECT_CMP(q.pop(), ==, 3);
EXPECT_CMP(q.peek(), ==, 8); EXPECT_CMP(q.pop(), ==, 8);
EXPECT_CMP(q.peek(), ==, 15); EXPECT_CMP(q.pop(), ==, 15);
EXPECT_CMP(q.peek(), ==, 66); EXPECT_CMP(q.pop(), ==, 66);
EXPECT_CMP(q.peek(), ==, 77); EXPECT_CMP(q.pop(), ==, 77);
EXPECT(q.empty());
q.push(77);
q.push(2);
q.push(15);
EXPECT_CMP(q.peek(), ==, 2); EXPECT_CMP(q.pop(), ==, 2);
EXPECT_CMP(q.peek(), ==, 15); EXPECT_CMP(q.pop(), ==, 15);
q.push(3);
q.push(8);
EXPECT_CMP(q.peek(), ==, 3); EXPECT_CMP(q.pop(), ==, 3);
EXPECT_CMP(q.peek(), ==, 8); EXPECT_CMP(q.pop(), ==, 8);
q.clear();
EXPECT(q.empty());
q = IDSetMinQueue(5);
q.push(4);
q.pop();
cout << "All finished" << endl;
}catch(std::exception&err){
cout << "exception" << ":" << err.what() << endl;
return 1;
}
return expect_failed;
}
| true |
838b39c9cc07e698269514a2f81d38b0d215a98b | C++ | intolerants/str | /beagleSocket/setDate.cpp | UTF-8 | 1,434 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define YEAR_DEPRECATED 2015
void manual(void){
char date[30] /*= "1 May 2016 19:30:00"*/, cmd[40], c;
while((c = getchar()) != '\n' && c != EOF); // clear buffer
printf("Entre com a hora atual no formato (1 May 2016 19:30:00): \n");
if(scanf ("%[^\n]%*c", date)); // get string with spaces
sprintf(cmd, "date --set \"%s\"", date);
// printf("%s\n",cmd);
if(system(cmd));
}
void automatic(void){
printf("Aguardando servidor...\n");
system("ntpdate-debian");
}
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
int currentYear(void) {
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
return (int)tstruct.tm_year+1900;
}
void checkDate(void){
if(system("clear"));
if (currentYear() < YEAR_DEPRECATED)
{
char op = '\0';
printf("Atualizar hora do sistema.\nEscolha uma opcao:\n(a)utomatico\n(m)anual\n(n)ao atualizar\n");
while(op == '\0'){
if(scanf("%c", &op));
if(system("clear"));
switch(op){
case 'a':
automatic();
break;
case 'm':
manual();
break;
case 'n':
break;
default:
op = '\0';
}
}
} else {
printf("System date:\n");
if(system("date"));
printf("\n");
}
}
int main(int argc, char const *argv[])
{
checkDate();
return 0;
} | true |
359bbc8db6bbaf08f3f73af54e09347f0cdf09ca | C++ | hjmediastudios/Top-Down-Game-Framework | /src/Input.cpp | UTF-8 | 1,195 | 3 | 3 | [] | no_license | #include "../include/main.hpp"
Input::Input()
{
//Create memory
memset(&keyboardState, 0, sizeof (ALLEGRO_KEYBOARD_STATE));
}
void Input::poll()
{
al_get_keyboard_state(&keyboardState);
}
float Input::get_lr()
{
float rValue = 0.0;
if (al_key_down(&keyboardState, ALLEGRO_KEY_LEFT) && !al_key_down(&keyboardState, ALLEGRO_KEY_RIGHT))
rValue = -1.0;
else if (al_key_down(&keyboardState, ALLEGRO_KEY_RIGHT) && !al_key_down(&keyboardState, ALLEGRO_KEY_LEFT))
rValue = 1.0;
else
rValue = 0.0;
std::cout << "Input state: " << rValue << std::endl;
return rValue;
}
float Input::get_ud()
{
float uValue = 0.0;
if (al_key_down(&keyboardState, ALLEGRO_KEY_DOWN))
uValue -= 1.0;
if (al_key_down(&keyboardState, ALLEGRO_KEY_UP))
uValue += 1.0;
return uValue;
}
float Input::get_ad()
{
if (al_key_down(&keyboardState, ALLEGRO_KEY_A))
return -1.0;
if (al_key_down(&keyboardState, ALLEGRO_KEY_D))
return 1.0;
}
bool Input::get_esc()
{
return al_key_down(&keyboardState, ALLEGRO_KEY_ESCAPE);
}
bool Input::get_space()
{
return al_key_down(&keyboardState, ALLEGRO_KEY_SPACE);
}
| true |
eb5e0f2dcf7db040543a946b24a33db3f9630acc | C++ | jacob-hegna/yasc | /src/ast/number.h | UTF-8 | 3,077 | 3.5 | 4 | [] | no_license | #ifndef __YASC_AST_NUMBER_H_
#define __YASC_AST_NUMBER_H_
#include <memory>
#include <numeric>
#include <complex>
#include <iostream>
namespace yasc {
template<typename T>
using fraction_t = std::pair<T, T>;
template<typename T>
std::ostream& operator<<(std::ostream& o, fraction_t<T> const& f) {
o << f.first << "/" << f.second;
return o;
}
template<typename T>
fraction_t<T> operator+(fraction_t<T> const& lhs, fraction_t<T> const& rhs) {
fraction_t<T> ret{};
if(lhs.second == rhs.second) {
ret.second = lhs.second;
ret.first = rhs.first + lhs.first;
} else {
ret.second = std::lcm(lhs.second, rhs.second);
ret.first = (lhs.first * ret.second / lhs.second)
+ (rhs.first * ret.second / rhs.second);
}
return ret;
}
template<typename T>
fraction_t<T> operator-(fraction_t<T> const& f) {
fraction_t<T> ret{f};
ret.second *= -1;
return ret;
}
template<typename T>
fraction_t<T> operator-(fraction_t<T> const& lhs, fraction_t<T> const& rhs) {
return lhs + (-rhs);
}
template<typename T>
fraction_t<T> operator*(fraction_t<T> const& lhs, fraction_t<T> const& rhs) {
fraction_t<T> ret{lhs};
ret.first *= rhs.first;
ret.second *= rhs.second;
return ret;
}
template<typename T>
fraction_t<T> operator/(fraction_t<T> const& lhs, fraction_t<T> const& rhs) {
fraction_t<T> ret{lhs};
ret.first *= rhs.second;
ret.second *= rhs.first;
}
template<typename T>
class Number : public Value {
public:
using Ptr = std::shared_ptr<Number>;
constexpr Number()
: Value(Value::Type::Number)
, val_{}
{}
constexpr explicit Number(T val)
: Value(Value::Type::Number)
, val_{val}
{}
Number(Number<T> const& num)
: Value(Value::Type::Number)
, val_{num.get()}
{}
void set(T val) {
val_ = val;
}
T get() const {
return val_;
}
Number<T> operator+(Number<T> const& rhs) const { return Number(val_ + rhs.get()); }
Number<T> operator-(Number<T> const& rhs) const { return Number(val_ - rhs.get()); }
Number<T> operator*(Number<T> const& rhs) const { return Number(val_ * rhs.get()); }
Number<T> operator/(Number<T> const& rhs) const { return Number(val_ / rhs.get()); }
Number<T>& operator=(Number<T> const&) = default;
Number<T>& operator=(Number<T>&&) = default;
std::ostream& print(std::ostream& o) const override {
o << get();
return o;
}
private:
T val_;
};
using Complex = Number<std::complex<double>>;
using Real = Number<double>;
using Rational = Number<fraction_t<int>>;
using Integer = Number<int>;
} // end of namespace yasc
#endif // __YASC_AST_NUMBER_H_
| true |
158a290011e79baa7671132736ca51c651aa76b3 | C++ | rogrhrh/3DGameProgramming_2016 | /CodeCompleteExample/CodeCompleteExample_Step6_DrawAll/KCharacter.h | UTF-8 | 2,010 | 2.65625 | 3 | [] | no_license |
#pragma once
#include "KCharacterBase.h"
#include <memory>
#include "KVector.h"
class KCharacter;
typedef std::shared_ptr<KCharacter> KCharacterPtr;
typedef std::weak_ptr<KCharacter> KCharacterWeakPtr;
class KCharacter : public KCharacterBase
{
public:
KCharacter()
: m_dwHp( 0 )
, m_dwCharacterDataStamp( 0 )
{
m_pos = KVector( 0, 0, 0 );
m_velocity = KVector( 100, 100, 0 );
}
void SetCharacterManagerIndex( int iIndex_ );
int GetCharacterManagerIndex() const;
virtual void OnFrameMove( float fElapsedTime_ ) override;
virtual void OnFrameRender( HDC hdc_, float fElaspedTime_ ) override;
DWORD GetHp() const { return m_dwHp; }
void SetHp( DWORD dwNewHp_ )
{
m_dwHp = dwNewHp_;
m_dwCharacterDataStamp += 1;
}//SetHp()
DWORD GetCharacterDataStamp() const { return m_dwCharacterDataStamp; }
KVector GetPos() const { return m_pos; }
void SetPos( const KVector& pnt_ ) { m_pos = pnt_; }
KVector GetVelocity() const { return m_velocity; }
void SetVelocity( const KVector& dir_ ) { m_velocity = dir_; }
//{{ step4
KVector GetAcceleration() const { return m_acceleration; }
void SetAcceleration( const KVector& accel ) { m_acceleration = accel; }
//}} step4
private:
int m_iCharacterManagerIndex;
DWORD m_dwHp;
DWORD m_dwCharacterDataStamp;
KVector m_pos;
KVector m_velocity;
//{{ step4
KVector m_acceleration;
//}} step4
};//class KCharacter : public KCharacterBase
| true |
1d44c18f6c69cd8b5f5ad0db2b52190c2f84e096 | C++ | townboy/acm-algorithm | /HDOJcode/1022 2012-02-27 21 49 22.cpp | UTF-8 | 1,570 | 2.515625 | 3 | [] | no_license | ******************************
Author : townboy
Submit time : 2012-02-27 21:49:22
Judge Status : Accepted
HDOJ Runid : 5426032
Problem id : 1022
Exe.time : 0MS
Exe.memory : 208K
https://github.com/townboy
******************************
#include<stdio.h>
int top,j,stack[10000],num,tai[20000],t;
char o1[10000],o2[10000];
void xiao(int x,int y)
{
if(x==y)
{
tai[t]=-1;
t++;
j++;
top--;
if(-1==top)
{
return;
}
xiao(stack[top],o2[j]-'0');
}
}
int check()
{
int i;
top=-1;
j=0;
t=0;
for(i=0;i<num;i++)
{
if(8==top)
{
return 0;
}
tai[t]=1;
t++;
top++;
stack[top]=o1[i]-'0';
xiao(stack[top],o2[j]-'0');
}
if(-1==top)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int i;
while(scanf("%d",&num)!=EOF)
{
scanf("%s%s",o1,o2);
if(1==check())
{
printf("Yes.\n");
for(i=0;i<2*num;i++)
{
if(1==tai[i])
{
printf("in\n");
}
else
{
printf("out\n");
}
}
printf("FINISH\n");
}
else
{
printf("No.\n");
printf("FINISH\n");
}
}
return 0;
} | true |
250324a55333d04030bde348c285333066e09464 | C++ | chrisliu/BidirectedGraphGPU | /tests/serialization/serialization_test.cpp | UTF-8 | 1,179 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include "../../src/BidirectedGraph.hpp"
using namespace std;
int main(int argc, char* argv[]) {
string filename = argv[argc - 1];
ifstream json_file(filename, ifstream::binary);
BidirectedGraph g;
bool ret = g.deserialize(json_file);
cout << (ret ? "Is" : "Isn't") << " a success!" << endl;
g.for_each_handle([&](const handle_t& handle) {
bool printed = false;
cout << "Node " << g.get_id(handle) << " left nodes: ";
g.follow_edges(handle, true, [&](const handle_t& child_handle) {
cout << g.get_id(child_handle) << ", ";
printed = true;
});
if (printed) cout << "\b\b ";
cout << endl;
printed = false;
cout << "Node " << g.get_id(handle) << " right nodes: ";
g.follow_edges(handle, false, [&](const handle_t& child_handle) {
cout << g.get_id(child_handle) << ", ";
printed = true;
});
if (printed) cout << "\b\b ";
cout << endl;
});
ofstream out_file("test.json");
g.serialize(out_file);
out_file.close();
return 0;
} | true |
a781f6349b55241bce558c2975ad5654935cd033 | C++ | AverJing/LeetCode | /LeetCode/PointToOffer/CH06/Ex38GetNumberCountOfK.cpp | UTF-8 | 1,353 | 3.578125 | 4 | [] | no_license | /*
*
*
*@author: Aver Jing
*@description:
*@date:
*
*
*/
#include <iostream>
#include <vector>
using std::vector;
class Solution {
public:
int GetNumberOfK(vector<int>& data, int k) {
if (data.empty()) return 0;
int first = GetFirstKey(data, k, 0, data.size() - 1);
int end = GetLastKey(data, k, 0, data.size() - 1);
if (first > -1 && end > -1)
return end - first + 1;
return 0;
}
private:
int GetFirstKey(vector<int>& data, int k, int start, int end) {
if (start > end) return -1;
int middle = (start + end) / 2;
if (data[middle] == k) {
if (middle > 0 && data[middle - 1] != k || middle == 0) return middle;
else
end = middle - 1;
}
else if (data[middle] > k) {
end = middle - 1;
}
else
start = middle + 1;
return GetFirstKey(data, k, start, end);
}
int GetLastKey(vector<int>& data, int k, int start, int end) {
if (start > end) return -1;
int middle = (start + end) / 2;
if (data[middle] == k) {
if (middle < data.size()-1 && data[middle + 1] != k || middle == data.size() - 1) return middle;
else
start = middle + 1;
}
else if (data[middle] > k) {
end = middle - 1;
}
else
start = middle + 1;
return GetLastKey(data, k, start, end);
}
};
int main(){
vector<int> ivec{ 1,2,3,4,4,4,4,4,5,6,7 };
Solution s;
std::cout << s.GetNumberOfK(ivec, 4);
} | true |
23b74f270ba2203d9fcee78e71402ecc8ce68722 | C++ | federicopratto/Algoritmos-y-Programacion-2---TP-1 | /1- Programa/tablero.h | UTF-8 | 2,136 | 3.03125 | 3 | [
"MIT"
] | permissive |
#ifndef TABLERO_H_
#define TABLERO_H_
#include <iostream>
using std::cout;
using std::endl;
/*
* Esta función se encarga de inicializar con el valor '-'
* todas los casilleros del tablero
*/
void inicializarTablero(char tablero[10][10]);
/*
* Esta función revisa si hay espacio disponible para agregar
* fichas a una columna del tablero.
*/
bool columnaLlena(int columna, char tablero[10][10]);
/*
* Esta función se encarga de guardar la ultima ficha ingresada en
* el tablero, buscando la fila que le corresponda en base a la
* columna elegida por el usuario.
*/
void guardarUltimaFicha(int posicionUltimaFicha[2], char fichaActual, char tablero[10][10]);
/*
* Esta función se encarga de mostrar el estado del tablero luego de cada jugada.
*/
void mostrarTablero(char tablero[10][10]);
/*
* Esta funcion verifica si el tablero no se ha llenado.
*/
bool tableroLleno(char tablero[10][10]);
/*
* Esta función limpia mi hilera de fichas a revisar.
*/
void limpiarHilera(char hilera[10]);
/*
* Esta funcion hace una copia de la columna donde fue colocada la ultima ficha del tablero
* a una hilera para poder verificar si hubo 4 en linea.
*/
void copiarHileraVertical(int columnaUltimaFicha, char tablero[10][10], char hilera[10]);
/*
* Esta funcion hace una copia de la fila donde fue colocada la ultima ficha del tablero
* a una hilera para poder verificar si hubo 4 en linea.
*/
void copiarHileraHorizontal(int filaUltimaFicha, char tablero[10][10], char hilera[10]);
/*
* Esta funcion hace una copia de la diagonal creciente tomando como referencia donde fue
* colocada la ultima ficha del tablero a una hilera para poder verificar si hubo 4 en linea.
*/
void copiarHileraDiagonalCreciente(int posicionUltimaFicha[2], char tablero[10][10], char hilera[10]);
/*
* Esta funcion hace una copia de la diagonal decreciente tomando como referencia donde fue
* colocada la ultima ficha del tablero a una hilera para poder verificar si hubo 4 en linea.
*/
void copiarHileraDiagonalDecreciente(int posicionUltimaFicha[2], char tablero[10][10], char hilera[10]);
#endif /* TABLERO_H_ */
| true |
06809675f4eec158c69f12b14c17e176bb559a3f | C++ | piashishi/cleancode | /ut/libpool_ut.cc | UTF-8 | 2,440 | 2.984375 | 3 | [] | no_license | #include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "UnitTest++.h"
#include "list.h"
#include "libpool.h"
#define TEST_POOL_TYPE_DATA (0)
#define TEST_POOL_TYPE_2ND (1)
#define TEST_POOL_TYPE_MAX (2)
TEST(libpool_ut_init)
{
size_t element_size = 4;
const int entry_count = 25;
pool_attr_t pool_attr[] = {{element_size, entry_count}};
const int pool_count = sizeof(pool_attr) / sizeof(pool_attr_t);
size_t large_mem_size = pool_caculate_total_length(pool_count, pool_attr);
void *large_memory = malloc(large_mem_size);
CHECK(large_memory != NULL);
void *pools = pools_init(large_memory, large_mem_size - 1, pool_count, pool_attr);
CHECK(pools == NULL);
pools = pools_init(large_memory, large_mem_size, pool_count, pool_attr);
CHECK(pools != NULL);
free(pools);
}
TEST(libpool_ut_2_typse_of_pools)
{
size_t element_size = 4;
const int entry_count = 25;
pool_attr_t pool_attr[] = {{element_size, entry_count}, {element_size, entry_count}};
size_t large_mem_size = pool_caculate_total_length(TEST_POOL_TYPE_MAX, pool_attr);
void *large_memory = malloc(large_mem_size);
CHECK(large_memory != NULL);
void *pools = pools_init(large_memory, large_mem_size, TEST_POOL_TYPE_MAX, pool_attr);
CHECK(pools != NULL);
void *entry = pool_get_element(pools, TEST_POOL_TYPE_DATA);
CHECK(entry != NULL);
entry = pool_get_element(pools, TEST_POOL_TYPE_2ND);
CHECK(entry != NULL);
free(pools);
}
TEST(libpool_ut_get_element)
{
size_t mem_size = 100;
size_t element_size = 4;
const int entry_count = 25;
pool_attr_t pool_attr[] = {{element_size, entry_count}};
const int pool_count = sizeof(pool_attr) / sizeof(pool_attr_t);
size_t large_mem_size = pool_caculate_total_length(pool_count, pool_attr);
void* large_mem = malloc(large_mem_size);
CHECK_EQUAL(!large_mem, 0);
void *pools = pools_init(large_mem, large_mem_size, pool_count, pool_attr);
CHECK_EQUAL(!pools, 0);
void * entry_stack[entry_count];
int i;
void *entry;
for (i = 0; i < entry_count; i++) {
entry = pool_get_element(pools, TEST_POOL_TYPE_DATA);
CHECK_EQUAL(entry != (void* )NULL, TRUE);
entry_stack[i] = entry;
}
return_t ret;
for (i = 0; i < entry_count; i++) {
pool_free_element(pools, TEST_POOL_TYPE_DATA, entry_stack[i]);
}
free(pools);
}
| true |
8fd13ae0102d9f684595990e34f4436cd9e5cf32 | C++ | alexandraback/datacollection | /solutions_5769900270288896_1/C++/aid/main.cpp | UTF-8 | 1,672 | 3.0625 | 3 | [] | no_license | #include <fstream>
using namespace std;
int solve0(int r, int c, int n) {
int ans = (r - 1) * c + (c - 1) * r, cnt = ((r - 2) * (c - 2) + 1) / 2;
if(n <= cnt)
return ans - 4 * n;
ans -= 4 * cnt;
n -= cnt;
cnt = (r * c + 1) / 2 - cnt;
if((r * c) & 1)
cnt -= 4;
else
cnt -= 2;
if(n <= cnt)
return ans - 3 * n;
ans -= 3 * cnt;
n -= cnt;
return ans - 2 * n;
}
int solve1(int r, int c, int n) {
int ans = (r - 1) * c + (c - 1) * r, cnt = ((r - 2) * (c - 2)) / 2;
if(n <= cnt)
return ans - 4 * n;
ans -= 4 * cnt;
n -= cnt;
cnt = (r * c) / 2 - cnt;
if(!((r * c) & 1))
cnt -= 2;
if(n <= cnt)
return ans - 3 * n;
ans -= 3 * cnt;
n -= cnt;
return ans - 2 * n;
}
int main() {
ifstream in("input.txt");
ofstream out("output.txt");
int t;
in >> t;
for(int tt = 0; tt < t; tt++) {
int r, c, n;
in >> r >> c >> n;
out << "Case #" << tt + 1 << ": ";
if(n <= (r * c + 1) / 2) {
out << 0 << '\n';
continue;
}
if(r == 1) {
if(c & 1)
out << (n - (c + 1) / 2) * 2 << '\n';
else
out << (n - (c + 1) / 2) * 2 - 1 << '\n';
continue;
}
if(c == 1) {
if(r & 1)
out << (n - (r + 1) / 2) * 2 << '\n';
else
out << (n - (r + 1) / 2) * 2 - 1 << '\n';
continue;
}
n = r * c - n;
int ans0 = solve0(r, c, n), ans1 = solve1(r, c, n);
out << min(ans0, ans1) << '\n';
}
return 0;
}
| true |
e899c4ab0c0e1c361a887bc3bccd6a96bcad78ae | C++ | OverseerCouncil/leetcode | /1052.爱生气的书店老板/C++/75%T70%M.cpp | UTF-8 | 660 | 2.828125 | 3 | [] | no_license | int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {
int customers_num = customers.size();
int base_cnt = 0;
for (int i = 0; i < customers_num; i++) {
base_cnt += customers[i] * (1 - grumpy[i]);
}
int more_cnt = 0;
for (int i = 0; i < X; i++) {
more_cnt += customers[i] * grumpy[i];
}
int res_cnt = more_cnt;
for (int i = X; i < customers_num; i++) {
more_cnt = more_cnt + customers[i] * grumpy[i] - customers[i - X] * grumpy[i - X];
res_cnt = max(more_cnt, res_cnt);
}
return res_cnt + base_cnt;
} | true |
cc321f6e93af6874a667744f2cb089b884826f82 | C++ | joe-zxh/OJ | /程序员代码面试指南/第3章 二叉树问题/18.2 在二叉树中找到两个节点的最近公共祖先(进阶).cpp | UTF-8 | 895 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <set>
using namespace std;
int LCA(int head, int*lc, int *rc, int*father, int o1, int o2) {
set<int>f1;
f1.insert(o1);
while (father[o1] != -1) {
o1 = father[o1];
f1.insert(o1);
}
do {
if (f1.find(o2)!=f1.end()) {
return o2;
}
else {
o2 = father[o2];
}
} while (o2 != -1);
}
int main()
{
int n, root, t;
scanf("%d %d", &n, &root);
int* lc = new int[n + 1];
int* rc = new int[n + 1];
int* father = new int[n + 1];
father[root] = -1;
for (int i = 0; i < n; i++) {
scanf("%d", &t);
scanf("%d %d", &lc[t], &rc[t]);
father[lc[t]] = t;
father[rc[t]] = t;
}
int o1, o2, opts;
scanf("%d", &opts);
for (int i = 0; i < opts; i++) {
scanf("%d %d", &o1, &o2);
printf("%d\n", LCA(root, lc, rc, father, o1, o2));
}
delete[]lc, rc, father;
return 0;
}
| true |
0fd7855873809c27dcb682238d48d44e1c7d6797 | C++ | albertakopian/Algo | /SecondTerm/GraphTheory/Dijkstra.cpp | UTF-8 | 3,640 | 3.40625 | 3 | [] | no_license | /*
Требуется отыскать самый выгодный маршрут между городами.
Требуемое время работы O((N+M)logN), где N-количество городов,
M-известных дорог между ними.
Оптимизируйте ввод
Формат входных данных.
Первая строка содержит число N – количество городов.
Вторая строка содержит число M - количество дорог.
Каждая следующая строка содержит описание дороги (откуда, куда, время в пути).
Последняя строка содержит маршрут (откуда и куда нужно доехать).
Формат выходных данных.
Вывести длину самого выгодного маршрута.
*/
#include <iostream>
#include <numeric>
#include <set>
#include <vector>
using Vertex = size_t;
class Graph {
public:
Graph(size_t vertex_count, size_t edge_count);
size_t GetMinDistance(Vertex from, Vertex to);
private:
struct TargetVertex;
class VertexComparator;
void InputEdges(size_t edge_count);
static constexpr size_t infinity = std::numeric_limits<size_t>::max();
size_t vertex_count_;
std::vector<std::vector<TargetVertex>> adjacency_lists_;
};
Graph::Graph(const size_t vertex_count, const size_t edge_count)
: vertex_count_(vertex_count), adjacency_lists_(vertex_count) {
InputEdges(edge_count);
}
struct Graph::TargetVertex {
public:
TargetVertex(const Vertex vertex, const size_t edge_weight)
: vertex(vertex), edge_weight(edge_weight) {}
Vertex vertex;
size_t edge_weight;
};
void Graph::InputEdges(const size_t edge_count) {
Vertex vertex1;
Vertex vertex2;
size_t edge_weight;
for (int i = 0; i < edge_count; ++i) {
std::cin >> vertex1 >> vertex2 >> edge_weight;
adjacency_lists_[vertex1].emplace_back(vertex2, edge_weight);
adjacency_lists_[vertex2].emplace_back(vertex1, edge_weight);
}
}
class Graph::VertexComparator {
public:
VertexComparator(const std::vector<size_t>& distance) : distance_(distance) {}
bool operator()(const Vertex lhs, const Vertex rhs) const {
return distance_[lhs] < distance_[rhs] ||
distance_[lhs] == distance_[rhs] && lhs < rhs;
}
private:
const std::vector<size_t>& distance_;
};
size_t Graph::GetMinDistance(const Vertex from, const Vertex to) {
std::vector<size_t> distances(vertex_count_, infinity);
VertexComparator comparator(distances);
std::set<Vertex, VertexComparator> wip_vertices(comparator);
distances[from] = 0;
wip_vertices.insert(from);
while (!wip_vertices.empty()) {
Vertex current_vertex = *wip_vertices.begin();
wip_vertices.erase(wip_vertices.begin());
if (current_vertex == to) {
return distances[to];
}
for (const auto& target : adjacency_lists_[current_vertex]) {
size_t new_distance = distances[current_vertex] + target.edge_weight;
if (new_distance < distances[target.vertex]) {
wip_vertices.erase(target.vertex);
distances[target.vertex] = new_distance;
wip_vertices.insert(target.vertex);
}
}
}
return distances[to];
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
size_t city_count = 0;
size_t road_count = 0;
std::cin >> city_count >> road_count;
Graph map(city_count, road_count);
size_t from = 0;
size_t to = 0;
std::cin >> from >> to;
std::cout << map.GetMinDistance(from, to) << std::endl;
return 0;
} | true |
c10c211e0d13d28a4ccf2ddff12ca553ff538b4e | C++ | alladdinkumar/LeetCoding-Challenge-MAY- | /K Closest Points to Origin.cpp | UTF-8 | 1,133 | 3 | 3 | [] | no_license | class Solution {
public:
float euclidean(vector<int> x)
{
return sqrt(pow(x[0],2)+pow(x[1],2));
}
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
int cnt=0;
map<float,vector<int>> m;
map<float,vector<int>>::iterator itr;
for(int i=0;i<points.size();i++)
{
auto vec=points[i];
float dist=euclidean(vec);
if(cnt<K)
{
m[dist].push_back(i);
cnt++;
}
else
{
itr = m.end();
itr--;
if(dist<itr->first)
{
if(itr->second.size()>1)
itr->second.erase(itr->second.begin());
else
m.erase(itr);
m[dist].push_back(i);
}
}
}
vector<vector<int>> sol;
for(auto i:m)
{
for(auto x:i.second)
{
sol.push_back(points[x]);
}
}
return sol;
}
};
| true |
bef5999c5ed099b0e0be4ffed3d9a750b1a34e2f | C++ | gndu91/donneesLibres | /tableau-donnees.h | UTF-8 | 1,267 | 3.46875 | 3 | [] | no_license | #include <vector>
#include <string>
using namespace std;
/** Moyenne d'un tableau
* @param un tableau d'entiers
* @result la moyenne de ces entiers
**/
int moyenne(vector<int> t);
/** Total d'un tableau
* @param un tableau d'entiers
* @result la somme de ces entiers
**/
int total(vector<int> t);
/** Max d'un tableau
* @param un tableau d'entiers
* @result le plus grand de ces entiers (0 par defaut)
**/
int max(vector<int> t);
/** Position du max d'un tableau
* @param un tableau d'entiers
* @result la position du plus grand de ces entiers;
le premier s'il y en a plusieurs;
-1 si le tableau est vide
**/
int maxPosition(vector<int> t);
/** Construction d'un tableau 2D d'entiers lu depuis un fichier
* @param fichier le nom d'un fichier contenant un nombre fixe
* d'entiers par lignes, séparés par des espaces
* @param nb_colonnes le nombre de colonnes du fichier
* @return un tableau d'entiers à deux dimensions
**/
vector<vector<int>> litTableauInt(string fichier, int nb_colonnes);
/** Extraction d'une colonne d'un tableau d'entiers
* @param t un tableau 2D d'entiers
* @param i un numéro de colonne
* @return la colonne i, représentée par un vecteur d'entiers
**/
vector<int> colonne(vector<vector<int>> t, int i);
| true |
4ec3aea5e4afef1ec7d14a0dfb622f5cdbc22492 | C++ | muneebGH/complex-number-library-cpp | /cmplx.cpp | UTF-8 | 1,551 | 3.15625 | 3 | [] | no_license | #include"cmplx.h"
double cmplx::getRealPart() const
{
return realvalue;
}
void cmplx::setRealPart(double r)
{
realvalue = r;
}
double cmplx::getImgValue() const
{
return imgvalue;
}
void cmplx::setImgValue(double i)
{
imgvalue = i;
}
void cmplx::setcomplexno(double r, double i)
{
realvalue = r;
imgvalue = i;
}
double cmplx::magnitude() const
{
double mag;
mag = sqrt((realvalue*realvalue) + (imgvalue*imgvalue));
return mag;
}
cmplx cmplx::conjucate() const
{
cmplx conj;
conj.realvalue = realvalue;
conj.imgvalue = -1 * imgvalue;
return conj;
}
cmplx cmplx::reciprocal() const
{
int m;
cmplx no, res;
no = conjucate();
m = magnitude();
res.realvalue = no.realvalue / (m*m);
res.imgvalue = no.imgvalue / (m*m);
return res;
}
cmplx cmplx::operatorplus(const cmplx &rec)
{
cmplx sum;
sum.realvalue = realvalue + rec.realvalue;
sum.imgvalue = imgvalue + rec.imgvalue;
return sum;
}
cmplx cmplx::operatormin(const cmplx &rec)
{
cmplx sub;
sub.realvalue = realvalue - (rec.realvalue);
sub.imgvalue = imgvalue - (rec.imgvalue);
return sub;
}
cmplx cmplx::operatormul(const cmplx &rhs)
{
cmplx mul;
mul.realvalue = realvalue * rhs.realvalue;
mul.imgvalue = imgvalue * rhs.imgvalue;
return mul;
}
cmplx cmplx::operatorminus()const
{
cmplx neg;
neg.realvalue = realvalue * -1;
neg.imgvalue = imgvalue * -1;
return neg;
}
void cmplx::display() const
{
cout << realvalue << "+";
cout << imgvalue << "i" << endl;
}
| true |
4be2e463d4fb83710094aef47cf4e2b7768d2bb0 | C++ | crosslink/tranlator | /src/article.h | UTF-8 | 1,214 | 2.546875 | 3 | [] | no_license | /*
* article.h
*
* Created on: Apr 24, 2012
* Author: monfee
*/
#ifndef ARTICLE_H_
#define ARTICLE_H_
#include <string>
class article {
public:
enum {WRITE_TO_DATABASE = 1, WRITE_TO_DISK = 2};
/*, WRITE_TO_DISK_AND_DATABASE = 3*/
protected:
std::string file_path;
std::string name;
std::string ext;
char* content;
long doc_id;
std::string source_lang;
std::string target_lang;
public:
article();
article(const char* file);
virtual ~article();
virtual bool read();
virtual void write();
virtual void write(int write_type);
virtual void write(const char* content);
virtual void write(const char* content, int write_type);
virtual void write(const char* content, const char* path, int write_type);
static std::string id2dir(unsigned long id);
static int file2id(const char* file);
std::string file2name(const char* file);
std::string get_source_lang() const;
void set_source_lang(std::string source_lang);
std::string get_target_lang() const;
void set_target_lang(std::string target_lang);
long get_doc_id();
void set_doc_id(long id);
private:
void init();
};
#endif /* ARTICLE_H_ */
| true |
77a1f654519b21e68c1dafe448715763732007ef | C++ | Dio12334/proyecto-alpha | /saviour/UTEC/POO2/estructuras/unidad5_sem07/src/ejercicios.cpp | UTF-8 | 2,921 | 3.46875 | 3 | [] | no_license | //
// Author: marvin on 5/20/20.
//
#include "ejercicios.h"
#include "funciones.h"
#include "hash/hash_direct_address_table.h"
#include "hash/hash_chaining.h"
void ejercicio1() {
cout<<"hashing"<<endl;
client_hash_direct_address_table();
}
void ejercicio2() {
my_hash myHash(7);
myHash.insert(53);
myHash.insert(7);
myHash.insert(21);
myHash.insert(58);
myHash.insert(25);
myHash.insert(24);
myHash.insert(17);
myHash.insert(56);
myHash.insert(56);
myHash.print();
cout<<"search 25: "<<myHash.search(25)<<endl;
myHash.delete_key(25);
cout<<"search 25: "<<myHash.search(25)<<endl;
myHash.print();
}
void ejercicio3() {
int arr[] = {19, 12, 19, 12, 13, 13, 18};
cout<<"count distinct elements: "<<count_distinct(arr, 7)<<endl;
cout<<"count distinct elements: "<<count_distinct_optima(arr, 7)<<endl;
}
void ejercicio4() {
cout<<"Quicksort"<<endl;
/*
* Best | Average | Worst
* Omega(nlogn) theta(nlogn) O(n^2)
*/
cout<<"Mergesort"<<endl;
/*
* Best | Average | Worst
* Omega(nlogn) theta(nlogn) O(nlogn)
1.- Divide and conquer
2.- Stable
3.- theta(nlogn) time, O(n) space
*/
int arr[] = {10, 5, 30, 15, 7};
print(arr, 5);
merge_sort(arr, 0, 4);
print(arr, 5);
}
void ejercicio5() {
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->right->left = new Node(40);
root->right->right = new Node(50);
/*
* 10
* / \
* 20 30
* / \
* 40 50
*
* inorder: 20 10 40 30 50
* preorder: 10 20 30 40 50
* postorder: 20 40 50 30 10
*/
inorder(root);
cout<<endl;
preorder(root);
cout<<endl;
postorder(root);
}
void ejercicio6() {
cout<<"Calculate the median of a sequence"<<endl;
/*
* int arr[] = {25, 7, 10, 15, 20}
* 25 16 10 12.5 15
*
*
* Mantener un tmp (sorted)
* tmp[] = |25| -> size = 1 -> 25
* tmp[] = |7|25| -> size = 2 -> 16
* tmp[] = |7|10|25| -> size = 3 -> 10
* tmp[] = |7|10|15|25| -> size = 4 -> 12.5
* tmp[] = |7|10|15|20|25| -> size = 5 -> 15
*
* if (size%2 != 0)
* return tmp[size/2];
* else
* return (tmp[size/2] + tmp[(size-1)/2])/2;
*
*
*
*/
int arr[] = {25, 7, 10, 15, 20};
print_medians(arr, 5);
}
void ejercicio7() {
cout<<"Heap Sort"<<endl;
/*
* int arr[] = {10, 15, 50, 4, 20}
* int arr[] = {4, 10, 15, 20, 50}
*
*/
int arr[] = {10, 15, 50, 4, 20};
print(arr, 5);
heap_sort(arr, 5);
print(arr, 5);
}
| true |
3e0282d8663db6e6ef2614d62bb45a23bb99d5ce | C++ | Grishameister/CoursachStatVerySimple | /include/SafeQueue.h | UTF-8 | 907 | 3.15625 | 3 | [] | no_license | #ifndef HIGHLOAD_SERVER_SAFEQUEUE_H
#define HIGHLOAD_SERVER_SAFEQUEUE_H
#include <queue>
#include <condition_variable>
template<typename T>
class SafeQueue {
private:
std::queue<T> q;
mutable std::mutex mu;
std::condition_variable cv;
public:
bool Push(T value) {
std::lock_guard<std::mutex> guard(mu);
q.push(std::move(value));
cv.notify_one();
return true;
}
bool WaitPop(T& value) {
std::unique_lock<std::mutex> guard(mu);
cv.wait(guard, [this]() {
return !q.empty();
});
value = std::move(q.front());
q.pop();
return false;
}
bool Empty() const {
std::lock_guard<std::mutex> guard(mu);
return q.empty();
}
size_t Size() const {
std::lock_guard<std::mutex> guard(mu);
return q.size();
}
};
#endif //HIGHLOAD_SERVER_SAFEQUEUE_H
| true |
89fabbdf19d0b11fa94c1e00273667d00e91dd11 | C++ | linguoliang/learning | /data_strcture_and_algorithms/algorithms/dynamic_programming/src/cutting_rod.cc | UTF-8 | 1,374 | 3.390625 | 3 | [] | no_license | #include "cutting_rod.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include "util.h"
using std::cout;
using std::endl;
using std::max;
using std::string;
using std::vector;
int cut1(const vector<int>& prices, int index, int length);
int cut2(const vector<int>& prices, int length);
void CuttingRod() {
vector<int> prices{1, 5, 8, 9, 10, 17, 17, 20};
int length = 8;
cout << cut1(prices, prices.size(), length) << endl;
cout << cut2(prices, length) << endl;
}
int cut1(const vector<int>& prices, int n, int length) {
if (length == 0 || n == 0) {
return 0;
}
if (n > length) {
return prices[length - 1];
}
return max(cut1(prices, n - 1, length),
cut1(prices, n, length - n) + prices[n - 1]);
}
int cut2(const vector<int>& prices, int length) {
vector<vector<int>> dp(prices.size() + 1, vector<int>(length + 1, -1));
for (int i = 0; i <= prices.size(); ++i) {
for (int j = 0; j <= length; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (i > j) {
dp[i][j] = prices[j - 1];
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - i] + prices[i - 1]);
}
}
}
vector<int> backint;
int i = prices.size();
int j = length;
for (int p : backint) {
cout << p << " ";
}
cout << endl;
return dp[prices.size()][length];
}
| true |
0d4905d96bda2eccfb35a5a2fddb8c9f8f059610 | C++ | hahanhuy/KTLT_2017 | /UserManager.cpp | UTF-8 | 5,133 | 2.8125 | 3 | [] | no_license | #include "Assignment.h"
//////////////////////////////////////////////////////////////////////////////////
// Phan quyen cho account, nho chu y CLOSE va OPEN, phai check ky xem CO TON TAI TEMP hay khong.
void delete_in_permissionaccount(string username) {
fstream outfile;
outfile.open("permissionaccount.txt", ios::in);
fstream temp;
temp.open("temp.txt", ios::out);
string datatemp;
account *tempaccount=new account();
int flag=0;
do {
getline(outfile, datatemp);
tempaccount->setUsername(datatemp);
getline(outfile, datatemp);
tempaccount->setPassword(datatemp);
getline(outfile, datatemp);
tempaccount->setID(datatemp);
getline(outfile, datatemp);
tempaccount->setRole(datatemp);
getline(outfile, datatemp);
tempaccount->setActive(datatemp);
if (username != tempaccount->getUsername()&&(tempaccount->getUsername() != "")) {
temp << tempaccount->getUsername() << '\n' << tempaccount->getPassword() << '\n' << tempaccount->getID() << '\n' << tempaccount->getRole() << '\n' << tempaccount->getActive()<< endl;
}
} while (!outfile.eof());
temp.close();
outfile.close();
remove("permissionaccount.txt");
rename("temp.txt", "permissionaccount.txt");
}
void change_role_function(string username, string newRole) {
fstream outfile;
outfile.open("account.txt", ios::in);
fstream temp;
temp.open("temp.txt", ios::out);
string datatemp;
account *tempaccount=new account();
int flag=0;
do {
getline(outfile, datatemp);
tempaccount->setUsername(datatemp);
getline(outfile, datatemp);
tempaccount->setPassword(datatemp);
getline(outfile, datatemp);
tempaccount->setID(datatemp);
getline(outfile, datatemp);
tempaccount->setRole(datatemp);
getline(outfile, datatemp);
tempaccount->setActive(datatemp);
if (username != tempaccount->getUsername()&&(tempaccount->getUsername() != "")) {
temp << tempaccount->getUsername() << '\n' << tempaccount->getPassword() << '\n' << tempaccount->getID() << '\n' << tempaccount->getRole() << '\n' << tempaccount->getActive()<< endl;
}
if (username == tempaccount->getUsername()) {
temp << tempaccount->getUsername() << '\n' << tempaccount->getPassword() << '\n' << tempaccount->getID() << '\n' << newRole << '\n' << tempaccount->getActive()<< endl;
}
} while (!outfile.eof());
temp.close();
outfile.close();
remove("account.txt");
rename("temp.txt", "account.txt");
}
void grant_new_role() {
//show thong tin cac account
// check xem username co khong
//neu co thi tien hanh grant moi role
//xoa ben permissionaccount
}
//////////////////////////////////////////////////////////////////////////
//Xet duyet thong tin User
void delete_user_in_manage_user(string ID) {
fstream outfile;
outfile.open("manageuser.txt", ios::in);
fstream temp;
temp.open("temp.txt", ios::out);
string datatemp;
user *tempuser=new user();
int flag=0;
do {
getline(outfile,datatemp);
tempuser->setName(datatemp);
getline(outfile,datatemp);
tempuser->setCMND(datatemp);
getline(outfile,datatemp);
tempuser->setID(datatemp);
getline(outfile,datatemp);
tempuser->setPassword(datatemp);
getline(outfile,datatemp);
tempuser->setPhone(datatemp);
getline(outfile,datatemp);
tempuser->setAddress(datatemp);
getline(outfile,datatemp);
tempuser->setBirthday(datatemp);
getline(outfile,datatemp);
tempuser->setEmail(datatemp);
getline(outfile,datatemp);
tempuser->setJob(datatemp);
getline(outfile,datatemp);
tempuser->setActive(datatemp);
if (ID != tempuser->getID()&&(tempuser->getID() != "")) {
temp << tempuser->getName() << '\n' << tempuser->getCMND() << '\n' << tempuser->getID() << '\n' << tempuser->getPassword() << '\n' << tempuser->getPhone()
<<'\n'<<tempuser->getAddress()<< '\n'<<tempuser->getBirthday()<< '\n'<<tempuser->getEmail()<< '\n'<<tempuser->getJob()<<'\n'<<tempuser->getActive()<<endl;
}
} while (!outfile.eof());
temp.close();
outfile.close();
remove("manageuser.txt");
rename("temp.txt", "manageuser.txt");
}
void verify_user_function(string ID) {
fstream outfile;
outfile.open("manageuser.txt", ios::in);
string datatemp;
int count = 1;
user *temp=new user();
while (!outfile.eof()) {
getline(outfile,datatemp);
temp->setName(datatemp);
getline(outfile,datatemp);
temp->setCMND(datatemp);
getline(outfile,datatemp);
temp->setID(datatemp);
getline(outfile,datatemp);
temp->setPassword(datatemp);
getline(outfile,datatemp);
temp->setPhone(datatemp);
getline(outfile,datatemp);
temp->setAddress(datatemp);
getline(outfile,datatemp);
temp->setBirthday(datatemp);
getline(outfile,datatemp);
temp->setEmail(datatemp);
getline(outfile,datatemp);
temp->setJob(datatemp);
getline(outfile,datatemp);
temp->setActive(datatemp);
if (temp->getID() == ID) {
user *newUser=new user(temp); //ghi vao list
newUser->add_user_to_list();
}
}
outfile.close();
delete_user_in_manage_user(ID);
}
void verify_user() { //TO DO
}
////////////////////////
| true |
ec7b02c7cbb24115fb0f4a3072ff04bd3b91c423 | C++ | iamDip171/URI-Probelms | /1960.cpp | UTF-8 | 562 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std ;
int main ()
{
int n, temp, i, j ; cin >> n ;
int test[] = {500, 100, 50, 10, 5, 1} ;
for (i=0; n!=0; i++){
temp = n / test[i] ;
n = n % test[i] ;
for (j=1; j<=temp; j++){
if (i==0) cout << "D" ;
else if (i==1) cout << "C" ;
else if (i==2) cout << "L" ;
else if (i==3) cout << "X" ;
else if (i==4) cout << "V" ;
else if (i==5) cout << "I" ;
}
//cout << temp << " ";
}
}
| true |
6c09f4a90078df6e509ffd23cdd9f0065761c0f8 | C++ | liangjisheng/C-Cpp | /books/C++_Prime_Plus/Chapter15/error1.cpp | UTF-8 | 445 | 3.203125 | 3 | [
"MIT"
] | permissive | // error1.cpp -- using the abort() function
#include"iostream"
#include"cstdlib"
double hmean(double,double);
int main()
{
double x,y,z;
std::cout<<"Input two numbers:";
while(std::cin>>x>>y) {
z=hmean(x,y);
std::cout<<"z="<<z<<std::endl;
std::cout<<"\nInput two numbers:";
}
return 0;
}
double hmean(double a,double b) {
if(a==-b) {
std::cout<<"Untenable arguments to hmean()\n";
abort();
}
return 2.0 * a * b / (a + b);
} | true |
e9b0367a783e1216f589b3543ae66751d42fc242 | C++ | abhavgarg/DX11-Scene | /Source/Ball.cpp | UTF-8 | 2,608 | 2.953125 | 3 | [] | no_license | #include "pch.h"
#include "Ball.h"
//camera for our app simple directX application. While it performs some basic functionality its incomplete.
//
Ball::Ball()
{
//initalise values.
//Orientation and Position are how we control the camera.
m_orientation.x = 90.0f; //rotation around x - pitch
m_orientation.y = 0.0f; //rotation around y - yaw
m_orientation.z = 0.0f; //rotation around z - roll //we tend to not use roll a lot in first person
m_position.x = 0.0f; //camera position in space.
m_position.y = -0.8f;
m_position.z = 0.0f;
//These variables are used for internal calculations and not set. but we may want to queary what they
//externally at points
m_lookat.x = 0.0f; //Look target point
m_lookat.y = 0.0f;
m_lookat.z = 0.0f;
m_forward.x = 0.0f; //forward/look direction
m_forward.y = 0.0f;
m_forward.z = 0.0f;
m_right.x = 0.0f;
m_right.y = 0.0f;
m_right.z = 0.0f;
//
m_movespeed = 0.30;
m_ballRotRate = 3.0;
radius = 0.075;
//force update with initial values to generate other camera data correctly for first update.
Update();
}
Ball::~Ball()
{
}
void Ball::Update()
{
//rotation in yaw - using the paramateric equation of a circle
m_forward.x = sin((m_orientation.y)*3.1415f / 180.0f);
m_forward.z = cos((m_orientation.y)*3.1415f / 180.0f);
m_forward.Normalize();
//m_right.y = sin((m_orientation.x)*3.1415f / 180.0f);
//m_right.z = cos((m_orientation.x)*3.1415f / 180.0f);
//m_right.Normalize();
//create right vector from look Direction
m_forward.Cross(DirectX::SimpleMath::Vector3::UnitY, m_right);
//update lookat point
m_lookat = m_position + m_forward;
//apply camera vectors and create camera matrix
m_ballMatrix = (DirectX::SimpleMath::Matrix::CreateLookAt(m_position, m_lookat, DirectX::SimpleMath::Vector3::UnitY));
xmin = m_position.x - radius;
xmax = m_position.x + radius;
zmin = m_position.z - radius;
zmax = m_position.z + radius;
}
DirectX::SimpleMath::Matrix Ball::getBallMatrix()
{
return m_ballMatrix;
}
void Ball::setPosition(DirectX::SimpleMath::Vector3 newPosition)
{
m_position = newPosition;
}
DirectX::SimpleMath::Vector3 Ball::getPosition()
{
return m_position;
}
DirectX::SimpleMath::Vector3 Ball::getForward()
{
return m_forward;
}
DirectX::SimpleMath::Vector3 Ball::getRight()
{
return m_right;
}
void Ball::setRotation(DirectX::SimpleMath::Vector3 newRotation)
{
m_orientation = newRotation;
}
DirectX::SimpleMath::Vector3 Ball::getRotation()
{
return m_orientation;
}
float Ball::getMoveSpeed()
{
return m_movespeed;
}
float Ball::getRotationSpeed()
{
return m_ballRotRate;
}
| true |
6f42524fa45cdffc058e39445c80c3ab2752bc25 | C++ | shihyu/MyTool | /Doxygen_Graphviz/DesignPatternExample/品味Java的21種設計模式/dp_cpp/factorymethod/example2/Creator.h | GB18030 | 665 | 2.546875 | 3 | [] | no_license | #pragma once
#include "Product.h"
namespace cn
{
namespace javass
{
namespace dp
{
namespace factorymethod
{
namespace example2
{
///
/// <summary> * </summary>
///
class Creator
{
///
/// <summary> * ProductĹ </summary>
/// * <returns> Product </returns>
///
protected:
virtual Product *factoryMethod() = 0;
///
/// <summary> * ʾⷽʵijЩܵķ </summary>
///
public:
virtual void someOperation();
};
}
}
}
}
} | true |
61beb0dc5eb1794c1f78fe8ffd66d1f1d774ece2 | C++ | Victor-Barcelo/Arduino-FSM-test-1 | /FSMExample.ino | UTF-8 | 2,627 | 2.78125 | 3 | [] | no_license | #include <Wire.h>
#include <Time.h>
#define SLAVE_ADDRESS 0x05
#define DEBUG true
const int PIN_TEMPSENSOR = 0;
const int PIN_PUSHBUTTON = 7;
// Debounce para el botón: (http://arduino.cc/en/Tutorial/Debounce)
int buttonState;
int lastButtonState = LOW;
long lastDebounceTime = 0;
long debounceDelay = 50;
//-------------------------
typedef enum {WaitingForOrders, ConfiguringTime, SendingSensorData, SendingButtonInfo} State;
State state;
typedef enum {RequestingSensorData, RequestingPushButtonTimes} RequestType;
RequestType requestType;
unsigned long pushButtonTimes[10];
void setup() {
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
// Wire.onRequest(sendSensorData);
// Wire.onRequest(kk);
Wire.onReceive(onRecieve);
state = WaitingForOrders;
if(DEBUG) Serial.println("Ready!");
}
void loop() {
delay(100);
// switch (state) {
// case WaitingForOrders:
// checkForButtonPress();
// break;
// case SendingSensorData:
// sendSensorData();
// state = WaitingForOrders;
// break;
// case SendingButtonInfo:
// sendButtonInfo();
// state = WaitingForOrders;
// break;
// case ConfiguringTime:
// configureTime();
// state = WaitingForOrders;
// break;
// }
}
void onRecieve(int byteCount){
int cmd = Wire.read();
Serial.println(cmd);
if(cmd == 0) state = ConfiguringTime;
if(cmd == 1) state = SendingSensorData;
if(cmd == 2) state = SendingButtonInfo;
}
void kk(){}
void sendSensorData(){
// int cmd = Wire.read();
// Serial.println(cmd);
byte data[2];
int temperature = (125*analogRead(PIN_TEMPSENSOR))>>8; // raw to Celsius
if(DEBUG){
Serial.print("Temperatura: ");
Serial.println(temperature);
}
data[0] = lowByte(temperature);
data[1] = highByte(temperature);
byte dataSend[] = {data[0],data[1]};
Wire.write(dataSend, 2);
}
void checkForButtonPress(){
int reading = digitalRead(PIN_PUSHBUTTON);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
//Insert entry to pushButtonTimes
}
}
}
lastButtonState = reading;
}
void sendButtonInfo(){
//send pushButtonTimes array
//clear pushButtonTimes array
}
void configureTime(){
unsigned long bytes[4];
int i = 0;
while(Wire.available()){
bytes[i] = Wire.read();
i++;
}
unsigned long result = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24);
setTime(result);
} | true |
91ddfa21e58b28f3ada92c93ceb514853dfd4d99 | C++ | JohnGlassmyer/cpp-sandbox | /x86storeload.cpp | UTF-8 | 1,055 | 3.125 | 3 | [] | no_license | #include <atomic>
#include <iostream>
#include <thread>
// based on the oft-referenced example from Intel's x86 guide.
// switch this to demonstrate the effect
constexpr bool shouldFence = false;
int x;
int y;
// not registers but w/e
int r1;
int r2;
std::atomic<bool> shouldProceed;
void storeAndLoad(int &storeTo, int &loadFrom, int &dest) {
while(!shouldProceed);
storeTo = 1;
// prevent compile-time reordering by the compiler
asm ("" ::: "memory");
if (shouldFence) {
// also prevent run-time reordering by the processor
asm ("mfence" ::: "memory");
}
dest = loadFrom;
}
int main() {
for (int i = 0; i < 10000; i++) {
x = 0;
y = 0;
r1 = 0;
r2 = 0;
shouldProceed = false;
std::thread left(storeAndLoad, std::ref(x), std::ref(y), std::ref(r1));
std::thread right(storeAndLoad, std::ref(y), std::ref(x), std::ref(r2));
shouldProceed = true;
left.join();
right.join();
std::cout << r1 << r2;
if (r1 == 0 && r2 == 0) {
// store-load reordered
std::cout << "*****";
}
std::cout << std::endl;
}
}
| true |
34e7096bb50437e46d8c87f5a431943ce931151d | C++ | KeylaRocha/URI_problems | /Beginner/C++/2936.cpp | UTF-8 | 516 | 3.0625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int pesos[5] = {300, 1500, 600, 1000, 150}; //peso em gramas das porções de cada convidado
int porcao[5]; //Quantidade de porçoẽs que cada convidado comeu
int mandioca = 0; //Quantidade final de mandioca
cin >> porcao[0] >> porcao[1] >> porcao[2] >> porcao[3] >> porcao[4];
for(int i = 0; i < 5; i++)
mandioca += porcao[i]*pesos[i];
cout << mandioca+225 << endl; //Os 225 a mais é por causa da porção da Dona Chica
return 0;
} | true |
b8caa1e79819db49c5effef38945a2083e445c1b | C++ | garrettkinman/ECSE-421-Labs | /Lab 4/a4_e1/a4_e1.ino | UTF-8 | 3,180 | 3.125 | 3 | [] | no_license | #include <Arduino_FreeRTOS.h>
#include "Arduino_SensorKit.h"
#include "loopTimer.h"
#include <semphr.h>
#define BUZZER 5
#define LED 6
// declare tasks
void buzzTask(void *pvParameters);
void ledTask(void *pvParameters);
void messageTask(void *pvParameters);
// declare global mutex for the serial port
SemaphoreHandle_t serialMutex;
void setup() {
Serial.begin(9600);
// create a mutex for the serial port
serialMutex = xSemaphoreCreateMutex();
if (serialMutex == NULL) Serial.println("Mutex cannot be created!");
// construct tasks to run concurrently
// loopTimer seems to take up too much memory, hence its absence
// all tasks are at same priority level, as none is really any more important than the others
xTaskCreate(
ledTask,
"Blink",
128, // stack size
NULL,
2, // priority (1-3, where 3 is highest)
NULL);
xTaskCreate(
buzzTask,
"Buzz",
128, // stack size
NULL,
2, // priority (1-3, where 3 is highest)
NULL);
xTaskCreate(
messageTask,
"Hello, world!",
128, // stack size
NULL,
2, // priority (1-3, where 3 is highest)
NULL);
}
void buzzTask(void *pvParameters) {
(void) pvParameters;
// setup
pinMode(BUZZER, OUTPUT);
// loop
for (;;) {
// turn on for 100 ms
// then turn off for a second
// vTaskDelay(...) hands control back over to the RTOS so other tasks can run
// mutex is here to protect serial port
tone(BUZZER, 85);
xSemaphoreTake(serialMutex, portMAX_DELAY);
Serial.println("'buzz buzz buzz' -a bee, probably");
xSemaphoreGive(serialMutex);
vTaskDelay(100 / portTICK_PERIOD_MS);
noTone(BUZZER);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void ledTask(void *pvParameters) {
(void) pvParameters;
// setup
pinMode(LED, OUTPUT);
// loop
for (;;) {
// turn on for half a second
// then turn off for half a second
// vTaskDelay(...) hands control back over to the RTOS so other tasks can run
// mutex is here to protect serial port
digitalWrite(LED, HIGH);
xSemaphoreTake(serialMutex, portMAX_DELAY);
Serial.println("THIS LED IS ON FIIIIIIIIRE");
xSemaphoreGive(serialMutex);
vTaskDelay(500 / portTICK_PERIOD_MS);
digitalWrite(LED, LOW);
vTaskDelay(500 / portTICK_PERIOD_MS);
}
}
void messageTask(void *pvParameters) {
(void) pvParameters;
// setup
Oled.begin();
Oled.setFlipMode(true);
// loop
for (;;) {
// display for 2 seconds
// then remain clear for 2 seconds
// vTaskDelay(...) hands control back over to the RTOS so other tasks can run
// mutex is here to protect serial port
Oled.setFont(u8x8_font_chroma48medium8_r);
Oled.setCursor(0, 33);
Oled.print("Hello, world!");
Oled.refreshDisplay();
xSemaphoreTake(serialMutex, portMAX_DELAY);
Serial.println("'Hello, world!' is your first program, but is 'Goodbye, cruel world!' your last?");
xSemaphoreGive(serialMutex);
vTaskDelay(2000 / portTICK_PERIOD_MS);
Oled.clear();
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
void loop() {
// empty because all the work is done in tasks (also to make FreeRTOS happy)
}
| true |
3581ea2e4dc806f1135e84efbd021efe13017e07 | C++ | vigusmao/IntroC_2015_2 | /Escola/src/Funcionario.cpp | UTF-8 | 787 | 3.1875 | 3 | [] | no_license | #include "Funcionario.h"
#include <iostream>
#include <string>
using namespace std;
Funcionario::Funcionario(string _nome, int _idade):Pessoa::Pessoa(_nome, _idade)
{
//cout << "Construindo um Funcionário " << endl;
}
Funcionario::Funcionario(string _nome, int _idade, double _salario):Pessoa::Pessoa(_nome, _idade) //passando os parâmetros para o construtor da classe base
{
salario = _salario;
}
Funcionario::~Funcionario()
{
//dtor
}
double Funcionario::getSalario()
{
return salario;
}
void Funcionario::setSalario(double _salario)
{
salario = _salario;
}
void Funcionario::dizOi()
{
cout << "Ola, meu nome é " << nome << ", tenho " << idade << " anos e ganho " << salario << endl;
}
double Funcionario::valorXerox(int qtd)
{
return 0.07 * qtd;
}
| true |
565c224d19febf290abc60fdb7760a763d621a9c | C++ | archer18/homework | /HW2 Q1 near done.cpp | UTF-8 | 4,356 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;
main ()
{
int hour, min, duration;
double cost;
char day;
string Time, Day;
do
{
cout << "What time was the call placed?\n";
cin >> Time;
if ((Time.length () > 4) && (Time.length () < 6))
{
cout << "time confirm = " << Time << endl;
string delimiter = ":";
string StrHour = Time.substr (0, Time.find (delimiter));
string StrMin = Time.substr (3, 4);
cout << "SubStrings confirm = " << StrHour << " : " << StrMin << endl;
hour = stoi (StrHour);
min = stoi (StrMin);
cout << "hour int = " << hour << "\nmin int = " << min <<endl;
if ((hour < 0)||(hour > 24))
{
cout << "\nInvalid Hour Input\n";
cout << "Hours only valid between 0-24";
}
if ((min < 0)||(min > 60))
{
cout << "\nInvalid Minute Input\n";
cout << "Minutes only valid between 0-60\n";
}
}
else
{
cout << "Invaild time format.\n";
cout << "Please use 24 hour time format with leading zero and colon.\n Example, 09:45\n"<<endl;
}
}
while (((Time.length () <= 4) || (Time.length () >= 6))||((hour < 0)||(hour > 24))||((min < 0)||(min > 60)));
cout << endl;
cout << "\nUsing minutes, how long was call?\n";
cin >> duration;
cout << "What day was the call placed?\n";
cin >> Day;
string SubDay = Day.substr (0, 2);
cout << endl << "Day confirmation = " << SubDay << endl;
if ((SubDay == "mo")||(SubDay == "Mo"))
{
cout << "\nCall on monday \n";
if ((hour >= 8)&&(hour <= 18))
{
cout << "$0.40c/min\n";
cost = duration * (0.40);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
if (((hour >= 0)&&(hour < 8))||((hour > 18)&&(hour <= 24)))
{
cout << "$0.25c/min\n";
cost = duration * (0.25);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
}
if ((SubDay == "tu")||(SubDay == "Tu"))
{
cout << "\nCall on Tuesday \n";
if ((hour >= 8)&&(hour <= 18))
{
cout << "$0.40c/min\n";
cost = duration * (0.40);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
if (((hour >= 0)&&(hour < 8))||((hour > 18)&&(hour <= 24)))
{
cout << "$0.25c/min\n";
cost = duration * (0.25);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
}
if ((SubDay == "we")||(SubDay == "We"))
{
cout << "\nCall on Wednesday \n";
if ((hour >= 8)&&(hour <= 18))
{
cout << "$0.40c/min\n";
cost = duration * (0.40);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
if (((hour >= 0)&&(hour < 8))||((hour > 18)&&(hour <= 24)))
{
cout << "$0.25c/min\n";
cost = duration * (0.25);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
}
if ((SubDay == "th")||(SubDay == "Th"))
{
cout << "\nCall on Thursday \n";
if ((hour >= 8)&&(hour <= 18))
{
cout << "$0.40c/min\n";
cost = duration * (0.40);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
if (((hour >= 0)&&(hour < 8))||((hour > 18)&&(hour <= 24)))
{
cout << "$0.25c/min\n";
cost = duration * (0.25);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
}
if ((SubDay == "fr")||(SubDay == "Fr"))
{
cout << "\nCall on monday \n";
if ((hour >= 8)&&(hour <= 18))
{
cout << "$0.40c/min\n";
cost = duration * (0.40);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
if (((hour >= 0)&&(hour < 8))||((hour > 18)&&(hour <= 24)))
{
cout << "$0.25c/min\n";
cost = duration * (0.25);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
}
if (((SubDay == "sa") || (SubDay == "Sa"))||((SubDay == "su") || (SubDay == "Su")))
{
cout << "\nCall on saturday or sunday \n";
cout << "$0.15c/min\n";
cost = duration * (0.15);
cout << "$" << fixed << setprecision (2) << cost << ".\n";
}
cout << endl << "cost is $" << cost << endl;
return 0;
} | true |
6aaa8021953ac4501d7128df07f74857fc6f329f | C++ | Tryneus/Lethe | /LetheCommon/src/windows/WindowsAtomic.cpp | UTF-8 | 2,380 | 2.71875 | 3 | [] | no_license | #include "windows/WindowsAtomic.h"
#include "Windows.h"
#include <intrin.h>
using namespace lethe;
WindowsAtomic32::WindowsAtomic32(const uint32_t value) :
m_data(value)
{
// Do nothing
}
uint32_t WindowsAtomic32::set(uint32_t value)
{
return m_data = value;
}
uint32_t WindowsAtomic32::add(uint32_t value)
{
return _InterlockedExchangeAdd(&m_data, value);
}
uint32_t WindowsAtomic32::subtract(uint32_t value)
{
value = ~value;
return _InterlockedExchangeAdd(&m_data, value);
}
uint32_t WindowsAtomic32::increment()
{
return InterlockedIncrement(&m_data);
}
uint32_t WindowsAtomic32::decrement()
{
return InterlockedDecrement(&m_data);
}
uint32_t WindowsAtomic32::bitwiseAnd(uint32_t value)
{
return _InterlockedAnd(&m_data, value);
}
uint32_t WindowsAtomic32::bitwiseOr(uint32_t value)
{
return _InterlockedOr(&m_data, value);
}
uint32_t WindowsAtomic32::bitwiseXor(uint32_t value)
{
return _InterlockedXor(&m_data, value);
}
bool WindowsAtomic32::bitTestAndSet(uint32_t bit)
{
return (InterlockedBitTestAndSet(&m_data, bit) != 0);
}
bool WindowsAtomic32::bitTestAndReset(uint32_t bit)
{
return (InterlockedBitTestAndReset(&m_data, bit) != 0);
}
#if defined(_M_IA64) || defined(_M_X64)
WindowsAtomic64::WindowsAtomic64(const uint64_t value) :
m_data(value)
{
// Do nothing
}
uint64_t WindowsAtomic64::set(uint64_t value)
{
return InterlockedExchange64(&m_data, value);
}
uint64_t WindowsAtomic64::add(uint64_t value)
{
return _InterlockedExchangeAdd64(&m_data, value);
}
uint64_t WindowsAtomic64::subtract(uint64_t value)
{
value = ~value;
return _InterlockedExchangeAdd64(&m_data, value);
}
uint64_t WindowsAtomic64::increment()
{
return InterlockedIncrement64(&m_data);
}
uint64_t WindowsAtomic64::decrement()
{
return InterlockedDecrement64(&m_data);
}
uint64_t WindowsAtomic64::bitwiseAnd(uint64_t value)
{
return _InterlockedAnd64(&m_data, value);
}
uint64_t WindowsAtomic64::bitwiseOr(uint64_t value)
{
return InterlockedOr64(&m_data, value);
}
uint64_t WindowsAtomic64::bitwiseXor(uint64_t value)
{
return InterlockedXor64(&m_data, value);
}
bool WindowsAtomic64::bitTestAndSet(uint32_t bit)
{
return (_bittestandset64(const_cast<LONG64*>(&m_data), bit) != 0);
}
bool WindowsAtomic64::bitTestAndReset(uint32_t bit)
{
return (_bittestandreset64(const_cast<LONG64*>(&m_data), bit) != 0);
}
#endif
| true |
76ff172ce7365704d8b9705759037b9937f273c0 | C++ | vejmarie/dbus-sensors | /src/NVMeBasicContext.cpp | UTF-8 | 11,898 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include "NVMeBasicContext.hpp"
#include <endian.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <boost/asio/read.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/write.hpp>
#include <cassert>
#include <cerrno>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <system_error>
#include <thread>
extern "C"
{
#include <i2c/smbus.h>
#include <linux/i2c-dev.h>
}
/*
* NVMe-MI Basic Management Command
*
* https://nvmexpress.org/wp-content/uploads/NVMe_Management_-_Technical_Note_on_Basic_Management_Command.pdf
*/
static std::shared_ptr<std::array<uint8_t, 6>>
encodeBasicQuery(int bus, uint8_t device, uint8_t offset)
{
if (bus < 0)
{
throw std::domain_error("Invalid bus argument");
}
/* bus + address + command */
uint32_t busle = htole32(static_cast<uint32_t>(bus));
auto command =
std::make_shared<std::array<uint8_t, sizeof(busle) + 1 + 1>>();
memcpy(command->data(), &busle, sizeof(busle));
(*command)[sizeof(busle) + 0] = device;
(*command)[sizeof(busle) + 1] = offset;
return command;
}
static void decodeBasicQuery(const std::array<uint8_t, 6>& req, int& bus,
uint8_t& device, uint8_t& offset)
{
uint32_t busle;
memcpy(&busle, req.data(), sizeof(busle));
bus = le32toh(busle);
device = req[sizeof(busle) + 0];
offset = req[sizeof(busle) + 1];
}
static ssize_t execBasicQuery(int bus, uint8_t addr, uint8_t cmd,
std::vector<uint8_t>& resp)
{
char devpath[PATH_MAX]{};
int32_t size;
ssize_t rc = snprintf(devpath, sizeof(devpath), "/dev/i2c-%" PRIu32, bus);
if ((size_t)rc > sizeof(devpath))
{
std::cerr << "Failed to format device path for bus " << bus << "\n";
return -EINVAL;
}
int dev = ::open(devpath, O_RDWR);
if (dev == -1)
{
std::cerr << "Failed to open bus device " << devpath << ": "
<< strerror(errno) << "\n";
return -errno;
}
/* Select the target device */
if (::ioctl(dev, I2C_SLAVE, addr) == -1)
{
rc = -errno;
std::cerr << "Failed to configure device address: " << strerror(errno)
<< "\n";
goto cleanup_fds;
}
resp.reserve(UINT8_MAX + 1);
/* Issue the NVMe MI basic command */
size = i2c_smbus_read_block_data(dev, cmd, resp.data());
if (size < 0)
{
rc = size;
std::cerr << "Failed to read block data: " << strerror(errno) << "\n";
goto cleanup_fds;
}
else if (size > UINT8_MAX + 1)
{
rc = -EBADMSG;
std::cerr << "Unexpected message length: " << size << " (" << UINT8_MAX
<< ")\n";
goto cleanup_fds;
}
rc = size;
cleanup_fds:
if (::close(dev) == -1)
{
std::cerr << "Failed to close device descriptor: " << strerror(errno)
<< "\n";
}
return rc;
}
static ssize_t processBasicQueryStream(int in, int out)
{
std::vector<uint8_t> resp{};
ssize_t rc;
while (true)
{
uint8_t device;
uint8_t offset;
uint8_t len;
int bus;
/* bus + address + command */
std::array<uint8_t, sizeof(uint32_t) + 1 + 1> req{};
/* Read the command parameters */
if ((rc = ::read(in, req.data(), req.size())) !=
static_cast<ssize_t>(req.size()))
{
assert(rc < 1);
rc = rc ? -errno : -EIO;
if (errno)
{
std::cerr << "Failed to read request: " << strerror(errno)
<< "\n";
}
goto done;
}
decodeBasicQuery(req, bus, device, offset);
/* Execute the query */
rc = execBasicQuery(bus, device, offset, resp);
/* Bounds check the response */
if (rc < 0)
{
len = 0;
}
else if (rc > UINT8_MAX)
{
assert(rc == UINT8_MAX + 1);
/* YOLO: Lop off the PEC */
len = UINT8_MAX;
}
else
{
len = rc;
}
/* Write out the response length */
if ((rc = ::write(out, &len, sizeof(len))) != sizeof(len))
{
assert(rc < 1);
rc = rc ? -errno : -EIO;
std::cerr << "Failed to write block length to out pipe: "
<< strerror(-rc) << "\n";
goto done;
}
/* Write out the response data */
uint8_t* cursor = resp.data();
while (len > 0)
{
ssize_t egress;
if ((egress = ::write(out, cursor, len)) == -1)
{
rc = -errno;
std::cerr << "Failed to write block data to out pipe: "
<< strerror(errno) << "\n";
goto done;
}
cursor += egress;
len -= egress;
}
}
done:
if (::close(in) == -1)
{
std::cerr << "Failed to close in descriptor: " << strerror(errno)
<< "\n";
}
if (::close(out) == -1)
{
std::cerr << "Failed to close out descriptor: " << strerror(errno)
<< "\n";
}
return rc;
}
/* Throws std::error_code on failure */
/* FIXME: Probably shouldn't do fallible stuff in a constructor */
NVMeBasicContext::NVMeBasicContext(boost::asio::io_service& io, int rootBus) :
NVMeContext::NVMeContext(io, rootBus), io(io), reqStream(io), respStream(io)
{
std::array<int, 2> responsePipe;
std::array<int, 2> requestPipe;
/* Set up inter-thread communication */
if (::pipe(requestPipe.data()) == -1)
{
std::cerr << "Failed to create request pipe: " << strerror(errno)
<< "\n";
throw std::error_code(errno, std::system_category());
}
if (::pipe(responsePipe.data()) == -1)
{
std::cerr << "Failed to create response pipe: " << strerror(errno)
<< "\n";
if (::close(requestPipe[0]) == -1)
{
std::cerr << "Failed to close write fd of request pipe: "
<< strerror(errno) << "\n";
}
if (::close(requestPipe[1]) == -1)
{
std::cerr << "Failed to close read fd of request pipe: "
<< strerror(errno) << "\n";
}
throw std::error_code(errno, std::system_category());
}
reqStream.assign(requestPipe[1]);
int streamIn = requestPipe[0];
int streamOut = responsePipe[1];
respStream.assign(responsePipe[0]);
std::thread thread([streamIn, streamOut]() {
ssize_t rc;
if ((rc = processBasicQueryStream(streamIn, streamOut)) < 0)
{
std::cerr << "Failure while processing query stream: "
<< strerror(-rc) << "\n";
}
if (::close(streamIn) == -1)
{
std::cerr << "Failed to close streamIn descriptor: "
<< strerror(errno) << "\n";
}
if (::close(streamOut) == -1)
{
std::cerr << "Failed to close streamOut descriptor: "
<< strerror(errno) << "\n";
}
std::cerr << "Terminating basic query thread\n";
});
thread.detach();
}
void NVMeBasicContext::readAndProcessNVMeSensor()
{
auto response = std::make_shared<boost::asio::streambuf>();
if (sensors.empty())
{
return;
}
std::shared_ptr<NVMeSensor>& sensor = sensors.front();
/* Ensure sensor query parameters are sensible */
if (sensor->bus < 0)
{
std::cerr << "Bus index cannot be negative: " << sensor->bus << "\n";
sensors.pop_front();
sensors.emplace_back(sensor);
return;
}
auto command = encodeBasicQuery(sensor->bus, 0x6a, 0x00);
/* Issue the request */
boost::asio::async_write(
reqStream, boost::asio::buffer(command->data(), command->size()),
[&command](boost::system::error_code ec, std::size_t) {
if (ec)
{
std::cerr << "Got error writing basic query: " << ec << "\n";
}
});
response->prepare(1);
/* Gather the response and dispatch for parsing */
boost::asio::async_read(
respStream, *response,
[response](const boost::system::error_code& ec, std::size_t n) {
if (ec)
{
std::cerr << "Got error completing basic query: " << ec << "\n";
return static_cast<std::size_t>(0);
}
if (n == 0)
{
return static_cast<std::size_t>(1);
}
std::istream is(response.get());
size_t len = static_cast<std::size_t>(is.peek());
if (n > len + 1)
{
std::cerr << "Query stream has become unsynchronised: "
<< "n: " << n << ", "
<< "len: " << len << "\n";
return static_cast<std::size_t>(0);
}
if (n == len + 1)
{
return static_cast<std::size_t>(0);
}
if (n > 1)
{
return len + 1 - n;
}
response->prepare(len);
return len;
},
[self{shared_from_this()},
response](const boost::system::error_code& ec, std::size_t length) {
if (ec)
{
std::cerr << "Got error reading basic query: " << ec << "\n";
return;
}
if (length == 0)
{
std::cerr << "Invalid message length: " << length << "\n";
return;
}
if (length == 1)
{
std::cerr << "Basic query failed\n";
return;
}
/* Deserialise the response */
response->consume(1); /* Drop the length byte */
std::istream is(response.get());
std::vector<char> data(response->size());
is.read(data.data(), response->size());
self->processResponse(data.data(), data.size());
});
}
void NVMeBasicContext::pollNVMeDevices()
{
scanTimer.expires_from_now(boost::posix_time::seconds(1));
scanTimer.async_wait(
[self{shared_from_this()}](const boost::system::error_code errorCode) {
if (errorCode == boost::asio::error::operation_aborted)
{
return;
}
if (errorCode)
{
std::cerr << errorCode.message() << "\n";
return;
}
self->readAndProcessNVMeSensor();
self->pollNVMeDevices();
});
}
static double getTemperatureReading(int8_t reading)
{
if (reading == static_cast<int8_t>(0x80) ||
reading == static_cast<int8_t>(0x81))
{
// 0x80 = No temperature data or temperature data is more the 5 s
// old 0x81 = Temperature sensor failure
return std::numeric_limits<double>::quiet_NaN();
}
return reading;
}
void NVMeBasicContext::processResponse(void* msg, size_t len)
{
if (msg == nullptr)
{
std::cerr << "Bad message received\n";
return;
}
if (len < 6)
{
std::cerr << "Invalid message length: " << len << "\n";
return;
}
uint8_t* messageData = static_cast<uint8_t*>(msg);
std::shared_ptr<NVMeSensor> sensor = sensors.front();
double value = getTemperatureReading(messageData[2]);
if (std::isfinite(value))
{
sensor->updateValue(value);
}
else
{
sensor->markAvailable(false);
sensor->incrementError();
}
sensors.pop_front();
sensors.emplace_back(sensor);
}
| true |