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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
547232620f3ea16e813c8e9db17e4e6c0ef349c2 | C++ | RobPang/Algorithm_study | /백준알고리즘/BOJ-11049 행렬 곱셈순서.cpp | UTF-8 | 633 | 2.796875 | 3 | [] | no_license | //행렬 곱셈 순서 - dp 각각을 분리
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int r[501];
int c[501];
long long dp[501][501];
long long dfs(int a, int b) {
if (b - a == 1) {
int temp = r[a] * c[a] * c[b];
}
if (a == b) return 0;
long long& res = dp[a][b];
if (res != -1) {
return res;
}
res = 9999999999;
for (int i = a; i <= b-1; i++) {
res = min(res, dfs(a, i) + dfs(i+1, b) + r[a]*c[i]*c[b]);
}
return res;
}
int main() {
int n; cin >> n;
for (int i = 1; i <= n; i++) {
cin >> r[i] >> c[i];
}
memset(dp, -1, sizeof(dp));
cout << dfs(1,n) << '\n';
} | true |
0db452bd351fe7340772802296fbed2e548329c9 | C++ | Maesly/TareaCortaDatos2 | /Singly_Linked_List.h | UTF-8 | 4,491 | 3.390625 | 3 | [] | no_license | //
// Created by parallels on 9/10/17.
//
#ifndef TAREA_SINGLY_LINKED_LIST_H
#define TAREA_SINGLY_LINKED_LIST_H
#include <iostream>
#include <stdlib.h>
using namespace std;
/**
* Inicializa el nodo
*/
struct nodo{
int nro;
struct nodo *sgte;
};
typedef struct nodo *Tlista;
/**
* Inserta valores al inicio de la lista enlazada.
*/
void insertarInicio(Tlista &lista, int valor)
{
Tlista q;
q = new(struct nodo);
q->nro = valor;
q->sgte = lista;
lista = q;
}
/**
*
*/
/**
* Su función es buscar el elemento deseado
* dentro de una lista.
*/
void buscarElemento(Tlista lista, int valor)
{
Tlista q = lista;
int i = 1, band = 0;
while(q!=NULL)
{
if(q->nro==valor)
{
cout<<endl<<" Encontrada en posicion "<< i <<endl;
band = 1;
}
q = q->sgte;
i++;
}
if(band==0)
cout<<"\n\n Numero no encontrado..!"<< endl;
}
/**
* Imprime la Lista
*/
void reportarLista(Tlista lista)
{
int i = 0;
while(lista != NULL)
{
cout <<' '<< i+1 <<") " << lista->nro << endl;
lista = lista->sgte;
i++;
}
}
/**
* Eliminar Elemento
*
*/
void eliminarElemento(Tlista &lista, int valor)
{
Tlista p, ant;
p = lista;
if(lista!=NULL)
{
while(p!=NULL)
{
if(p->nro==valor)
{
if(p==lista)
lista = lista->sgte;
else
ant->sgte = p->sgte;
delete(p);
return;
}
ant = p;
p = p->sgte;
}
}
else
cout<<" Lista vacia..!";
}
/**
*
* Eliminar Repetidos
*/
void eliminaRepetidos(Tlista &lista, int valor){
Tlista q, ant;
q = lista;
ant = lista;
while(q!=NULL)
{
if(q->nro==valor)
{
if(q==lista) // primero elemento
{
lista = lista->sgte;
delete(q);
q = lista;
}
else
{
ant->sgte = q->sgte;
delete(q);
q = ant->sgte;
}
}
else
{
ant = q;
q = q->sgte;
}
}// fin del while
cout<<"\n\n Valores eliminados..!"<<endl;
}
/**
*
* Main
*/
int mainSinglyLinkedList(){
Tlista lista = NULL;
int n;
double t1,t2;
cout << "\n\t\t LISTA ENLAZADA SIMPLE \n\n";
int dato;
cout << " Numero de elementos de la lista: ";
cin >> n;
cout << endl;
srand(time(NULL));
for (int i = 0; i < n; i++) {
int x = rand() % 10000;
insertarInicio(lista, x);
}
cout << "\n\n MOSTRANDO LISTA\n\n";
reportarLista(lista);
cout<<"\n"<<endl;
/**
* t1 y t2 miden el tiempo que tarda el algoritmo
* en buscar un elemento
* en la lista.
*/
int opcion = 0;
while(opcion !=987){
cout<<"1.Buscar un Elemento"<<endl;
cout<<"2.Eliminar Elemento"<<endl;
cout<<"3.Ingresar Elemento"<<endl;
cout<<"4.Salir"<<endl;
cin>>opcion;
switch (opcion){
case 1:
cout << "\n Valor a buscar: ";
cin >> dato;
t1 = clock();
buscarElemento(lista, dato);
t2 = clock();
cout << "\nTiempo Búsqueda: \t: " << ((t2 - t1)/CLOCKS_PER_SEC)*1000<<endl;
break;
case 2:
cout<<"\n Mostrando Lista"<<endl;
reportarLista(lista);
cout << "\n Valor a Eliminar: ";
cin >> dato;
t1 = clock();
eliminarElemento(lista,dato);
t2 = clock();
cout << "\nTiempo Eliminar: \t: " << ((t2 - t1)/CLOCKS_PER_SEC)*1000<<endl;
break;
case 3:
cout << "\n Valor a Ingresar: ";
cin >> dato;
t1 = clock();
insertarInicio(lista,dato);
t2 = clock();
reportarLista(lista);
cout << "\nTiempo Ingreso: \t: " << ((t2 - t1)/CLOCKS_PER_SEC)*1000<<endl;
break;
case 4:
opcion = 987;
break;
default:
cout<<"Opcion Incorrecta"<<endl;
}
}
}
#endif //TAREA_SINGLY_LINKED_LIST_H
| true |
df3e070d90226ba4ce7aaa40e05571f10f95a597 | C++ | jjsuper/leetcode | /leetcode-viewer/solutions/228.summary-ranges/summary-ranges.cpp | UTF-8 | 1,259 | 2.765625 | 3 | [] | no_license | class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> vec;
queue<int> que;
int i;
if(nums.empty()) return vec;
que.push(nums[0]);
for(i=1;i<nums.size();++i)
{
if(nums[i-1]+1!=nums[i])
{
string s;
int head=que.front();
que.pop();
if(head==nums[i-1])
{
s=to_string(head);
vec.push_back(s);
}
else
{
s=to_string(head)+"->"+to_string(nums[i-1]);
vec.push_back(s);
}
que.push(nums[i]);
}
}
while(!que.empty())
{
int tmp=que.front();
que.pop();
if(tmp==nums.back())
{
vec.push_back(to_string(tmp));
}
else
{
string s;
s=to_string(tmp)+"->"+to_string(nums.back());
vec.push_back(s);
}
}
return vec;
}
}; | true |
2195aa33c236771d4518ef3c06c53c1696ae5e96 | C++ | dmccreary/moving-rainbow | /src/arduino/hsb-lab/hsb-lab.ino | UTF-8 | 4,829 | 2.625 | 3 | [] | no_license |
/*
Control a RGB led with Hue, Saturation and Brightness (HSB / HSV )
Hue is change by an analog input.
Brightness is changed by a fading function.
Saturation stays constant at 255
getRGB() function based on <http://www.codeproject.com/miscctrl/CPicker.asp>
dim_curve idea by Jims
created 05-01-2010 by kasperkamperman.com
*/
/*
dim_curve 'lookup table' to compensate for the nonlinearity of human vision.
Used in the getRGB function on saturation and brightness to make 'dimming' look more natural.
Exponential function used to create values below :
x from 0 - 255 : y = round(pow( 2.0, x+64/40.0) - 1)
*/
const byte dim_curve[] = {
0, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6,
6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 11, 11,
11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
15, 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20,
20, 20, 21, 21, 22, 22, 22, 23, 23, 24, 24, 25, 25, 25, 26, 26,
27, 27, 28, 28, 29, 29, 30, 30, 31, 32, 32, 33, 33, 34, 35, 35,
36, 36, 37, 38, 38, 39, 40, 40, 41, 42, 43, 43, 44, 45, 46, 47,
48, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 78, 79, 81, 82,
83, 85, 86, 88, 90, 91, 93, 94, 96, 98, 99, 101, 103, 105, 107, 109,
110, 112, 114, 116, 118, 121, 123, 125, 127, 129, 132, 134, 136, 139, 141, 144,
146, 149, 151, 154, 157, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 190,
193, 196, 200, 203, 207, 211, 214, 218, 222, 226, 230, 234, 238, 242, 248, 255,
};
const int sensorPin = 0; // pin the potmeter is attached too
const int ledPinR = 9; // pwm pin with red led
const int ledPinG = 10; // pwm pin with green led
const int ledPinB = 11; // pwm pin with blue led
int sensorVal = 0; // store the value coming from the sensor
int fadeVal = 0; // value that changes between 0-255
int fadeSpeed = 4; // 'speed' of fading
// getRGB function stores RGB values in this array
// use these values for the red, blue, green led.
int rgb_colors[3];
int hue;
int saturation;
int brightness;
void setup() {
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
Serial.begin(57600);
}
void loop() {
sensorVal = analogRead(sensorPin);
// fade from 0 - 255 and back with a certain speed
fadeVal = fadeVal + fadeSpeed; // change fadeVal by speed
fadeVal = constrain(fadeVal, 0, 255); // keep fadeVal between 0 and 255
if(fadeVal==255 || fadeVal==0) // change from up>down or down-up (negative/positive)
{ fadeSpeed = -fadeSpeed;
}
// set HSB values
hue = map(sensorVal,0, 1023,0, 359); // hue is a number between 0 and 360
saturation = 255; // saturation is a number between 0 - 255
brightness = fadeVal; // value is a number between 0 - 255
getRGB(hue,saturation,brightness,rgb_colors); // converts HSB to RGB
analogWrite(ledPinR, rgb_colors[0]); // red value in index 0 of rgb_colors array
analogWrite(ledPinG, rgb_colors[1]); // green value in index 1 of rgb_colors array
analogWrite(ledPinB, rgb_colors[2]); // blue value in index 2 of rgb_colors array
delay(20); // delay to slow down fading
}
void getRGB(int hue, int sat, int val, int colors[3]) {
/* convert hue, saturation and brightness ( HSB/HSV ) to RGB
The dim_curve is used only on brightness/value and on saturation (inverted).
This looks the most natural.
*/
val = dim_curve[val];
sat = 255-dim_curve[255-sat];
int r;
int g;
int b;
int base;
if (sat == 0) { // Acromatic color (gray). Hue doesn't mind.
colors[0]=val;
colors[1]=val;
colors[2]=val;
} else {
base = ((255 - sat) * val)>>8;
switch(hue/60) {
case 0:
r = val;
g = (((val-base)*hue)/60)+base;
b = base;
break;
case 1:
r = (((val-base)*(60-(hue%60)))/60)+base;
g = val;
b = base;
break;
case 2:
r = base;
g = val;
b = (((val-base)*(hue%60))/60)+base;
break;
case 3:
r = base;
g = (((val-base)*(60-(hue%60)))/60)+base;
b = val;
break;
case 4:
r = (((val-base)*(hue%60))/60)+base;
g = base;
b = val;
break;
case 5:
r = val;
g = base;
b = (((val-base)*(60-(hue%60)))/60)+base;
break;
}
colors[0]=r;
colors[1]=g;
colors[2]=b;
}
}
| true |
d2c92d4e66c75c447eb7f741a83a2ee0ead910c6 | C++ | SashiRin/protrode | /atcoder/abc104/B.cpp | UTF-8 | 1,179 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <stack>
#include <set>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
string s;
cin >> s;
if (s[0] != 'A') {
cout << "WA" << endl;
} else {
int cntC = 0;
int indexC = -1;
for (int i = 2; i < s.length() - 1; ++i) {
if (s[i] == 'C') {
cntC++;
indexC = i;
}
}
if (cntC != 1) {
cout << "WA" << endl;
} else {
bool flag = true;
for (int i = 1; i < s.length(); ++i) {
if (i == indexC) {
continue;
} else {
if (s[i] >= 'a' && s[i] <= 'z') {
continue;
} else {
cout << "WA" << endl;
flag = false;
break;
}
}
}
if (flag)
cout << "AC" << endl;
}
}
return 0;
}
| true |
6cf4c1a7cf6db109e0a827fa3eca6f01cdc50f7b | C++ | debanjan877/Shipping-And-Bidding | /ShippingBiddingC.cpp | UTF-8 | 14,490 | 2.8125 | 3 | [] | no_license | #include<stdlib.h>
#include<iostream.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
#include"headers\Globals.h"
#include"headers\BidInfo.h"
#include"headers\ShipInfo.h"
#include"headers\File.h"
using namespace std;
/* Non Static Functions */
BidInfo::BidInfo()
{
_id=_shipItemId=_shipperId=_timeReqDays=_bidAmount=0;
}
unsigned long BidInfo::getId(){
return_id;
}
unsigned long BidInfo::getShipItemId(){
return _shipItemId;
}
void BidInfo::displayDetails(){
cout<<"\n\tId: "<<_id;
cout<<"\n\tAmount: "<<_bidAmount;
cout<<"\n\tTime Required: "<<_time ReqDAys<<" days";
cout<<endl;
}
void BidInfo::displayAsRow(){
cout<<_id;
cout<<"\t"<<_shipItemId;
cout<<"\t"<<_shipperId;
cout<<"\t"<<_bidAmount;
cout<<"\t"<<_timeReqDays;
cout<<endl;
}
void BidInfo::accept(){
ShipInfo*shipInfo=File<ShipInfo>::find(SHIPINFO_FILE,_shipItenId);
if(shipInfo!=NULL){
shipInfo>setWonBy(_shipperId);
}
}
/* Static Functions */
BidInfo*BidInfo::newEntry(unsigned long shipperId,unsigned long shipItemId){
BidInfo* temp=new BidInfo();
temp->_id=::newId();
temp->_shipperId=shipperId;
temp->_shipItemId=shipItemId;
if(File<BidInfo>::find(BIDINFO_FILE,temp->_id)!=NULL){
cout<<"Internal error.Please retry.";
system('cls");
return BidInfo::newEntry(shipperId,shipItemId);
}
cout<<"\n\tTime Required(days): ";
cin>>temp->_timeReqDays;
cout<<"\n\tamount: ";
cin>>temp->_bidAmount;
if(::canProceed()==1){
File<BidInfo>::insert(BIDINFO_FILE,temp);
return temp;
}
else{
return NULL;
}
}
void BidInfo::displayColumns(){
cout<<"Id";
cout<<"\t"<<"Ship Item Id";
cout<<"\t"<<"Shipper Id";
cout<<"\t"<<"Bid Amount";
cout<<"\t"<<"Time Allocated (days)";
cout<<endl;
cout<<"----------------------------------------------------------------";
cout<<endl;
}
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
#include"headers\Globals.h"
#include"headers\Contact.h"
#include"headers\ShipInfo.h"
#include"headers\File.h"
using namespace std;
/* Non Static Functions */
ShipInfo::ShipInfo(){
_id=_customerId=_wonByShipperId=0;
strcpy(_description,"");
strcpy(_destinationLocation,"");
strcpy(_status,"");
_width=_height=_depth=_weight=_maxAmount=_maxDaysToTransport;
}
unsigned long ShipInfo::getCustomerId(){
return_customerId;
}
unsigned long ShipInfo::getWonByShipperId(){
return_wonByShipperId;
}
const char* ShipInfo::getStatus(){
return_satus;
}
void ShipInfo::close(){
if(::canProceed()){
stcpy(_status,"Closed");
File<ShipInfo>::update(SHIPINFO_FILE,this);
}
}
void ShipInfo::setWonBy(unsigned long shipperId){
if(::canProceed()){
strcpy(_status,"Accepted");
_wonByShipperId=shipperId;
File<ShipInfo>::update(SHIPINFO_FILE,this);
}
}
void ShipInfo::displayDetails(){
cout<<"\n\tId: "<<_id;
cout<<"\n\tCustomer Id: "<<_wonbyShipperId;
cout<<"\n\tDescription: "<<_description;
cout<<"\n\tLocation To: "<<_destinationLocation;
cout<<"\n\tLocation From: "<<_sourceLocation;
cout<<"\n\tWidth: "<<_width;
cout<<"\n\tHeight: "<<_height;
cout<<"\n\tDepth: "<<_dept;
cout<<"\n\tweight: "<<_weight;
cout<<"\n\tMax Bid: "<<_maxAmount;
cout<<"\n\tMax Days: "<<_maxDaysToTransport;
cout<<"\n\tCreated On: "<<ctime(&_createdOn);
cout<<"\n\tExpire On:<<ctime(&_expireOn);
cout<<"\n\tStatus: "<<_status;
cout<<endl;
}
void ShipInfo::displayAsRow(){
cout<<_id;
cout<<"\t"<<_status;
cout<<"\t"<<_sourceLocation;
cout<<"\t"<<_destinationLocation;
cout<<"\t"<<ctime(&_createdOn);
cout<<"\t"<<ctime(&_expireOn);
cout<<"\t"<<_description;
cout<<endl;
}
/* Static Functions */
ShipInfo* ShipInfo::newEntry(unsigned long customerId){
ShipInfo* temp=new ShipINfo();
temp->_id=::newId();
temp->_customerId=customerId;
temp->_createdOn=time(NULL);
strcpy(temp->_status,"New");
if(FIle<ShipInfo>::find(ShIPINFO_FILE,temp->_id)!=NULL){
cout<<"Internal error.Please retry.";
system("cls");
reutrn ShipInfo::newEntry(customerId);
}
cin.ignore();
cout<<"\n\tItem DEscription: ";
cin.getline(temp->_description,255);
cout<<"\tItem weight: ";
cin>>temp->_weight;
cout<<"\tItem height: ";
cin>>temp->_height;
cout<<"\tItem depth: ";
cin>>temp->_depth;
cout<<"\tItem width: ";
cin>>temp->_width;
cin.ignore();
cout<<"\tSource location: ";
cin.getline(temp->_sourceLocation: ";
cin.getline(temp->_destinationLocation,255);
cout<<"\tInitial price: ";
cin>>temp->_maxAmount;
int iVal;
cout<<"\texpire after(days): ";
cin>>iVal;
struct tm* t=localtime(&temp->_createdOn);
t->tm_mday+=iVal;
temp->_expireOn=mktime(t);
cout<<"\tTime allocated(days): ";
cin>>temp->_maxDaystoTransport;
if(::canProceed()==1){
File<ShipInfo>::insert(SHIPINFO_FILE,temp);
return temp;
}
else{
return NULL;
}
}
void ShipInfo::displayColumns(){
cout<<"Id";
cout<<"\t"<<"\tStatus";
cout<<"\t"<<"\tSource Location:";
cout<<"\t"<<"\tDestination Location";
cout<<"\t"<<"\tCreated On";
cout<<"\t"<<"\tExpire On";
cout<<"\t"<<"\tDescription";
cout<<endl;
cout<<"---------------------------------------------------------------------";
cout<<endl;
}
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include"headers\Globals.h"
#include"headers\BidInfo.h"
#include"headers\ShipInfo.h"
#include"headers\File.h"
using namespace std;
Contact* shipper;
void shipperMenu(contact*item){
shipper=item;
int ch;
unsigned long id;
ShipInfo* itemShip=NULL;
BidInfo* itemBid=NULL;
File<ShipInfo>*fShip=NULL;
File<BidInfo>* fBid=NULL;
system("cls");
do{
cout<<"\n*****************************";
cout<<"\nSHIPPER MENU: "<<shipper->getId();
cout<<"\n*****************************";
cout<<"\n1.Display available ship items.";
cout<<"\n2.Display my bids";
cout<<"\n3.Bid details";
cout<<"\n4.New Bid";
cout<<"\n58.clear screen";
cout<<"\n9.Logoff";
cout<<"\nEnter your choice: ";
cin>>ch;
switch(ch){
case 1:
ShipInfo::displayColumns();
fShip=new File<ShipInfo>(SHIPINFO_FILE);
while(!fShip->eof()){
itemShip=fShip->read();
if(itemShip!=NULL &&
strcmp(itemShip->getStatus(),"Closed")!=0 &&
itemShip->getWonByShipperId()==0){
itemShip->displayAsRow();
}
delete(itemShip);
}
::pressKey();
break;
case 2:
BidInfo::displayColumns();
fBid=new File<BidInfo>(BIDINFO_FILE);
while(!fBid->eof()){
itemBid=fBid->read();
if(itemBid!=NULL &&
itemBid->getShipperId()==shipper->getId()){
itemBid->displayAsRow();
}
delete(itemBid);
}
::pressKey();
break;
case 3:
cout<<"enter Bid id: ";
cin>>id;
itemBid=FIle<BidInfo>::find(BIDINFO_FILE,id);
if(itemBid==NULL){
cout<<"no item Found!";
}
else{
itemBid->displayDetails();
delete(itemBid);
}
::pressKey();
break;
case 4:
cout<<"enter ship id: ";
cin>>id;
itemShip=FIle<ShipInfo>::find(SHIPINFO_FILE,id);
if(itemShip==NULL){
cout<<"no item found!";
}
else{
itemShip->displayDetails();
if(::canProceed()==1){
itemBid=BidInfo::newEntry(shipper->getId(),id);
if(itemBid!=NULL){
cout<<"Item successfully created with id: "<<itemBid->getId();
delete(itemBid);
}
}
}
::pressKey();
break;
case 8:
system("cls");
break;
case 9:
system("cls");
break;
default:
cout<<"\tError:101.Invalid option!";
break;
}
}while(ch!=9);
}
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include"headers\Globals.h"
#include"headers\BidInfo.h"
#include"headers\ShipInfo.h"
#include"headers\File.h"
using namespace std;
Contact* customer;
void customerMenu(Contact* item){
customer=item;
int ch;
unsigned long id;
ShipInfo* itemShip=NULL;
BidInfo* itemBid=NULL;
File<ShipInfo>* fShip=NULL;
File<BidInfo>* fBid=NULL;
system("cls");
do{
cout<<"\n***************************************************";
cout<<"\nCUSTOMER MENU : FOR CUSTOMER Id "<<customer->getId();
cout<<"\n***************************************************";
cout<<"\n1.Input an item for shipping";
cout<<"\n2.Remove an item from the list";
cout<<"\n3.Display items whose bidding are not done yet";
cout<<"\n4.Display the all ny items";
cout<<"\n5.Accept Bid";
cout<<"\n8.Clear screen";
cout<<"\n9. Logoff";
cout<<\nEnter your choice: ";
cin>>ch;
switch(ch){
case 1:
system("cls");
cout<<"***********************************************";
cout<<"\n\tNEW SHIP INFORMATION FORM";
cout<<"\n*********************************************";
itemShip=ShipInfo::newEntry(customer->getId());
if(itemShip!=NULL){
cout<<"\nShip Item successfully created with id"<<itemShip->getId();
delete(itemShip);
}
::pressKey();
break;
case 2:
cout<<"Enter Ship Item id: ";
cin>>id;
itemShip=File<ShipInfo>::find(SHIPINFO_FILE,id);
if(itemShip==NULL){
}
else{
itemShip->close();
delete(itemShip);
}
::pressKey();
break;
case 3:
ShipInfo::displayColumns();
fShip=new File<ShipInfo>(SHIPINFO_FILE);
while(!fShip->eof()){
itemShip=fShip->read();
if(itemShip!=NULL &&
itemShip->getCustomerId()==customer->getId()){
itemShip->displayAsRow();
}
delete(itemShip);
}
::pressKey();
break;
case 4:
cout<<"Enter Ship Item Id: ";
cin>>id;
BidInfo::displayColumns();
fBid=new File<BidInfo>(BIDINFO_FILE);
while(!fBid->eof()){
itemBid=fBid->read();
if(itemBid!=NULL &&
itemBid->getShipItemId()==itemBid->getId()){
itemBid->displayAsRow();
}
delete(itemBid);
}
::pressKey();
break;
case 5:
cout<<"enter Bid Item Id: ";
cin>>id;
itemBid=File<BidInfo>::find(BIDINFO_FILE,id);
if(itemBid==NULL){
cout<<"no items found!!!";
}
else{
itemBid->displayDetails();
itemBid->accept();
delete(itemBid);
}
::pressKey();
break;
case 8:
system("cls")
break;
case 9:
system('cls");
break;
default:
cout<<"ERROR:303.Invalid input";
break;
}
}while(ch!=9);
}
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include"headers\Globals.h"
#include"headers\LogWriter.h"
#include"headers\Contact.h"
#include<windows.h>
using namespace std;
void mainMenu();
void contactRegistration(const char* contactType);
void contactLogin(const char* contactType);
void administrations();
void customerMenu(Contact*);
void shipperMenu(Contact*);
void mainMenu(){
int ch;
system("cls");
do{
cout<<"\n**************************************************";
cout<<"\n\tMAIN MENU";
cout<<"\n1.New Customer Registration";
cout<<"\n2.Customer Login";
cout<<"\n3.New Shipper Registration";
cout<<"\n4.Shipper Login";
cout<<"\n8.Clear screen";
cout<<"\n9.Exit";
cout<<"\nEnter your choice: ";
cin>>ch;
switch(ch){
case 1:
contactRegistration("Customer");
break;
case 2:
contactLogin("Customer");
break;
case 3:
contactRegistration("Shipper");
break;
case 4:
contactLogin("Shipper");
break;
case 5:
administrations();
break;
case 8:
system("cls");
break;
case 9:
cout<<"Press any key to exit";
break;
default:
cout<<"ERROR:420...invalid";
break;
}
}while(ch!=9);
}
void contactRegistration(const char* contactType){
system("cls");
cout<<"**********************************************************";
if(strcmpi(contactType,"Customer")==0)
cout<<"\nNEW CUSTOMER REGISTRATION FORM":
else
cout<<"\nNEW SHIPPER REGISTRATION FORM":
cout<<"\n************************************************************";
Contact* temp=Contact::newEntry(contactType);
if(temp!=NULL){
cout<<"\nYour login id: "<<temp->getId();
cout<<"\nPress any key to Continue...":
getchar();
}
}
void contactLogin(const char* contactType){
char sval[20];
unsigned long id;
system("cls");
cout<<"Enter your login Id: ";
cin>>id;
cin.ignore();
cout<<"enter oyur password: ";
cin>>id;
cin.ignore();
cout<<"enter your password:";
strcpy(sval,readPassword());
Contact* temp=Contact::validateLOgin(id,sval);
if(temp!=NULL){
getch();
if(strcmpi(contactType,"Customer")==0)
customerMenu(temp);
else
shipperMenu(temp);
}
else{
cout<<"\nERROR........";
::pressKey();
}
}
void administrations(){
system("cls");
}
int canProceed(){
char ch;
cout<<"\ndo you want to proceed?(y/n): ";
cin>>ch;
if(ch=='y'||ch=='Y')
return 1;
else
return 0;
}
const char* readPassword(){
string pass=="";
char ch;
ch=getch();
while(ch!=13){
pass.push_back(ch);
cout<<'*';
ch=getch();
}
return pass.c_str();
}
int newId(){
unsigned long uid=GetTickCount();
::Sleep(10);
int id=(int)uid;
return id;
}
void pressKey(){
cout<<"\nPress anyKey...";
getch();
}
int main(){
char input=0;
system("cls");
LogWriter::Enable();
mainMenu()
return 1;
}
#include<stdlib.h>
#include<iostream.h>
#include<string.h>
#include"headers\Globals.h"
#include"headers\Contact.h"
//#include"headers\ShipInfo.h"
#include"headers\File.h"
using namespace std;
/* int canProceed();
const char* readPassword();
int newId();*/
/* Non Static Functionc*/
Contact::Contact(){
_id=0;
strcpy(_name,"");
strcpy(_address,"");
strcpy(_type,"");
strcpy(_password,"");
_contactNo=_altContactNo=0;
}
unsigned long Contact::getId(){
return_id;
}
void Contact::displayDetails(){
cout<<"\n\tId: "<<_id;
cout<<"\n\tName: "<<_name;
cout<<"\n\tAddress: "<<_address;
cout<<"\n\tContact No: "<<_contactNo;
cout<<"\n\tAlt Contact No: "<<_altContactno;
cout<<endl;
}
/* Static Functions*/
Contact* Contact::newEntry(const char* contactType){
Contact* temp=new Contact();
temp->_id=::newId();
strcpy(temp-._type,contactType);
if(File<Contact>::(CONTACT_FILE,temp->getId())!=NULL){
cout<<"Internal error.retry";
system("cls");
reutrn Contact::newEntry(contactType);
}
cin.ignore();
cout<<"\n\tName: ";
cin.getline(temp->_name,100);
cout<<"\tAddress: ';
cingetline(temp->_address,500);
cout<<"\tContact No: ";
cin>>temp->_contactno;
cout<<"\tAlt Contactno: ";
cin>>temp->_altContactNo;
| true |
dd9810e0ad7e8e0ec97023e351a061ab624484d5 | C++ | aashrayjain/Simple-Mobile-Phone | /AT_by_serial.ino | UTF-8 | 915 | 3.375 | 3 | [] | no_license | /*
* Author: Devvrat arya
*
* The code enable user to directly enter AT command in Serial window
* The response of GSM also printed on the Serial window
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX // can be replaced to any other PWM pin
/*
* GSM module is connected to software serial (declared as mySerial) at 10, 11 Pin of arduino
*/
void setup()
{
Serial.begin(9600);
Serial.println("Enter AT commands");
mySerial.begin(9600);
delay(500);
}
void loop()
{
if(Serial.available()) // If data available on hard Serial, pirnt it on soft Serial
{
char input=Serial.read();
mySerial.print(input);
}
if(mySerial.available()) // If data available on soft Serial,print it on hard Serial
{
char output=mySerial.read();
Serial.print(output);
}
}
| true |
5cb98a34a5a3c959be3dd875e80bde737af89254 | C++ | MKwiatosz/Programming | /KURS C++ PRATA/Rozdział 3/2.4/2.4/2.4.cpp | UTF-8 | 777 | 3.015625 | 3 | [] | no_license | // 2.4.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
const int MIN = 60;
const int GODZ = 3600;
const int DZIEN = 3600 * 24;
long long sekundy;
cout << "Podaj liczbe sekund: ";
cin >> sekundy;
int dni = sekundy / DZIEN; // ile dni miesci sie w tych sekundach
sekundy = sekundy % DZIEN; // ile dni miesci sie w sekundach tyle ze zwracamy pozostala ilosc sekund
int godziny = sekundy / GODZ;
sekundy = sekundy % GODZ;
int minuty = sekundy / MIN;
sekundy = sekundy % MIN;
cout << sekundy << " sekund to: " << dni << " dni, " << godziny << " godzin, " << minuty << " minut, " << sekundy << " sekund" << endl;
cin.get();
cin.get();
return 0;
}
| true |
838a7625193af5d195763e43ff661ce69a56cd0b | C++ | mickebackman/EDA031 | /clientserver/memorydatabase.cc | UTF-8 | 2,066 | 3.234375 | 3 | [] | no_license | #include "memorydatabase.h"
#include <string>
#include <iostream>
#include "article.h"
#include "newsgroup.h"
#include <vector>
#include <map>
using namespace std;
void MemoryDatabase::addArticle(int newsGroupId, string name, string author, string text){
try{
groups.at(newsGroupId).addArticle(name, author, text);
}catch(...){
// Group does not exist
throw 0;
}
}
void MemoryDatabase::addNewsGroup(string newsGroupName){
for(auto p : groups){
if(p.second.getName() == newsGroupName){
throw runtime_error("The group already exists!");
}
}
groups.insert(make_pair(nextGroupId, NewsGroup(newsGroupName, nextGroupId)));
++nextGroupId;
}
Article MemoryDatabase::getArticle(int newsGroupId, int articleId){
NewsGroup g;
try{
g = groups.at(newsGroupId);
}catch(...){
// group does not exist - 0
throw 0;
}
try{
return g.getArticle(articleId);
}catch(exception& e){
throw 1;
}
}
void MemoryDatabase::deleteArticle(int newsGroupId, int articleId){
try{
groups.at(newsGroupId);
}catch(...){
// group does not exist - 0
throw 0;
}
if(!groups.at(newsGroupId).deleteArticle(articleId)){
throw 1;
}
}
void MemoryDatabase::deleteNewsGroup(int newsGroupId){
auto it = groups.find(newsGroupId);
if(it == groups.end()){
throw runtime_error("The group does not exist!");
}
groups.erase(it);
}
vector<pair<int, string>> MemoryDatabase::getNewsGroups(){
vector<pair<int, string>> result;
for (auto p : groups){
result.push_back(make_pair(p.first, p.second.getName()));
}
return result;
}
map<int, Article> MemoryDatabase::getArticlesInNewsGroup(int newsGroupId){
NewsGroup g;
try{
g = groups.at(newsGroupId);
}catch(...){
// group does not exist - 0
throw 0;
}
return g.getArticles();
}
int MemoryDatabase::numberOfNewsGroups(){
return groups.size();
}
int MemoryDatabase::numberOfArticlesInNewsGroup(int newsGroupId){
try{
return getArticlesInNewsGroup(newsGroupId).size();
}catch(...){
throw 0;
}
}
| true |
474fa25442c88f85ea05511572277a754565aa21 | C++ | ayushsherpa111/GBEmu | /GameBoyEmulator/WRAM.h | UTF-8 | 221 | 2.78125 | 3 | [] | no_license | #pragma once
class WRAM
{
public:
WRAM();
~WRAM();
virtual int ReadByte(long address);
virtual void WriteByte(int value, long address);
protected:
virtual void InitializeRAM();
unsigned char *RAM;
long RAMSize;
};
| true |
0bf1800a441102e95ed4e65b848b02e32566ce90 | C++ | newspring97/coding_test | /Dongju/boj1874.cpp | UTF-8 | 495 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
int n,x;
cin>>n;
stack<int> stck;
int idx=1,t=0;
vector<char> ans(2*n);
for(int i=0;i<n;i++){
cin>>x;
while(stck.empty() || stck.top()!=x)
{
if(idx>n)
{
printf("NO");
return 0;
}
stck.push(idx++);
ans[t++] = '+';
}
stck.pop();
ans[t++]='-';
}
for(int i=0;i<ans.size();i++)
{
cout<<ans[i]<<"\n";
}
return 0;
}
| true |
ad49bfb87644e99af872449901b057e79cf6d072 | C++ | P17seongbin/Graphics_Assn | /Assn4/Project File/Assn1/ObjLoader.hpp | UHC | 6,006 | 2.828125 | 3 | [] | no_license | //Reference : http://www.opengl-tutorial.org/kr/beginners-tutorials/tutorial-7-model-loading/
#pragma once
#include "State.h"
#include "RenderManager.h"
#include <vector>
#include <map>
#include "Const.h"
using namespace std;
class ObjLoader
{
public:
ObjLoader(RenderManager* t);
int findID(std::string name);
bool loadOBJ(vector<string> list);
GLuint vertexbuffer;
private:
std::map<std::string, GLuint> MeshID;
RenderManager* RM;
GLuint VertexArrayID;
};
inline ObjLoader::ObjLoader(RenderManager * t)
{
RM = t;
vector<string> mlist;
string spath = "Meshlist.txt";
const char* path = spath.c_str();
FILE * file = fopen(path, "r");
if (file == NULL) {
printf("Impossible to open the file !\n");
}
while (true) {
char line[127];
// read the first word of the line
int res = fscanf(file, "%s", line);
if (res == EOF)
break; // EOF = End Of File. Quit the loop.
else
{
mlist.push_back(string(line));
}
}
loadOBJ(mlist);
}
inline int ObjLoader::findID(std::string name)
{
std::map<std::string, GLuint>::iterator it = MeshID.find(name);
if (it != MeshID.end())
return it->second;
else return -1;
}
bool ObjLoader::loadOBJ(vector<string> list)
{
std::vector<float> out_vertices(0);
//Obj ణ ؼ Texture File ̸ t prefix Բ .
//Ʈ OBJ ϳϳ ε
for (int i = 0; i < list.size(); i++)
{
std::vector< unsigned int > vertexIndices, uvIndices, normalIndices;
std::vector< glm::vec3 > temp_vertices;
std::vector< glm::vec3 > temp_normals;
std::vector<glm::vec2> temp_uvs;
UnitMesh tmesh;
tmesh.ID = i;
tmesh.offset = out_vertices.size() / 8;
int len = 0;
string t = list[i];
t.append(".obj");
const char* path = t.c_str();
FILE* file;
if (path[0] == '#')
file = fopen(path + 1, "r");
else
file = fopen(path, "r");
if (file == NULL) {
printf("Impossible to open the file %s !\n", path);
return false;
}
tmesh.TextureID = -1;
while (true) {
char lineHeader[128];
// read the first word of the line
int res = fscanf(file, "%s", lineHeader);
if (res == EOF)
break; // EOF = End Of File. Quit the loop.
if (strcmp(lineHeader, "v") == 0) {
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.push_back(vertex);
}
else if (strcmp(lineHeader, "tdds") == 0)
{
char* path = new char[128];
fscanf(file, "%s", path);
tmesh.TextureID = (GLuint)loadDDS(path);
}
else if (strcmp(lineHeader, "tbmp") == 0)
{
char* path = new char[128];
fscanf(file, "%s", path);
tmesh.TextureID = (GLuint)loadBMP(path);
}
else if (strcmp(lineHeader, "vt") == 0) {
glm::vec2 uv;
fscanf(file, "%f %f\n", &uv.x, &uv.y);
temp_uvs.push_back(uv);
}
else if (strcmp(lineHeader, "vn") == 0) {
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
temp_normals.push_back(normal);
}
else if (strcmp(lineHeader, "f") == 0) {
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
if (matches != 9) {
printf("File can't be read by this parser\n");
return false;
}
vertexIndices.push_back(vertexIndex[0]);
vertexIndices.push_back(vertexIndex[1]);
vertexIndices.push_back(vertexIndex[2]);
uvIndices.push_back(uvIndex[0]);
uvIndices.push_back(uvIndex[1]);
uvIndices.push_back(uvIndex[2]);
normalIndices.push_back(normalIndex[0]);
normalIndices.push_back(normalIndex[1]);
normalIndices.push_back(normalIndex[2]);
}
}
// For each vertex of each triangle ( ﰢ ȸմϴ.)
for (unsigned int i = 0; i < vertexIndices.size(); i++) {
//save vertex data
unsigned int vertexIndex = vertexIndices[i];
glm::vec3 vertex = temp_vertices[vertexIndex - 1];
out_vertices.push_back(vertex.x);
out_vertices.push_back(vertex.y);
out_vertices.push_back(vertex.z);
//save uv data
unsigned int uvindex = uvIndices[i];
glm::vec2 uv = temp_uvs[uvindex - 1];
out_vertices.push_back(uv.x);
out_vertices.push_back(uv.y);
//save normal data
unsigned int normalindex = normalIndices[i];
glm::vec3 norm = temp_normals[uvindex - 1];
out_vertices.push_back(norm.x);
out_vertices.push_back(norm.y);
out_vertices.push_back(norm.z);
len++;
}
tmesh.len = len;
printf("%d %d %d %d\n", tmesh.ID, tmesh.len, tmesh.offset, tmesh.TextureID );
RM->enqueueMesh(tmesh);
}
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &vertexbuffer);
// Ʒ ɾ "vertexbuffer" ۿ ؼ ٷϴ.
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// Vertex OpenGL Ѱݴϴ
glBufferData(GL_ARRAY_BUFFER, out_vertices.size() * sizeof(float), &out_vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer(
2,
3, // ũ(size)
GL_FLOAT, // Ÿ(type)
GL_FALSE, // ȭ(normalized)?
8 * sizeof(float), // (stride)
(void*)(5 * sizeof(float)) // 迭 (offset; ű )
);
glVertexAttribPointer(
1,
2,
GL_FLOAT,
GL_FALSE,
8 * sizeof(float),
(void*)(3 * sizeof(float))
);
// ù° Ӽ(attribute) : ؽ
glVertexAttribPointer(
0, // 0° Ӽ(attribute)
3, // ũ(size)
GL_FLOAT, // Ÿ(type)
GL_FALSE, // ȭ(normalized)?
8 * sizeof(float), // (stride)
(void*)0 // 迭 (offset; ű )
);
RM->setVAO(VAO);
RM->setVBO(vertexbuffer);
return true;
} | true |
7b098e4886000a76ce9762e03e337a712fcabe19 | C++ | 1red2blue4/Paradox-Billiards | /BallPhysics.cpp | UTF-8 | 1,651 | 2.828125 | 3 | [] | no_license | #pragma once
#include "BallPhysics.h"
BallPhysics::BallPhysics()
{
netForce = vector3();
velocity = vector3();
speedCap = 1.5f;
gravity = vector3();
freedom = 0.035;
name = "default";
}
BallPhysics::~BallPhysics()
{
//NO MEMORY ALLOCATED
}
void BallPhysics::SetGravity(vector3 yfrc)
{
gravity = yfrc;
}
vector3 BallPhysics::GetGravity()
{
return gravity;
}
void BallPhysics::SetBounce(vector3 bounceFrc)
{
//TODO
bounceForce = bounceFrc;
}
vector3 BallPhysics::GetBounce()
{
return bounceForce;
}
void BallPhysics::AddForce(vector3 frc)
{
netForce += frc;
}
vector3 BallPhysics::ApplyForces(vector3 objectPosition)
{
velocity += netForce;
if (velocity.x*velocity.x + velocity.y*velocity.y + velocity.z*velocity.z > speedCap*speedCap)
{
float vectorDistance = sqrt(velocity.x*velocity.x + velocity.y*velocity.y + velocity.z*velocity.z);
velocity = vector3(velocity.x*speedCap / vectorDistance, velocity.y*speedCap / vectorDistance, velocity.z*speedCap / vectorDistance);
}
objectPosition += velocity;
return objectPosition;
}
void BallPhysics::SetVelocity(vector3 vel)
{
velocity = vel;
}
vector3 BallPhysics::GetVelocity()
{
return velocity;
}
void BallPhysics::ZeroVelocity()
{
SetVelocity(vector3());
}
vector3 BallPhysics::GetForce(void)
{
return netForce;
}
void BallPhysics::SetForce(vector3 frc)
{
netForce = frc;
}
void BallPhysics::SetName(String nm) { name = nm; }
String BallPhysics::GetName() { return name; }
void BallPhysics::SetType(String typ) { type = typ; }
String BallPhysics::GetType() { return type; } | true |
08c5b10fff7741f8e80980432bc81d35b6378708 | C++ | srimedhabc/Data-Structures | /DS/lab 1/ADD_MAX.CPP | UTF-8 | 687 | 2.921875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int A[20][20],B[20][20],C[20][20],i,j,a,b,m,n;
cout<<"enter the number of rows and columns in A and B respectively"<<endl;
cin>>a>>b>>m>>n;
if(a!=m||b!=n)
cout<<"Comparision not possible"<<endl;
else
{
cout<<"enter the elements of A"<<endl;
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
cin>>A[i][j];
}
}
cout<<"enter the elements of B"<<endl;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>B[i][j];
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
if(A[i][j]>B[i][j])
C[i][j]=A[i][j];
else
C[i][j]=B[i][j];
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
cout<<C[i][j]<<ends;
}
cout<<endl;
}
}
return 0;
}
| true |
99680dacf9daf5e82f1370abad92b347a24b9c5b | C++ | jandy14/LinkedListInCPP | /List.h | UTF-8 | 1,783 | 3.15625 | 3 | [] | no_license | template <class T>
class List {
class Node; //전방선언
public:
class Iterator {
public:
Node* current;
private:
bool isReversed;
public:
Iterator():isReversed(false) {}
Iterator(bool pIsReversed):isReversed(pIsReversed) {}
Iterator(bool pIsReversed, Node* pCurrent):isReversed(pIsReversed), current(pCurrent) {}
Iterator& operator++() { return isReversed? Prev() : Next(); }
Iterator& operator--() { return isReversed? Next() : Prev(); }
Iterator operator++(int) { return isReversed? Prev() : Next(); }
Iterator operator--(int) { return isReversed? Next() : Prev(); }
bool operator==(const Iterator& pIter) { return current == pIter.current; }
bool operator!=(const Iterator& pIter) { return current != pIter.current; }
T& operator*() { return current->item; }
private:
Iterator& Next();
Iterator& Prev();
};
private:
class Node {
public:
T item;
Node* prev;
Node* next;
Node(T pItem, Node* pPrev, Node* pNext):item(pItem), next(pNext), prev(pPrev) {}
Node():next(nullptr), prev(nullptr) {}
};
Node begin;
Node end;
int size;
public:
List();
~List();
T& Front();
T& Back();
int Size();
Iterator Begin() { return Iterator(false, begin.next); }
Iterator End() { return Iterator(false, &end); }
Iterator RBegin() { return Iterator(true, end.prev); }
Iterator REnd() { return Iterator(true, &begin); }
void PushFront (const T& item);
void PushBack (const T& item);
T PopFront();
T PopBack();
void InsertRight(Iterator&, const T&);
void InsertLeft(Iterator&, const T&);
void Insert(Iterator&, const T&);
T Erase(Iterator&);
void Clear();
private:
void RemoveNode(Node*);
void LinkNode(Node*);
};
| true |
84805b5ed4a7b3432a20dcd08fc16f056a790040 | C++ | singhshu250/Os_Simulator | /scheduling.cpp | UTF-8 | 26,717 | 3.046875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void roundRobin()
{
cout << "Enter the number of processes: ";
int n, i, j;
cin >> n;
while (n < 0)
{
cout << "Wrong input, try again\nEnter number of processes: ";
cin >> n;
}
vector<tuple<int, int, int, int, int>> times(n); // {at, bt, ct, tat, wt}
for (i = 0; i < n; i++)
{
int t;
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival Time: ";
cin >> t;
while (t < 0)
{
cout << "Wrong input, try again\nArrival time: ";
cin >> t;
}
get<0>(times[i]) = t; // Arrival time
cout << "Burst Time: ";
cin >> t;
while (t < 0)
{
cout << "Wrong input, try again\nBurst time: ";
cin >> t;
}
cout << endl;
get<1>(times[i]) = t; // Burst time
get<2>(times[i]) = 0; // Completion time
get<3>(times[i]) = 0; // Turn around time
get<4>(times[i]) = 0; // Waiting time
}
int ti = INT_MAX; // current time
int slicetime;
cout << "Enter slice time: ";
cin >> slicetime;
while (slicetime <= 0)
{
cout << "Wrong input, try again\nEnter slice time: ";
cin >> slicetime;
}
for (i = 0; i < n; i++)
{
ti = min(ti, get<0>(times[i]));
}
int visited[n] = {0}, bt[n]; // completed programs and Burst time
for (i = 0; i < n; i++)
{
bt[i] = get<1>(times[i]);
}
while (1)
{
int f = 0;
for (i = 0; i < n; i++)
{
if (visited[i])
continue;
if (get<0>(times[i]) <= ti && get<1>(times[i]) > 0)
{
f = 1;
ti += min(bt[i], slicetime);
bt[i] = max(0, bt[i] - slicetime);
if (bt[i] == 0)
{
get<2>(times[i]) = ti;
get<3>(times[i]) = get<2>(times[i]) - get<0>(times[i]);
get<4>(times[i]) = get<3>(times[i]) - get<1>(times[i]);
visited[i] = 1;
}
}
}
if (f == 0)
{
ti++;
}
f = 0;
// checking if all programs completed
for (i = 0; i < n; i++)
{
if (visited[i] == 0)
{
f = 1;
break;
}
}
if (f == 0)
break;
}
double TAT = 0, TWT = 0;
for (i = 0; i < n; i++)
{
TAT += get<3>(times[i]);
TWT += get<4>(times[i]);
}
cout << "\nProcess No.\tArrival Time\tBurst Time\tCompletion Time\t\tTurn-around Time\tWaiting Time\n";
for (i = 0; i < n; i++)
{
cout << i + 1 << "\t\t" << get<0>(times[i]) << "\t\t" << get<1>(times[i]) << "\t\t" << get<2>(times[i]) << "\t\t\t" << get<3>(times[i]) << "\t\t\t" << get<4>(times[i]) << "\n";
}
TAT = TAT / (1.0 * n); // Average TAT
TWT = TWT / (1.0 * n); // Average WT
cout << "\nAverage Turn around time is: " << TAT << "\n";
cout << "Average Waiting time is: " << TWT << "\n";
return;
}
void sjf()
{
int size;
cout << "Enter the number of processes: ";
cin >> size;
int at[size]; //arrival time of each process
int bt[size]; //burst time of each process
for (int i = 0; i < size; i++)
{
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival time: ";
cin >> at[i];
cout << "Burst time: ";
cin >> bt[i];
cout << endl;
}
long long wt[size], tat[size], total_WT = 0, total_TAT = 0;
//finding waiting time
long long rt[size];
for (int i = 0; i < size; i++)
rt[i] = bt[i];
long long comp = 0, t = 0, minm = INT_MAX;
long long shortest = 0, fin_time;
bool check = false;
while (comp != size)
{
for (int j = 0; j < size; j++)
{
if ((at[j] <= t) && (rt[j] < minm) && rt[j] > 0)
{
minm = rt[j];
shortest = j;
check = true;
}
}
if (check == false)
{
t++;
continue;
}
// decrementing the remaining time
rt[shortest]--;
minm = rt[shortest];
if (minm == 0)
minm = INT_MAX;
// If a process gets completly executed
if (rt[shortest] == 0)
{
comp++;
check = false;
fin_time = t + 1;
// Calculate waiting time
wt[shortest] = fin_time - bt[shortest] - at[shortest];
if (wt[shortest] < 0)
wt[shortest] = 0;
}
t++;
}
//turn around time
for (int i = 0; i < size; i++)
tat[i] = bt[i] + wt[i];
cout << "\nProcess No.\tArrival Time\tBurst Time\tTurn-around Time\tWaiting Time\n";
for (int i = 0; i < size; i++)
{
total_TAT += tat[i];
total_WT += wt[i];
cout << i + 1 << "\t\t" << at[i] << "\t\t" << bt[i] << "\t\t" << tat[i] << "\t\t\t" << wt[i] << "\n";
}
cout << "\nAverage Turn around time is: " << (double)total_TAT / size << "\n";
cout << "Average Waiting time is: " << (double)total_WT / size << "\n";
}
void fcfs()
{
cout << "\nEnter the number of processes: ";
int n, i;
cin >> n;
while (n < 0)
{
cout << "Wrong input, try again"
<< "\nEnter number of processes: ";
cin >> n;
}
vector<tuple<int, int, int, int, int>> times(n); // {at, bt, ct, tat, wt}
cout << "Process Details" << endl
<< endl;
for (i = 0; i < n; i++)
{
int t;
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival time: ";
cin >> t;
while (t < 0)
{
cout << "Wrong input, try again\nArrival Time P" << i << ": ";
cin >> t;
}
get<0>(times[i]) = t; // Arrival time
cout << "Burst time: ";
cin >> t;
while (t < 0)
{
cout << "Wrong input, try again\nBurst Time P" << i << ": ";
cin >> t;
}
cout << endl;
get<1>(times[i]) = t; // Burst time
get<2>(times[i]) = 0; // Completion time
get<3>(times[i]) = 0; // Turn around time
get<4>(times[i]) = 0; // Waiting time
}
sort(times.begin(), times.end()); // sorting according to Arrival time
int ti = 0; // current time
for (i = 0; i < n; i++)
{
if (ti < get<0>(times[i]))
ti = get<0>(times[i]);
get<2>(times[i]) = ti + get<1>(times[i]);
ti += get<1>(times[i]);
get<3>(times[i]) = get<2>(times[i]) - get<0>(times[i]);
get<4>(times[i]) = get<3>(times[i]) - get<1>(times[i]);
}
double TAT = 0, TWT = 0;
for (i = 0; i < n; i++)
{
TAT += get<3>(times[i]);
TWT += get<4>(times[i]);
}
cout << "\n"
"Process No.\tArrival Time\tBurst Time\tCompletion Time\t\tTurn-around Time\tWaiting Time\n";
for (i = 0; i < n; i++)
{
cout << i + 1 << "\t\t" << get<0>(times[i]) << "\t\t" << get<1>(times[i]) << "\t\t" << get<2>(times[i]) << "\t\t\t" << get<3>(times[i]) << "\t\t\t" << get<4>(times[i]) << "\n";
}
TAT = TAT / (1.0 * n); // Average TAT
TWT = TWT / (1.0 * n); // Average WT
cout << "\nAverage Turn around time is: " << TAT << "\n";
cout << "Average Waiting time is : " << TWT << "\n";
return;
}
void LJF()
{
struct processes
{
int pid;
int at;
int bt;
int ct;
int tat;
int wt;
};
int n, i, j, sumtat = 0, sumwt = 0;
cout << "Enter no of processes" << endl;
cin >> n;
struct processes arr[n];
struct processes k; // temporary structure used in swapping
for (i = 0; i < n; i++)
{
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival time: ";
cin >> arr[i].at;
cout << "Burst time: ";
cin >> arr[i].bt;
arr[i].pid = i + 1;
cout << endl;
}
//sorting the array of structures according to arrival time and if arrival time is same then sorting it according to processid
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1; j++)
{
if (arr[j].at > arr[j + 1].at)
{
k = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = k;
}
else if (arr[j].at == arr[j + 1].at)
{
if (arr[j].pid > arr[j + 1].pid)
{
k = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = k;
}
}
}
}
//finding the task which will be executed first
int maxt, l = 0;
maxt = arr[0].bt;
for (i = 1; arr[i].at == arr[0].at; i++)
{
if (arr[i].bt > maxt)
{
maxt = arr[i].bt;
l = i;
}
}
k = arr[0];
arr[0] = arr[l];
arr[l] = k;
arr[0].ct = arr[0].at + arr[0].bt;
//sorting the array of structures according to largest burst times for arrival times less than the previous completion time
for (i = 1; i < n; i++)
{
maxt = arr[i].bt;
int val = i;
for (j = i; j < n; j++)
{
if (arr[j].at <= arr[i - 1].ct && arr[j].bt > maxt)
{
maxt = arr[j].bt;
val = j;
}
}
k = arr[i];
arr[i] = arr[val];
arr[val] = k;
//takes account of the case where if all the arrival times are greater than previous completion time
if (arr[i].at > arr[i - 1].ct)
{
arr[i].ct = arr[i].at + arr[i].bt;
}
else
{
arr[i].ct = arr[i - 1].ct + arr[i].bt;
}
}
//finding the turnaround time and the waiting time
for (i = 0; i < n; i++)
{
arr[i].tat = arr[i].ct - arr[i].at;
arr[i].wt = arr[i].tat - arr[i].bt;
sumtat += arr[i].tat;
sumwt += arr[i].wt;
}
cout << "\nProcess No.\tArrival Time\tBurst Time\tCompletion Time\t\tTurn-around Time\tWaiting Time\n";
for (i = 0; i < n; i++)
{
cout << arr[i].pid << "\t" << arr[i].at << "\t" << arr[i].bt << "\t" << arr[i].ct << "\t" << arr[i].tat << "\t" << arr[i].wt << endl;
}
cout << "The average turnaround time is: " << float(sumtat) / float(n) << endl;
cout << "The average waiting time is: " << float(sumwt) / float(n) << endl;
}
//
void LRTF()
{
struct processes
{
int pid;
int at;
int bt;
int ct;
int tat;
int wt;
int rembt;
};
int n, i, j, sumtat = 0, sumwt = 0, timeslice;
cout << "Enter no of processes: ";
cin >> n;
cout << "Enter the timeslice: ";
cin >> timeslice;
struct processes arr[n];
struct processes k; // temporary structure used in swapping
for (i = 0; i < n; i++)
{
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival time: ";
cin >> arr[i].at;
cout << "Burst time: ";
cin >> arr[i].bt;
arr[i].rembt = arr[i].bt;
arr[i].pid = i + 1;
cout << endl;
}
//sorting the array of structures according to arrival time and if arrival time is same then sorting it according to processid
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1; j++)
{
if (arr[j].at > arr[j + 1].at)
{
k = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = k;
}
else if (arr[j].at == arr[j + 1].at)
{
if (arr[j].pid > arr[j + 1].pid)
{
k = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = k;
}
}
}
}
//finding the task which will be executed first
int maxt, l = 0;
maxt = arr[0].bt;
for (i = 1; arr[i].at == arr[0].at; i++)
{
if (arr[i].bt > maxt)
{
maxt = arr[i].bt;
l = i;
}
}
k = arr[0];
arr[0] = arr[l];
arr[l] = k;
int comptasks = 0, currtime = 0;
l = 0;
bool chk[n] = {false};
while (comptasks != n)
{
if (arr[l].at > currtime)
{
currtime = arr[l].at;
}
if (arr[l].rembt <= timeslice)
{
currtime += arr[l].rembt;
arr[l].rembt = 0;
arr[l].ct = currtime;
comptasks++;
}
else
{
currtime += timeslice;
arr[l].rembt -= timeslice;
}
maxt = arr[l].rembt;
for (i = 0; i < n; i++)
{
if (arr[i].at <= currtime && arr[i].rembt > maxt)
{
maxt = arr[i].rembt;
l = i;
}
else if (arr[i].at <= currtime && arr[i].rembt == maxt && arr[i].rembt != 0)
{
if (i < l)
{
l = i;
}
}
}
if (maxt == 0)
{
for (i = 0; i < n; i++)
{
if (arr[i].rembt > 0)
{
l = i;
break;
}
}
}
}
//finding the turnaround time and the waiting time
for (i = 0; i < n; i++)
{
arr[i].tat = arr[i].ct - arr[i].at;
arr[i].wt = arr[i].tat - arr[i].bt;
sumtat += arr[i].tat;
sumwt += arr[i].wt;
}
cout << "The table is as follows: (its shown according to the process that happens first) " << endl;
cout << "\nProcess No.\tArrival Time\tBurst Time\tCompletion Time\t\tTurn-around Time\tWaiting Time\n";
for (i = 0; i < n; i++)
{
cout << arr[i].pid << "\t\t" << arr[i].at << "\t\t" << arr[i].bt << "\t\t" << arr[i].ct << "\t\t\t\t" << arr[i].tat << "\t\t" << arr[i].wt << endl;
}
cout << "The average turnaround time is: " << float(sumtat) / float(n) << endl;
cout << "The average waiting time is: " << float(sumwt) / float(n) << endl;
}
//priority premptive
struct Process
{
int processID;
int burstTime;
int tempburstTime;
int responsetime;
int arrivalTime;
int priority;
int outtime;
int intime;
};
// It is used to include all the valid and eligible
// processes in the heap for execution. heapsize defines
// the number of processes in execution depending on
// the current time currentTime keeps a record of
// the current CPU time.
void insert(Process Heap[], Process value, int *heapsize,
int *currentTime)
{
int start = *heapsize, i;
Heap[*heapsize] = value;
if (Heap[*heapsize].intime == -1)
Heap[*heapsize].intime = *currentTime;
++(*heapsize);
// Ordering the Heap
while (start != 0 && Heap[(start - 1) / 2].priority >
Heap[start].priority)
{
Process temp = Heap[(start - 1) / 2];
Heap[(start - 1) / 2] = Heap[start];
Heap[start] = temp;
start = (start - 1) / 2;
}
}
// It is used to reorder the heap according to
// priority if the processes after insertion
// of new process.
void order(Process Heap[], int *heapsize, int start)
{
int smallest = start;
int left = 2 * start + 1;
int right = 2 * start + 2;
if (left < *heapsize && Heap[left].priority <
Heap[smallest].priority)
smallest = left;
if (right < *heapsize && Heap[right].priority <
Heap[smallest].priority)
smallest = right;
// Ordering the Heap
if (smallest != start)
{
Process temp = Heap[smallest];
Heap[smallest] = Heap[start];
Heap[start] = temp;
order(Heap, heapsize, smallest);
}
}
// This function is used to find the process with
// highest priority from the heap. It also reorders
// the heap after extracting the highest priority process.
Process extractminimum(Process Heap[], int *heapsize,
int *currentTime)
{
Process min = Heap[0];
if (min.responsetime == -1)
min.responsetime = *currentTime - min.arrivalTime;
--(*heapsize);
if (*heapsize >= 1)
{
Heap[0] = Heap[*heapsize];
order(Heap, heapsize, 0);
}
return min;
}
// Compares two intervals according to staring times.
bool compare(Process p1, Process p2)
{
return (p1.arrivalTime < p2.arrivalTime);
}
int prevtime = -1;
// This function is responsible for executing
// the highest priority extracted from Heap[].
void scheduling(Process Heap[], Process array[], int n,
int *heapsize, int *currentTime)
{
if (heapsize == 0)
return;
Process min = extractminimum(Heap, heapsize, currentTime);
min.outtime = *currentTime + 1;
--min.burstTime;
if (prevtime != *currentTime)
{
printf(" %d\t %d \n",
*currentTime, min.processID);
prevtime = *currentTime;
}
// If the process is not yet finished
// insert it back into the Heap*/
if (min.burstTime > 0)
{
insert(Heap, min, heapsize, currentTime);
return;
}
for (int i = 0; i < n; i++)
if (array[i].processID == min.processID)
{
array[i] = min;
break;
}
}
// This function is responsible for
// managing the entire execution of the
// processes as they arrive in the CPU
// according to their arrival time.
void priority(Process array[], int n)
{
sort(array, array + n, compare);
int totalwaitingtime = 0, totalbursttime = 0,
totalturnaroundtime = 0, i, insertedprocess = 0,
heapsize = 0, currentTime = array[0].arrivalTime,
totalresponsetime = 0;
Process Heap[4 * n];
// Calculating the total burst time
// of the processes
for (int i = 0; i < n; i++)
{
totalbursttime += array[i].burstTime;
array[i].tempburstTime = array[i].burstTime;
}
printf("At\tProcess\n");
// Inserting the processes in Heap
// according to arrival time
do
{
if (insertedprocess != n)
{
for (i = 0; i < n; i++)
{
if (array[i].arrivalTime == currentTime)
{
++insertedprocess;
array[i].intime = -1;
array[i].responsetime = -1;
insert(Heap, array[i], &heapsize, ¤tTime);
}
}
}
scheduling(Heap, array, n, &heapsize, ¤tTime);
++currentTime;
if (heapsize == 0 && insertedprocess == n)
break;
} while (1);
for (int i = 0; i < n; i++)
{
totalresponsetime += array[i].responsetime;
totalwaitingtime += (array[i].outtime - array[i].intime -
array[i].tempburstTime);
totalbursttime += array[i].burstTime;
}
printf("Average waiting time = %f\n",
((float)totalwaitingtime / (float)n));
printf("Average response time =%f\n",
((float)totalresponsetime / (float)n));
printf("Average turn around time = %f\n",
((float)(totalwaitingtime + totalbursttime) / (float)n));
}
// Driver code
void priority_premptive()
{
int n, i;
cout << "Enter the number of processes: ";
cin >> n;
Process a[n];
for (i = 0; i < n; i++)
{
a[i].processID = i + 1;
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival time: ";
cin >> a[i].arrivalTime;
cout << "Burst time: ";
cin >> a[i].burstTime;
cout << "Piority: ";
cin >> a[i].priority;
cout << endl;
}
priority(a, n);
return;
}
//hrrn
struct node
{
int pname;
int btime;
int atime;
int wtime;
float rr = 0;
} a[50];
void insert(int n)
{
int i;
for (int i = 0; i < n; i++)
{
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival time: ";
cin >> a[i].atime;
cout << "Burst time: ";
cin >> a[i].btime;
a[i].rr = 0;
a[i].pname = i + 1;
a[i].wtime = -a[i].atime;
cout << endl;
}
}
bool btimeSort(node a, node b)
{
return a.btime < b.btime;
}
bool atimeSort(node a, node b)
{
return a.atime < b.atime;
}
bool rrtimeSort(node a, node b)
{
return a.rr > b.rr;
}
void disp(int n)
{
sort(a, a + n, btimeSort);
sort(a, a + n, atimeSort);
int ttime = 0, i;
int j, tArray[n];
for (i = 0; i < n; i++)
{
j = i;
while (a[j].atime <= ttime && j != n)
{
j++;
}
for (int q = i; q < j; q++)
{
a[q].wtime = ttime - a[q].atime;
a[q].rr = (float)(a[q].wtime + a[q].btime) / (float)a[q].btime;
}
sort(a + i, a + j, rrtimeSort);
tArray[i] = ttime;
cout << endl;
ttime += a[i].btime;
}
tArray[i] = ttime;
float averageWaitingTime = 0;
float averageResponseTime = 0;
float averageTAT = 0;
cout << "\nProcess No.\tArrival Time\tBurst Time\tCompletion Time\t\tTurn-around Time\tWaiting Time\n";
for (i = 0; i < n; i++)
{
cout << 'P' << a[i].pname << "\t\t";
cout << a[i].atime << "\t\t";
cout << a[i].btime << "\t\t";
cout << tArray[i + 1] << "\t\t";
cout << tArray[i] - a[i].atime + a[i].btime << "\t\t";
averageTAT += tArray[i] - a[i].atime + a[i].btime;
cout << a[i].wtime << "\t\t";
averageWaitingTime += tArray[i] - a[i].atime;
cout << tArray[i] - a[i].atime << "\t\t";
averageResponseTime += tArray[i] - a[i].atime;
cout << "\n";
}
cout << "\n";
cout << "\n";
cout << "Average Response time: " << (float)averageResponseTime / (float)n << endl;
cout << "Average Waiting time: " << (float)averageWaitingTime / (float)n << endl;
cout << "Average TA time: " << (float)averageTAT / (float)n << endl;
}
void hrrn()
{
int nop, choice, i;
cout << "Enter number of processes: ";
cin >> nop;
insert(nop);
disp(nop);
return;
}
//SRTF
struct process_srtf
{
int pid;
int arrival_time;
int burst_time;
int start_time;
int completion_time;
int turnaround_time;
int waiting_time;
int response_time;
};
void srtf()
{
int n;
struct process_srtf p[100];
float avg_turnaround_time;
float avg_waiting_time;
float avg_response_time;
float cpu_utilisation;
int total_turnaround_time = 0;
int total_waiting_time = 0;
int total_response_time = 0;
int total_idle_time = 0;
float throughput;
int burst_remaining[100];
int is_completed[100];
memset(is_completed, 0, sizeof(is_completed));
cout << setprecision(2) << fixed;
cout << "Enter the number of processes: ";
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "For process " << i + 1 << ":" << endl;
cout << "Arrival Time: ";
cin >> p[i].arrival_time;
cout << "Burst time"
<< ": ";
cin >> p[i].burst_time;
p[i].pid = i + 1;
burst_remaining[i] = p[i].burst_time;
cout << endl;
}
int current_time = 0;
int completed = 0;
int prev = 0;
while (completed != n)
{
int idx = -1;
int mn = 10000000;
for (int i = 0; i < n; i++)
{
if (p[i].arrival_time <= current_time && is_completed[i] == 0)
{
if (burst_remaining[i] < mn)
{
mn = burst_remaining[i];
idx = i;
}
if (burst_remaining[i] == mn)
{
if (p[i].arrival_time < p[idx].arrival_time)
{
mn = burst_remaining[i];
idx = i;
}
}
}
}
if (idx != -1)
{
if (burst_remaining[idx] == p[idx].burst_time)
{
p[idx].start_time = current_time;
total_idle_time += p[idx].start_time - prev;
}
burst_remaining[idx] -= 1;
current_time++;
prev = current_time;
if (burst_remaining[idx] == 0)
{
p[idx].completion_time = current_time;
p[idx].turnaround_time = p[idx].completion_time - p[idx].arrival_time;
p[idx].waiting_time = p[idx].turnaround_time - p[idx].burst_time;
p[idx].response_time = p[idx].start_time - p[idx].arrival_time;
total_turnaround_time += p[idx].turnaround_time;
total_waiting_time += p[idx].waiting_time;
total_response_time += p[idx].response_time;
is_completed[idx] = 1;
completed++;
}
}
else
{
current_time++;
}
}
int min_arrival_time = 10000000;
int max_completion_time = -1;
for (int i = 0; i < n; i++)
{
min_arrival_time = min(min_arrival_time, p[i].arrival_time);
max_completion_time = max(max_completion_time, p[i].completion_time);
}
avg_turnaround_time = (float)total_turnaround_time / n;
avg_waiting_time = (float)total_waiting_time / n;
avg_response_time = (float)total_response_time / n;
// cpu_utilisation = ((max_completion_time - total_idle_time) / (float)max_completion_time) * 100;
// throughput = float(n) / (max_completion_time - min_arrival_time);
cout << endl
<< endl;
cout << "\nProcess No.\tArrival Time\tStart Time\tBurst Time\tCompletion Time\t\tTurn-around Time\tWaiting Time\tResponse Time\n";
for (int i = 0; i < n; i++)
{
cout << p[i].pid << "\t\t" << p[i].arrival_time << "\t\t" << p[i].burst_time << "\t\t" << p[i].start_time << "\t\t" << p[i].completion_time << "\t\t\t\t" << p[i].turnaround_time << "\t\t" << p[i].waiting_time << "\t\t" << p[i].response_time << "\t\t"
<< "\n"
<< endl;
}
cout << "Average Turnaround Time = " << avg_turnaround_time << endl;
cout << "Average Waiting Time = " << avg_waiting_time << endl;
cout << "Average Response Time = " << avg_response_time << endl;
}
| true |
66d18e5dfbd6d22420853e49046eaf0c44129c69 | C++ | MintYiqingchen/learnByCode | /c++/template/variableTuple.cpp | UTF-8 | 2,363 | 3.3125 | 3 | [] | no_license | #include <memory>
#include <vector>
#include <iostream>
#include <numeric>
#include <utility>
using namespace std;
// test 1
namespace test {
template <typename T, typename... Args>
inline unique_ptr<T> make_unique(Args&&... args)
{
return unique_ptr<T>(new T(forward<Args>(args)...));
}
}
// test 2
template <typename T>
constexpr auto sum(T x)
{
return x;
}
template <typename T1, typename T2, typename... Targ>
constexpr auto sum(T1 x, T2 y, Targ... args)
{
return sum(x + y, args...);
}
// test 3
template <typename... Args>
auto compose() {
return [](auto&&... x) {return compose<Args...>();};
}
template <typename F>
auto compose(F f)
{
return [f](auto&&... x) {
return f(forward<decltype(x)>(x)...);
};
}
template <typename F, typename... Args>
auto compose(F f, Args... other)
{
return [f, other...](auto&&... x) {
return f(compose(other...)(forward<decltype(x)>(x)...));
};
}
template <template <typename, typename> class OutContainer = vector, typename F, class R>
auto fmap(F&& f, R&& inputs)
{
typedef decay_t<decltype(f(*inputs.begin()))> result_type;
OutContainer<result_type, allocator<result_type>> result;
for (auto&& item : inputs) {
result.push_back(f(item));
}
return result;
}
// test 4
constexpr int count_bits(unsigned char value)
{
if (value == 0) {
return 0;
} else {
return (value & 1) + count_bits(value >> 1);
}
}
template <size_t... V>
struct bit_count_t {
unsigned char count[sizeof...(V)] = {static_cast<unsigned char>(count_bits(V))...};
};
template <size_t... V>
bit_count_t<V...> get_bit_count(index_sequence<V...>)
{
return bit_count_t<V...>();
}
auto bit_count = get_bit_count(
make_index_sequence<256>());
int main(int argc, char** argv) {
auto a = test::make_unique<vector<int>>(100, 1);
auto b = sum(1,1.2, 1.3,10, -2);
cout << b << endl;
// test 3
auto square_list = [](auto&& container) {
return fmap([](int x) { return x * x; }, container);};
auto sum_list = [](auto&& container) {
return accumulate(container.begin(),container.end(), 0);};
auto square_sum = compose(sum_list, square_list);
auto c = vector<int>{1,2,3,4};
cout << square_sum(c) << endl;
// test 4
auto bitStruct = get_bit_count(make_index_sequence<256>());
cout << sizeof(bitStruct.count) << endl;
} | true |
5b502e33330149d38c1add2a780b83c3b1918b60 | C++ | ethanmick/Blowfish482 | /Blowfish.cpp | UTF-8 | 4,661 | 2.84375 | 3 | [] | no_license | #include "Blowfish.h"
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
Blowfish::Blowfish() {
hexStart = 0;
}
uint32_t Blowfish::blockSize(){
return 8;
}
uint32_t Blowfish::keySize(){
//56 is the maximum, this is variable
return 8;
}
void Blowfish::setKey(uint8_t* key){
for (int i = 0; i < 18; i++) {
pArray[i] = computeHexPi();
}
for (int i=0; i < 256; i++) {
s1[i] = computeHexPi();
}
for (int i=0; i < 256; i++) {
s2[i] = computeHexPi();
}
for (int i=0; i < 256; i++) {
s3[i] = computeHexPi();
}
for (int i=0; i < 256; i++) {
s4[i] = computeHexPi();
}
uint32_t key_size = keySize();
uint32_t subkeyCounter = 0;
for (int pI=0; pI < 18; pI++) {
uint32_t subkey = 0;
for (int i=0; i < 4; i++, subkeyCounter++) {
if (subkeyCounter >= key_size) {
subkeyCounter = 0;
}
subkey <<= 8;
subkey |= (uint32_t)key[subkeyCounter];
}
pArray[pI] ^= subkey;
}
uint8_t* zeros = new uint8_t[ 8 ];
for( int i = 0; i < 8; i++ ){
zeros[ i ] = 0;
}
for (int i=0; i < 18; i += 2) {
encrypt(zeros);
pArray[i] = pack32BitWord(zeros, 0);
pArray[i+1] = pack32BitWord(zeros, 4);
}
for (int i=0; i < 256; i += 2) {
encrypt(zeros);
s1[i] = pack32BitWord(zeros, 0);
s1[i+1] = pack32BitWord(zeros, 4);
}
for (int i=0; i < 256; i += 2) {
encrypt(zeros);
s2[i] = pack32BitWord(zeros, 0);
s2[i+1] = pack32BitWord(zeros, 4);
}
for (int i=0; i < 256; i += 2) {
encrypt(zeros);
s3[i] = pack32BitWord(zeros, 0);
s3[i+1] = pack32BitWord(zeros, 4);
}
for (int i=0; i < 256; i += 2) {
encrypt(zeros);
s4[i] = pack32BitWord(zeros, 0);
s4[i+1] = pack32BitWord(zeros, 4);
}
}
void Blowfish::encrypt(uint8_t* text){
uint32_t xL, xR, temp;
xL = pack32BitWord( text, 0 );
xR = pack32BitWord( text, 4 );
for( int i = 0; i <= 15; i++ ){
xL ^= pArray[ i ];
xR ^= F( xL );
temp = xL;
xL = xR;
xR = temp;
}
temp = xL;
xL = xR;
xR = temp;
xR ^= pArray[ 16 ];
xL ^= pArray[ 17 ];
//merge into xR and xL into xL
uint64_t final = 0;
final |= xL;
final <<= 32;
final |= xR;
//now final is the ciphertext, need to convert to ascii
text[ 0 ] = final >> 56;
text[ 1 ] = final >> 48;
text[ 2 ] = final >> 40;
text[ 3 ] = final >> 32;
text[ 4 ] = final >> 24;
text[ 5 ] = final >> 16;
text[ 6 ] = final >> 8;
text[ 7 ] = final;
}
uint32_t Blowfish::F( uint32_t input ){
uint8_t a, b, c, d;
d = (uint8_t) input;
input >>= 8;
c = (uint8_t) input;
input >>= 8;
b = (uint8_t) input;
input >>= 8;
a = (uint8_t) input;
return ( ( s1[ a ] + s2[ b ] ) ^ s3[ c ] ) + s4[ d ];
}
uint32_t Blowfish::pack32BitWord( uint8_t* input, uint32_t startVal ){
uint32_t result = 0;
for( unsigned int i = startVal; i < startVal + 4; i++ ){
result <<= 8;
result |= input[ i ];
}
return result;
}
uint32_t Blowfish::computeHexPi() {
double s1 = series(hexStart, 1);
double s2 = series(hexStart, 4);
double s3 = series(hexStart, 5);
double s4 = series(hexStart, 6);
double pi = (4.0 * s1) - (2.0 * s2) - s3 - s4;
pi = pi - (int)pi + 1.0;
uint32_t pihex= 0;
for (int i=0; i < 8; i++) {
pi *= 16;
uint32_t hVal = floor(pi);
pihex <<= 4;
pihex |= hVal;
pi -= hVal;
}
hexStart += 8;
return pihex;
}
double Blowfish::series(uint32_t d, uint32_t j) {
double sum = 0;
for ( unsigned int k = 0; k < d; k++ ) {
sum += (binaryExp(16, (d - k), (8 * k + j))) / (8 * k + j);
sum = sum - (int)sum;
}
for ( unsigned int k = d; k < d + 100; k++ ) {
sum += pow(16.0, (double) d - k) / (8 * k + j);
sum = sum - (int)sum;
}
return sum;
}
double Blowfish::binaryExp(int b, int n, double mod) {
if (mod == 1.0) {
return 0;
}
// Largest power of 2 less than n
double t = pow(2, floor(log2(n)));
double r = 1;
while (t >= 1) {
if (n >= t) {
r = fmod(b * r, mod);
n = n - t;
}
t = t / 2;
if (t >= 1) {
r = fmod(r * r, mod);
}
}
return r;
}
| true |
54dff18e0e92589ce104112c9700b511459492da | C++ | patrickfreed/regency | /world/Region.cpp | UTF-8 | 4,102 | 3.078125 | 3 | [] | no_license | #include <regency/world/Region.h>
#include <regency/Game.h>
namespace regency::world {
Region::Region(Location a, Location b, bool checks):
_world(Game::get_instance().get_world()), _a(a), _b(b) {
_min_x = std::min(_a.get_x(), _b.get_x());
_min_y = std::min(_a.get_y(), _b.get_y());
_max_x = std::max(_a.get_x(), _b.get_x());
_max_y = std::max(_a.get_y(), _b.get_y());
if (checks) {
_using_marks = true;
_marks.resize(size());
}
}
Region& Region::operator=(const Region& other) {
_min_x = other._min_x;
_max_x = other._max_x;
_a = other._a;
_b = other._b;
_using_marks = other._using_marks;
_marks = other._marks;
_min_y = other._min_y;
_max_y = other._max_y;
return *this;
}
bool Region::contains(const Location& loc) const {
return _min_x <= loc.get_x() && loc.get_x() <= _max_x &&
_min_y <= loc.get_y() && loc.get_y() <= _max_y;
}
int Region::get_max_x() {
return _max_x;
}
int Region::get_min_x() {
return _min_x;
}
int Region::get_max_y() {
return _max_y;
}
int Region::get_min_y() {
return _min_y;
}
int Region::size() {
return (_max_x - _min_x + 1) * (_max_y - _min_y + 1);
}
bool Region::is_marked(int x, int y)const {
if (!_using_marks) {
return false;
}
int width = _max_x - _min_x + 1;
return _marks[(x - _min_x) % width + (y - _min_y) * width];
}
bool Region::is_marked(const Tile &t) {
return is_marked(t.get_location().get_x(), t.get_location().get_y());
}
void Region::set_marked(int x, int y, bool mark) {
if (!_using_marks) {
_marks.resize(size());
_using_marks = true;
}
int width = _max_x - _min_x + 1;
_marks[(x - _min_x) % width + (y - _min_y) * width] = mark;
}
void Region::set_marked(const Tile &t, bool mark) {
set_marked(t.get_location().get_x(), t.get_location().get_y(), mark);
}
int Region::get_number_marked() const {
int num = 0;
for (int x = _min_x; x <= _max_x; ++x) {
for (int y = _min_y; y <= _max_y; ++y) {
if (is_marked(x, y)) {
++num;
}
}
}
return num;
}
Region::RegionIterator Region::begin() const {
return RegionIterator(*this);
}
Region::RegionIterator Region::end() const {
RegionIterator it(*this);
it._y = it._max_y + 1;
it._x = it._min_x;
return it;
}
Location Region::get_closest_point(Location other) {
int x = std::min(std::max(_min_x, other.get_x()), _max_x);
int y = std::min(std::max(_min_y, other.get_y()), _max_y);
return Location{x, y};
}
bool Region::is_on_border(const Location& l) {
return contains(l) && (l.get_y() == _min_y || l.get_y() == _max_y || l.get_x() == _max_x || l.get_x() == _min_x);
}
Region::RegionIterator::RegionIterator(const Region& region) {
_world = ®ion._world;
_x = region._min_x;
_y = region._min_y;
_min_x = _x;
_min_y = _y;
_max_x = region._max_x;
_max_y = std::max(region._a.get_y(), region._b.get_y());
}
Region::RegionIterator &Region::RegionIterator::operator++() {
_x++;
if (_x > _max_x) {
_x = _min_x;
_y++;
}
}
Tile& Region::RegionIterator::operator*() {
if (!_world || _y > _max_y) {
throw std::runtime_error("dereferencing end iterator");
}
return _world->get_tile(_x, _y);
}
bool Region::RegionIterator::operator==(const Region::RegionIterator &other) const {
return other._x == _x && other._y == _y && other._world == _world &&
other._min_x == _min_x && other._max_x == _max_x && other._max_y == _max_y &&
other._min_y == _min_y;
}
bool Region::RegionIterator::operator!=(const Region::RegionIterator &other) const {
return !(other == *this);
}
int Region::get_width() {
return _max_x - _min_x + 1;
}
int Region::get_height() {
return _max_y - _min_y + 1;
}
bool Region::intersects(Region& other) {
if (_min_x > other._max_x || other._min_x > _max_x) {
return false;
} else return !(_min_y > other._max_y || other._min_y > _max_y);
}
}
| true |
b3f56d29340c5f2c6fbfebf6882309fa5c81bb6f | C++ | zhufangda/Telecom-Paristech | /IGR201/QT/paintExample/paintarea.cpp | UTF-8 | 3,892 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #include "paintarea.h"
#include <QApplication>
#include<iostream>
PaintArea::PaintArea(QWidget *parent):QWidget(parent)
{
QPalette pal = palette();
pal.setColor(QPalette::Background, Qt::white);
this->setAutoFillBackground(true);
this->setPalette(pal);
this->setMinimumSize(500,400);
myPenColor=Qt::blue;
myPenWidth=3;
}
void PaintArea::paintEvent(QPaintEvent *event)
{
//std::cout << pens.length();
QWidget::paintEvent(event);
QPainter painter(this);
myPen.setColor(myPenColor);
myPen.setWidth(myPenWidth);
painter.setPen(myPen);
//painter.drawPath(xxx);
//Qlist<QPainterPath>
for(int i=0; i<paths.size();i++){
painter.setPen(pens[i]);
painter.drawPath(paths[i]);
}
switch(state){
case 1 :
path = QPainterPath();
path.moveTo(startPoint);
path.lineTo(endPoint);
painter.drawPath(path);
break;
case 2 :
path = QPainterPath();
path.moveTo(startPoint);
path.addEllipse(startPoint.x(), startPoint.y(), endPoint.x() - startPoint.x(), endPoint.y() - startPoint.y());
painter.drawPath(path);
break;
case 3 :
path = QPainterPath();
path.moveTo(startPoint);
path.addRect(startPoint.x(), startPoint.y(), endPoint.x() - startPoint.x(), endPoint.y() - startPoint.y());
painter.drawPath(path);
break;
default:
break;
}
}
/* for(int i=0; i<_lines.size();i++){
const QVector<QPoint> &line = _lines.at(i);
const QVector<QPen> &penAttribute = _pensAttribute.at(i);
for(int j=0;j<line.size()-1;j++){
painter.setPen(penAttribute.at(j));
painter.drawLine(line.at(j), line.at(j+1));
}
}
}*/
void PaintArea::setPenColor(const QColor &newColor){
myPenColor=newColor;
}
void PaintArea::setPenWidth(int newWidth){
myPenWidth=newWidth;
}
void PaintArea::setState(int choice){
state=choice;
}
void PaintArea::mousePressEvent(QMouseEvent *event){
if(event->button() == Qt::LeftButton){
startPoint = event->QMouseEvent::pos();
}
/* //每次点击鼠标都会为之绘画一条新的线,并将该线的起点位置添加到_lines中
QVector<QPoint> line;
QVector<QPen> penAttribute;
_lines.append(line);
_pensAttribute.append(penAttribute);
//记录下该条线当前的位置
QVector<QPoint> &lastLine = _lines.last();
lastLine.append(event->pos());
QVector<QPen> &lastPenAttribute = _pensAttribute.last();
lastPenAttribute.append(pen);
*/
}
void PaintArea::mouseMoveEvent(QMouseEvent *event){
if(event->type() == QEvent::MouseMove){
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
endPoint = mouseEvent->pos();
}
update();
/*if(_lines.size() == 0)
{
QVector<QPoint> line;
QVector<QPen> penAttribute;
_lines.append(line);
_pensAttribute.append(penAttribute);
}
QVector<QPoint> &lastLine = _lines.last();
QVector<QPen> &lastPenAttribute=_pensAttribute.last();
//记录该条线当前的位置
lastLine.append(event->pos());
lastPenAttribute.append(pen);
//强制重绘
update();
*/
}
void PaintArea::mouseReleaseEvent(QMouseEvent *event){
if(event->button() == Qt::LeftButton){
paths.append(path);
pens.append(myPen);
}
/* QVector<QPoint> &lastLine = _lines.last();
QVector<QPen> &lastPenAttribute = _pensAttribute.last();
lastLine.append(event->pos());
lastPenAttribute.append(pen);
*/
}
| true |
8d5e34e6e9ebcaf4cf2d02bb5518b945f6d5272e | C++ | tvphu20th2/baitapOOP | /QL_Sach.cpp | UTF-8 | 2,324 | 2.53125 | 3 | [] | no_license | #include <conio.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include<stdlib.h>
#include <iomanip>
#include <iostream>
using namespace std;
#define MAX_NXB 50
//Class Nhanvien
class QLSach
{ protected:
char MaSach[12];
char NgayNhap[12];
float DonGia;
int SoLuong;
char NXB[50];
float ThanhTien;
public:
QLSach();
virtual void Nhap();
void Xuat();
virtual void TinhTien()=0; //Ham thuan ao
//...bo sung code
};
//Class Bien che
class SachGK: public QLSach
{
protected:
int TinhTrang; //1-Moi; 0-Cu
public:
SachGK();
void TinhTien();
void Nhap();
//...bo sung code
};
//Dinh nghia lop SachTK
class SachTK : public QLSach
{
protected:
float Thue;
public:
SachTK();
void Nhap();
void TinhTien();
//...bo sung code
};
//Dinh nghia ham thanh vien cho lop QLSach
QLSach::QLSach()
{
strcpy(MaSach,"");
strcpy(NgayNhap,"");
strcpy(NXB,"");
ThanhTien=DonGia=SoLuong=0;
}
void QLSach::Nhap()
{
//bo sung code
}
void QLSach::Xuat()
{
cout<<"MS: "<<MaSach<<",NG: "<<NgayNhap;
cout<<",DG: "<<DonGia<<",SL: "<<SoLuong;
cout<<",TT: "<<ThanhTien<<"NXB: "<<NXB<<endl;
}
//Dinh nghia ham thanh vien cho lop SachGK
SachGK::SachGK(): QLSach()
{
//QLSach::QLSach();
TinhTrang=1; //mac nhien la Sach moi
}
void SachGK::TinhTien()
{
if (TinhTrang==1)
ThanhTien=SoLuong*DonGia;
else
ThanhTien=SoLuong*DonGia*0.5;
}
void SachGK::Nhap()
{
//...bo sung code
}
//Cac ham thanh vien trong lop SachTK
SachTK::SachTK(): QLSach()
{
Thue=0;
}
void SachTK::Nhap()
{
//...bo sung code
}
void SachTK::TinhTien()
{
ThanhTien= SoLuong*DonGia + Thue;
}
int main()
{
QLSach *MSach[100];
int i=0,n=0;
char Chon,Loai, nxb_ct[50];
cout<<setiosflags(ios::fixed)<<setprecision(2);
cout<<"Nhap thong tin cho cac loai sach"<<endl;
do
{
cout<<"Sack Giao khoa hay Sach Tham khao (G/T)? ";
cin>>Loai;
Loai=toupper(Loai);
if (Loai=='G')
{
//...bo sung code
}
else
{
//...bo sung code
}
n++; //tang len so luong sach
cout<<"Tiep tuc (C/K)? ";
cin>>Chon;
Chon=toupper(Chon);
if ((n==100)||(Chon=='K'))
break;
}
while (1);
//...bo sung code
getch();
return 1;
}
| true |
f8e650ca87d01577e2e20dbd2118759c01c471a2 | C++ | zhrv/heat_2d | /src/methods/heat_bnd.cpp | WINDOWS-1251 | 2,269 | 2.796875 | 3 | [] | no_license | #include "heat_bnd.h"
const char* HeatBoundary::TYPE_CONST = "BOUND_CONST";
const char* HeatBoundary::TYPE_FLOW = "BOUND_FLOW";
const char* HeatBoundary::TYPE_NOFLOW = "BOUND_NOFLOW";
HeatBoundary* HeatBoundary::create(TiXmlNode* bNode)
{
HeatBoundary * b = 0;
TiXmlNode* node = 0;
TiXmlNode* node1 = 0;
const char * type = bNode->FirstChild("type")->ToElement()->GetText();
if (strcmp(type, HeatBoundary::TYPE_CONST) == 0) {
b = new HeatBndConst();
bNode->ToElement()->Attribute("edgeType", &b->edgeType);
b->parCount = 1;
b->par = new double[1];
node = bNode->FirstChild("parameters");
node1 = node->FirstChild("T");
if (!node1) throw Exception("Parameter 'T' isn't specified for BOUND_FLOW.", Exception::TYPE_BOUND_NOPAR);
node1->ToElement()->Attribute("value", &b->par[0]);
}
if (strcmp(type, HeatBoundary::TYPE_NOFLOW) == 0) {
b = new HeatBndNoFlow();
bNode->ToElement()->Attribute("edgeType", &b->edgeType);
b->parCount = 0;
b->par = NULL;
}
if (strcmp(type, HeatBoundary::TYPE_FLOW) == 0) {
b = new HeatBndFlow();
bNode->ToElement()->Attribute("edgeType", &b->edgeType);
b->parCount = 2;
b->par = new double[2];
node = bNode->FirstChild("parameters");
node1 = node->FirstChild("factor");
if (!node1) throw Exception("Parameter 'factor' isn't specified for BOUND_FLOW.", Exception::TYPE_BOUND_NOPAR);
node1->ToElement()->Attribute("value", &b->par[0]); // factor*(dT/dX)=flowValue
node1 = node->FirstChild("flowValue");
if (!node1) throw Exception("Parameter 'flowValue' isn't specified for BOUND_FLOW.", Exception::TYPE_BOUND_NOPAR);
node1->ToElement()->Attribute("value", &b->par[1]);
}
const char * name = bNode->FirstChild("name")->ToElement()->GetText();
strcpy(b->name, name);
if (!b) {
throw Exception("Unknown bountary type '%s' specified.", Exception::TYPE_BOUND_UNKNOWN);
}
return b;
}
void HeatBndConst::run(Param& pL, Param& pR)
{
pR.T = par[0];
pR.u = pL.u;
pR.v = pL.v;
}
void HeatBndFlow::run(Param& pL, Param& pR) // @todo -
{
pR.T = pL.T+par[1]/par[0];
pR.u = pL.u;
pR.v = pL.v;
}
void HeatBndNoFlow::run(Param& pL, Param& pR)
{
pR.T = pL.T;
pR.u = pL.u;
pR.v = pL.v;
}
| true |
ee565ea6ded26ca2b301cdeaa3984bf667b75d89 | C++ | deathcod/mycode | /My_Algorithmic_CODES/DP_0-1knapsack.cpp | UTF-8 | 718 | 2.640625 | 3 | [] | no_license | /*
0-1 knapscak
by chinmay rakshit
date:20/11/2015
*/
#include <bits/stdc++.h>
int max(int a,int b)
{
return(a>b)?a:b;
}
int main()
{
int dp[101][101]={0},w[101]={0},val[101]={0},n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
scanf("%d %d",&w[i],&val[i]);
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(w[i]<=j)
dp[i][j]=max(dp[i-1][j-w[i]]+val[i],dp[i-1][j]);
else
dp[i][j]=dp[i-1][j];
}
}
// row items and column is weight.....
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
printf("%d ",dp[i][j]);
printf("\n");
}
printf("%d\n",dp[m][n] );
return 0;
} | true |
ee74de25ca38acd421c554ad4fec30497333b8d5 | C++ | KaPrimov/cpp-courses | /Advance/d_classMembers/e_lectures/LecturesMain.cpp | UTF-8 | 843 | 2.9375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <set>
#include <map>
#include "ResourceType.h"
#include "Resource.h"
#include "Lecture.h"
int main() {
using SoftUni::Resource;
using SoftUni::Lecture;
using SoftUni::ResourceType;
Lecture lecture;
std::map<ResourceType, int> numberOfResourcesByType;
int numResources;
std::cin >> numResources;
for (int i = 0; i < numResources; i++) {
Resource r;
std::cin >> r;
lecture << r;
}
std::cout << "... by id:" << std::endl;
for (const Resource& r : lecture) {
std::cout << r << std::endl;
}
std::cout << "... by type:" << std::endl;
std::vector<ResourceType> resourceTypes;
resourceTypes << lecture;
for (ResourceType type : resourceTypes) {
std::cout << type << ": " << lecture[type] << std::endl;
}
return 0;
}
| true |
b3ecf3790f8d10a151f03a2eafb3b94925521861 | C++ | asnows/opencv_vs2013 | /opencv_algorithm/opencv_algorithm/fpga_imgsharp.cpp | UTF-8 | 971 | 2.640625 | 3 | [] | no_license | #include"include.h"
void laplacian_sharp(cv::Mat srcImg, cv::Mat dstImg)
{
int lalp_delt1;
int lalp_delt2;
int value;
cv::Mat tmpImg(srcImg.rows,srcImg.cols,CV_8U);
unsigned int rows = srcImg.rows;
unsigned int cols = srcImg.cols;
for (int y = 1; y < rows - 1; y++)
{
for (int x = 1; x < cols - 1; x++)
{
lalp_delt1 = srcImg.at<unsigned char>(y - 1, x - 1) + srcImg.at<unsigned char>(y - 1, x) + srcImg.at<unsigned char>(y - 1, x + 1)
+ srcImg.at<unsigned char>(y, x - 1) + srcImg.at<unsigned char>(y, x + 1)
+ srcImg.at<unsigned char>(y + 1, x - 1) + srcImg.at<unsigned char>(y + 1, x) + srcImg.at<unsigned char>(y + 1, x + 1);
lalp_delt2 = 8 * srcImg.at<unsigned char>(y, x) - lalp_delt1;
if (lalp_delt2 < 0)
{
lalp_delt2 = 0;
}
lalp_delt2 = srcImg.at<unsigned char>(y, x) + lalp_delt2;
if (lalp_delt2 > 255)
{
lalp_delt2 = 255;
}
dstImg.at<unsigned char>(y, x) = lalp_delt2;
}
}
} | true |
6fe9076099c478f3735fa0707889e27be022449b | C++ | TrueElement/CPlusPlus | /Simple Game/include/Creature.h | UTF-8 | 2,391 | 3.28125 | 3 | [] | no_license | #ifndef CREATURE_H
#define CREATURE_H
#include <iostream>
class Room;
/*
* Creature Superclass Declaration
*/
class Creature {
public:
Creature();
~Creature();
void print();
void performAction(bool type);
void speak(bool pos_neg);
bool move(int direction);
bool moveRoom(Room *toMove);
void look();
int getName();
void setName(int creature_name);
int getType();
void setType(int creature_type);
Room * getCurrentRoom();
void setCurrentRoom(Room *new_room);
void setCurrentRoomName(int room_name);
int getCurrentRoomName();
bool moveOnStateChange();
bool processStateChange();
void commandClean();
void commandDirty();
private:
int type;
int currentRoomName;
int name;
Room *current_room;
};
/*
* Animal Subclass Declaration
*/
class Animal : public Creature {
public:
Animal();
~Animal();
void speak(bool pos_neg);
void print();
bool move(int direction);
bool checkRoom();
void enteringRoom();
bool processStateChange();
bool processCommand(std::string *command);
bool moveOnStateChange();
bool moveRoom(Room *room);
void processInitialState();
void commandClean();
void commandDirty();
};
/*
* NPC Subclass Declaration
*/
class NPC: public Creature {
public:
NPC();
~NPC();
void speak(bool pos_neg);
void print();
bool move(int direction);
bool checkRoom();
bool processStateChange();
bool processCommand(std::string *command);
bool moveOnStateChange();
void processInitialState();
bool moveRoom(Room *room);
void commandClean();
void commandDirty();
void enteringRoom();
};
/*
* PC Subclass Declaration
*/
class PC : public Creature {
public:
PC();
~PC();
void decrementRespect();
int getRespect();
void setRespect(int new_respect);
void modRespect(int modify);
void print();
bool move(int direction);
void printMoveFail(std::string direction);
void printMoveSuccess(std::string direction);
void look();
void look(std::string *direction);
bool commandClean();
bool commandDirty();
private:
int respect;
bool moveNorth();
bool moveSouth();
bool moveEast();
bool moveWest();
};
#endif
| true |
272ef7ccac301f85596c51b4de9703eb60f87188 | C++ | JasbirCodeSpace/du-CS-4th-Sem-Algorithms | /Practicals CPP files/selection sort/SLSRT100.CPP | UTF-8 | 999 | 2.8125 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include<time.h>
#include<limits.h>
#include<stdlib.h>
#include<fstream.h>
double selsort(int [],int);
void main()
{
clrscr();
time_t t;
fstream f;
f.open("abc.txt",ios::out);
srand((unsigned) time(&t));
int Test;
int *A;
int n,size=20;
double counter;
cout<<"Number of test cases:";
scanf("%d",&Test);
while(Test--)
{
size=size+10;
n=size;
A=new int[n];
for(int i=0;i<n;++i)
A[i]=rand()%INT_MAX+INT_MIN ;
counter=selsort(A,n);
printf("\n%lf",counter);
f<<"\n";
f<<n;
f<<"\t";
f<<counter;
delete A;
}
getch();
}
double selsort(int A[],int n)
{
int pos,temp;
double counter=0;
//pos to store current pos of min element ,counter for no. of comparisons
for(int i=0;i<n-1;++i)
{
pos=i;
for(int j=i+1;j<n;j++)
{
if(A[j]<A[pos])
{
pos=j;
counter++;
}
else
counter++;
}
temp=A[i];
A[i]=A[pos];
A[pos]=temp;
}
return counter;
} | true |
6679b8ddef601edfe4d86fff13cee83b52ed47e0 | C++ | amanmaldar/LinuxPerf | /main.cpp | UTF-8 | 840 | 3.328125 | 3 | [] | no_license | //new
#include <iostream>
#include <cstdlib>
#include <vector>
#include <ctime>
using namespace std;
void bar();
void foo();
vector <int> data;
vector <int> ans;
int lenght = 20000;
int sum = 0;
void foo(void) {
for(int i = 0; i < lenght ; i++){
sum = 0;
for(int j = 0; j < lenght ; j++){
sum += data.at(j);
}
ans.push_back(sum); //this will be same all the time
}
}
void bar(void) {
for(int i = 0; i < lenght ; i++){
sum = 0;
for(int j = 0; j < lenght ; j++){
sum += data.at(j);
}
ans.push_back(sum); //this will be same all the time
}
foo(); //calls foo
}
int main()
{
for(int i = 0; i < lenght ; i++){
data.push_back((rand() % 5) + 1);
}
bar();
return 0;
}
/*
for(int i = 0; i < lenght ; i++){
sum += data.at(i);
}
cout << "sum = " << sum << endl;
*/ | true |
ea4ee1e4249332fcddab83aa39f65f0e2b5d5e6d | C++ | cedricxs/LeetCode | /56-merge-intervals.cpp | UTF-8 | 1,009 | 3.078125 | 3 | [] | no_license | /*author : cedricxs
*level : middle
*/
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
static const auto _____ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval>res;if(intervals.empty())return res;
sort(intervals.begin(),intervals.end(),[&](Interval a,Interval b)->bool{return a.start<b.start;});
bool alive[intervals.size()];
memset(alive,true,intervals.size()*sizeof(bool));
for(int i=0;i<intervals.size();)
{if(alive[i]){
Interval temp=intervals[i];
while(temp.end>=intervals[i].start&&i<intervals.size()){temp.end=max(temp.end,intervals[i].end);alive[i]=false;i++;}
res.push_back(temp);}
}
return res;
}
}; | true |
12fbdae650e49730457a6d0dece65e20262a34ae | C++ | eriqwalker/algo | /Assign_01/assign_01/rgi.cc | UTF-8 | 1,076 | 3.328125 | 3 | [] | no_license | /*
* Eriq Walker
* z1908120
* CSCI-340-2
*
* I certify that this is my own work and where appropriate an extension
* of the starter code provided for the addignment.
*
* */
#include "rgi.h"
// Add needed constants
const int VEC_SIZE = 200,
LOW = 1,
HIGH = 10000,
SEED = 1;
// Generates and adds the random numbers to our vector
void genRndNums(vector<int> &v) {
srand(SEED);
for(int i = 0; i < VEC_SIZE; i++) {
v[i] = rand()%((HIGH-LOW)+1)+LOW;
}
}
// Prints all the items in our vector with a set width and
// output design
void printVec(const vector<int> &v) {
const int NO_ITEMS = 12, ITEM_W = 5;
int count = 0;
for (int i = 0; i < VEC_SIZE; i++) {
if (count == NO_ITEMS) {
count = 0;
cout << endl;
}
cout << setw(ITEM_W) << v[i] << ' ';
count++;
}
cout << endl;
}
int main() {
vector<int> v(VEC_SIZE);
genRndNums(v);
// Sorts our vector using STL sort
sort(v.begin(), v.end());
printVec(v);
return 1;
}
| true |
b5642110b9f81af70c3ba04996d266d768f01106 | C++ | Martisum/Algorithm | /邻接表建图深搜(实例)/adjacency list.cpp | GB18030 | 773 | 2.671875 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
using namespace std;
const int maxm=1001;
int p,s,a,b;
struct edge{
int u,v,next;
}e[maxm];
int head[maxm],js;
int book[maxm];
void addedge(int u,int v){
e[++js].u=u;
e[js].v=v;
e[js].next=head[u];
head[u]=js;
return;
}
void dfs(int x){
book[x]=1;
for(int i=head[x];i;i=e[i].next){
if(book[e[i].v]!=1){
cout<<e[i].u<<"to"<<e[i].v<<endl;
dfs(e[i].v);
}
}
return;
}
int main(){
freopen("ain.txt","r",stdin);
cin>>p>>s;
for(int i=1;i<=s;i++){
cin>>a>>b;
addedge(a,b);
}
freopen("CON","r",stdin);
int start;
cin>>start;
dfs(start);
// for(int i=1;i<=p;i++){
// cout<<""<<i<<"ȥеΪ";
// for(int j=head[i];j;j=e[j].next) cout<<e[j].v<<" ";
// cout<<endl;
// }
return 0;
}
| true |
50cb1bb83c1e8bf0b197b0970db6e4434fd6b1d6 | C++ | wisdom-weaver/c_cpp_mini | /data-structures_using_cpp/q-queue/queue_using_stack/queue_using_stack_rec_pop.cpp | UTF-8 | 785 | 3.4375 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
class queue_s2{
stack<int> s1;
public:
void push(int x){
s1.push(x);
}
int pop(){
if(s1.empty()){ cout<<"Queue is empty"<<endl; return -1; }
// get the top element
int x = s1.top(); s1.pop();
// base case=> if stack is empty then return the elem x
if(s1.empty()) return x;
// recursive case => call pop to get the next elem and so on till base case is hit
int item = pop();
// finally push back all the elements into the stack
s1.push(x);
return item;
}
bool empty(){
return s1.empty();
}
};
int main(){
queue_s2 q;
int i=0, n=5; while(i<n) q.push(++i);
i=0;
do
cout<<q.pop()<<endl;
while(++i<n+1);
return 0;
} | true |
b5a1e0793d60527375fde7295cf88107a145a21f | C++ | uwuser/MCsim | /IntegrationWithMacSim/src/MCsim/system/PipeCAS/RequestScheduler_PipeCAS.h | UTF-8 | 2,370 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef REQUESTSCHEDULER_PIPECAS_H
#define REQUESTSCHEDULER_PIPECAS_H
#include "../../src/RequestScheduler.h"
namespace MCsim
{
class RequestScheduler_PipeCAS: public RequestScheduler
{
private:
bool newRound;
bool firstACT;
RequestType bundlingType;
vector<unsigned int> scheduledCmdQueue;
bool isSchedulable(Request* request, bool open)
{
if(requestorCriticalTable.at(scheduledRequest->requestorID)== true) {
for(unsigned int index=0; index<scheduledCmdQueue.size(); index++) {
if(commandQueue[scheduledCmdQueue[index]]->getSize(true) < 2)
return false;
}
}
return true;
}
public:
RequestScheduler_PipeCAS(std::vector<RequestQueue*>&requestQueues, std::vector<CommandQueue*>& commandQueues, const std::map<unsigned int, bool>& requestorTable):
RequestScheduler(requestQueues, commandQueues, requestorTable)
{
newRound = true;
bundlingType = RequestType::DATA_READ;
}
void requestSchedule()
{
newRound = true; // Check if all the commands for scheduled requests are executed
firstACT = false; // Check if the execution already starts?
if(scheduledCmdQueue.size() > 0) {
for(unsigned int index=0; index<scheduledCmdQueue.size(); index++) {
if(commandQueue[scheduledCmdQueue[index]]->getSize(true) > 0) {
newRound = false;
if(commandQueue[scheduledCmdQueue[index]]->getSize(true) < 2) {
firstACT = true;
}
}
}
if(newRound)
scheduledCmdQueue.clear();
}
if(newRound || !firstACT) {
for(int index=0; index < requestQueue.size(); index++)
{
if(requestQueue[index]->getSize(false, 0) > 0) {
scheduledRequest = scheduleFR(index);
if(scheduledRequest->requestType == bundlingType) {
if(isSchedulable(scheduledRequest, isRowHit(scheduledRequest))) {
if(requestorCriticalTable.at(scheduledRequest->requestorID) == true ){
scheduledCmdQueue.push_back(scheduledRequest->requestorID);
}
updateRowTable(scheduledRequest->rank, scheduledRequest->bank, scheduledRequest->row);
requestQueue[index]->removeRequest();
}
}
}
}
}
else {
if(bundlingType == RequestType::DATA_WRITE) {bundlingType = RequestType::DATA_WRITE; }
else {bundlingType = RequestType::DATA_WRITE; }
}
}
};
}
#endif /* REQUESTSCHEDULER_PIPECAS_H */ | true |
65bd36282801e530e83f4429be0612dd6ee6d8b1 | C++ | ziggyman/stella | /cpp/msetapstozero/src/MSetApsToZero.cpp | UTF-8 | 3,393 | 2.625 | 3 | [] | no_license | /*
author: Andreas Ritter
created: 03/20/2007
last edited: 03/20/2007
compiler: g++ 4.0
basis machine: Ubuntu Linux 6.06
*/
#include "MSetApsToZero.h"
int main(int argc, char *argv[])
{
cout << "MSetApsToZero::main: argc = " << argc << endl;
if (argc < 4)
{
cout << "MSetApsToZero::main: ERROR: Not enough parameters specified!" << endl;
cout << "USAGE: setapstozero <char[] FitsFileName_In> <char[] DatabaseFileName_In> <char[] FitsFileName_Out>" << endl;
exit(EXIT_FAILURE);
}
char *P_CharArr_In = (char*)argv[1];
char *P_CharArr_DB = (char*)argv[2];
char *P_CharArr_Out = (char*)argv[3];
CString CS_FitsFileName_In;
CS_FitsFileName_In.Set(P_CharArr_In);
CString CS_FitsFileName_Out;
CS_FitsFileName_Out.Set(P_CharArr_Out);
CString CS_DatabaseFileName_In;
CS_DatabaseFileName_In.Set(P_CharArr_DB);
CFits F_Image;
if (!F_Image.SetFileName(CS_FitsFileName_In))
{
cout << "MSetApsToZero::main: ERROR: F_Image.SetFileName(" << CS_FitsFileName_In.Get() << ") returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: FileName <" << CS_FitsFileName_In.Get() << "> set" << endl;
/// Read FitsFile
if (!F_Image.ReadArray())
{
cout << "MSetApsToZero::main: ERROR: F_Image.ReadArray() returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: Array read" << endl;
/// Set DatabaseFileName_In
if (!F_Image.SetDatabaseFileName(CS_DatabaseFileName_In))
{
cout << "MSetApsToZero::main: ERROR: F_Image.SetDatabaseFileName(" << CS_DatabaseFileName_In << ") returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: DatabaseFileName <" << CS_DatabaseFileName_In << "> set" << endl;
// CString CS_Path(" ");
// F_Image.Get_Path(CS_Path);
// cout << "MSetApsToZero: CS_Path = <" << CS_Path << ">" << endl;
// exit(EXIT_FAILURE);
/// Read DatabaseFileName_In
if (!F_Image.ReadDatabaseEntry())
{
cout << "MSetApsToZero::main: ERROR: F_Image.ReadDatabaseEntry() returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: DatabaseEntry read" << endl;
/// Calculate Trace Functions
if (!F_Image.CalcTraceFunctions())
{
cout << "MSetApsToZero::main: ERROR: F_Image.CalcTraceFunctions() returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: TraceFunctions calculated" << endl;
/// Array<double, 1> D_A1_YLow(1);
/// D_A1_YLow(0) = 1;
/// F_Image.Set_YLow(D_A1_YLow);
/// Mark Centers
if (!F_Image.Set_ApertureDataToZero(0,0))
{
cout << "MSetApsToZero::main: ERROR: F_Image.Set_ApertureDataToZero() returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: Apertures set to zero" << endl;
/// Set CS_FitsFileName_Out
if (!F_Image.SetFileName(CS_FitsFileName_Out))
{
cout << "MSetApsToZero::main: ERROR: F_Image.SetFileName(" << CS_FitsFileName_Out << ") returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: FileName <" << CS_FitsFileName_Out << "> set" << endl;
/// Write Center Image
if (!F_Image.WriteArray())
{
cout << "MSetApsToZero::main: ERROR: F_Image.WriteArray() returned FALSE!" << endl;
exit(EXIT_FAILURE);
}
cout << "MSetApsToZero::main: F_Image: Array written" << endl;
return EXIT_SUCCESS;
}
| true |
99961e0c99e7478805865bba763c21477ad4eef9 | C++ | winshining/common_algorithms | /findmaxin/findmaxin.cpp | UTF-8 | 1,682 | 3.296875 | 3 | [] | no_license | #include "findmaxin.h"
/*
* More details refer to: http://blog.csdn.net/winshining/article/details/50389596
*/
static bool gt(const int a, const int b)
{
return a > b;
}
static void swap(int* buff, const int i, const int j)
{
assert(buff);
int temp = buff[i];
buff[i] = buff[j];
buff[j] = temp;
}
void findmaxin(int* buff, const int k, const int size, const int delta)
{
if (!buff || delta <= 0 || delta > k || k <= 0 || size <= 0 || k > size - k) {
cout << "bad parameters." << endl;
return;
}
int minElemIdx, zoneBeginIdx;
sort(buff, buff + k, gt); // 首先对前k个数进行排序
minElemIdx = k - 1; // 最小的数是第k - 1个数,数组下标从0开始计算
zoneBeginIdx = minElemIdx; // 将标记范围的变量也指向第k - 1个数,主要用于后续的排序
for (int i = k; i < size; i++) // 从第k个数开始循环
{
if (buff[i] > buff[minElemIdx]) // 从后size - k个数中找到比前k个数中最小的数大的数
{
swap(buff, i, minElemIdx); // 交换
if (minElemIdx == zoneBeginIdx)
{
zoneBeginIdx--; // 标记范围的变量往前移动
if (zoneBeginIdx < k - delta) // 无序的范围已经超过阈值了
{
sort(buff, buff + k, gt); // 再次排序
zoneBeginIdx = minElemIdx = k - 1; // 复位
continue;
}
}
int idx = zoneBeginIdx;
int j = idx + 1;
// 在标记范围内查找最小的数
for (; j < k; j++)
{
if(buff[idx] > buff[j])
idx = j;
}
minElemIdx = idx; // 将指向最小数的标志置成找到的最小数的索引
}
}
}
| true |
63c267484078678d88ab1cd4426f969ce1a34f87 | C++ | yeonie/Algorithm | /bokli_Calculate/bokli_Calculate/main.cpp | UTF-8 | 595 | 3.171875 | 3 | [] | no_license | //
// main.cpp
// bokli_Calculate
//
// Created by 이동연 on 2021/01/23.
//
#include <iostream>
#include <cmath>
using namespace std;
int bokli(long long money, int n, float interest){
for(int i = 0 ; i < n ; i++){
money = money*interest;
}
cout<<n<<"일 후 "<<"잔액 :"<< money<< endl;
return 0;
}
int main(){
long long capitalStock = 0;
int date=0;
float interest = 0;
cout<<"입금액 : ";
cin>> capitalStock;
cout<<"날짜 : ";
cin>> date;
cout<<"이율 : ";
cin>> interest;
bokli(capitalStock, date, interest);
}
| true |
ca5874a2668dcbd1815593276f2957316e68dc59 | C++ | chronos-cosine/Chronos | /src/Collections/Concurrent/Queue.h | UTF-8 | 2,286 | 3.15625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Collections/ConcurrentQueue.h
* Author: Chronos Cosine <chronos.cosine@gmail.com>
*
* Created on 12 October 2018, 10:52 PM
*/
#ifndef COLLECTIONS_CONCURRENT_QUEUE_H
#define COLLECTIONS_CONCURRENT_QUEUE_H
#include "Collections/ICollection.h"
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
namespace Collections {
namespace Concurrent {
template <typename T>
class Queue : public ICollection<T> {
Queue(const Queue&) = delete;
Queue& operator=(const Queue&) = delete;
Queue(const Queue&&) = delete;
Queue& operator=(const Queue&&) = delete;
private:
std::queue<T> queue;
std::mutex mutex;
std::condition_variable condition_variable;
public:
virtual ~Queue() = default;
Queue() = default;
virtual void push(T item) noexcept;
virtual T pop() noexcept;
virtual bool empty() const noexcept;
typename std::queue<T>::size_type size() const noexcept;
}; /* class Queue */
template <typename T>
void
Queue<T>::push(T item) noexcept {
std::lock_guard<std::mutex> lock(mutex);
queue.push(std::move(item));
condition_variable.notify_one();
}
template <typename T>
T
Queue<T>::pop() noexcept {
std::unique_lock<std::mutex> lock(mutex);
condition_variable.wait(lock, [this] {
return !queue.empty();
});
T item = std::move(queue.front());
queue.pop();
return item;
}
template <typename T>
bool
Queue<T>::empty() const noexcept {
return queue.empty();
}
template <typename T>
typename std::queue<T>::size_type
Queue<T>::size() const noexcept {
return queue.size();
}
} /* namespace Concurrent */
} /* namespace Collections */
#endif /* COLLECTIONS_CONCURRENT_QUEUE_H */
| true |
ff1413a53ad715ade4b4e8d9694f5accff58543d | C++ | iChenLei/c-_primer_plus | /day25.cpp | UTF-8 | 159 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
typedef string str;
int main(){
str s = "string";
cout<<"typedef------->"<<s<<endl;
}
| true |
de5f8762ab5dcab149ce7f12d70a4cf7073e4af6 | C++ | haz/fd-multisearch | /downward/search/operator_registry.h | UTF-8 | 1,042 | 2.640625 | 3 | [] | no_license | #ifndef OPERATOR_REGISTRY_H
#define OPERATOR_REGISTRY_H
#include "globals.h"
#include <vector>
class Operator;
class OperatorRegistry {
std::vector<const Operator *> canonical_operators;
inline int get_op_index(const Operator *op) const;
int num_vars;
int num_operators;
int num_canonical_operators;
public:
OperatorRegistry(
const std::vector<const Operator *> &relevant_operators,
const std::vector<int> &pruned_vars);
~OperatorRegistry();
inline const Operator *get_canonical_operator(
const Operator *) const;
void statistics() const;
};
inline int OperatorRegistry::get_op_index(const Operator *op) const {
int op_index = op - &*g_operators.begin();
assert(op_index >= 0 && op_index < g_operators.size());
return op_index;
}
inline const Operator *OperatorRegistry::get_canonical_operator(
const Operator *op) const {
const Operator *canonical_op = canonical_operators[get_op_index(op)];
assert(canonical_op);
return canonical_op;
}
#endif
| true |
3438f2b12a17691b71274f25cc0f803542bcc73d | C++ | mwiegant/CS480_wiegant | /PA7/include/object.h | UTF-8 | 1,834 | 2.703125 | 3 | [] | no_license | /**
* @file object.h
*
* @brief Definition file for object class
*
* @author Cactus Coolers
*
* @details Specifies all methods and variables for object class
*
* @version 1.00
*
* @Note None
*/
#ifndef OBJECT_H
#define OBJECT_H
#include <vector>
#include <string>
#include <cstdio>
#include <fstream>
#include <iostream>
#include "graphics_headers.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/color4.h>
#include <Magick++.h>
class Object
{
public:
Object();
~Object();
bool Initialize();
void Update(unsigned int dt, float speedModifier, glm::mat4 systemModel);
void Render();
glm::mat4 GetModel();
void AddSatellite(Object* satellite);
void ToggleChairMode();
//function to read in the required parts from the config file
bool ReadConfig(std::ifstream& fileIn);
private:
bool InitializeTexture();
bool InitializeModel(bool chairMode);
// Update functions
void updateAngles(float dt);
void drawObject(glm::mat4 matrix);
glm::mat4 model;
std::vector<Vertex> Vertices;
std::vector<unsigned int> Indices;
GLuint VB;
GLuint IB;
//Texture
GLuint aTexture;
// Unique Identifier
char* name;
// Path names
char* modelFilePath;
char* textureFilePath;
char* chairFilePath;
bool chairMode;
// Spin variables
float spinAngle;
float spinSpeed;
int spinAngleDivisor;
bool spinEnabled;
int spinDirection;
glm::vec3 spinAxisVector;
// Orbit variables
float orbitAngle;
float orbitSpeed;
int orbitAngleDivisor;
bool orbitEnabled;
int orbitDirection;
glm::vec3 orbitVector;
// For objects that orbit around this object
std::vector<Object *> satellites;
};
#endif /* OBJECT_H */
| true |
ce378156419bd845830b3c9be9005b9faddad1a4 | C++ | DriftingLQK/TrainCamp | /TrainTask/Solve_Question_Code/NimGame.cpp | GB18030 | 754 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
/*****************************************ʮһ*************************************
[Ҫ]
ѣһ Nim Ϸһʯͷÿõ1-3ʯͷ õһʯͷ˾ǻʤߡ
Ϊ֣
ǴˣÿһŽ⡣ дһжǷڸʯͷӮϷ
*****************************************************************************************/
bool NimGame(int n)
{
if (n <= 0 )
{
return false;
}
else if (n<4)
{
return true;
}
else
{
if (n % 4 == 0) return false;
else return true;
}
} | true |
4b80dd932ea96030254714a68ab602bb40bbcd13 | C++ | ang421/Pacman2 | /src/pacman.cpp | UTF-8 | 9,256 | 3.25 | 3 | [] | no_license | #include "pacman.h"
#include "pacmangame.h"
#include "ghost.h"
#include "wall.h"
#include "ghostwall.h"
Pacman::Pacman(PacmanGame* pacmangame, int row, int col, Character* (*board)[31][28], Mode mode) :
Character(row, col, board),
pacmangame(pacmangame),
direction(Dir::NONE),
mode(mode),
has_eaten_piece(false),
has_eaten_ghost(false),
has_encountered_ghost(false),
gain(false),
lose(false),
addpoints(-1)
{
//if classic, then start normally and with 5 lives
if(mode == Mode::CLASSIC) {
superpower = -1;
lives = 3;
}
//if reverse, superpower is our timer and no lives
else if (mode == Mode::REVERSE) {
superpower = 200;
lives = 0;
}
}
char Pacman::getImage() const
{
return IMAGE_PACMAN;
}
bool Pacman::just_eaten_superpower() const
{
return gain;
}
bool Pacman::just_lost_superpower() const
{
return lose;
}
void Pacman::set_gain()
{
gain = false;
}
void Pacman::set_lose()
{
lose = false;
}
Dir Pacman::get_direction() const
{
return direction;
}
int Pacman::get_superpower() const
{
return superpower;
}
void Pacman::set_superpower(int num)
{
superpower = num;
}
void Pacman::update_superpower()
{
//if newly gained superpower, extend time
if (gain) superpower = 100;
//otherwise, decrement superpower until zero and reset to -1
else if (superpower > 0) --superpower;
else if (superpower == 0) {
lose = true;
superpower = -1;
}
//safeguar to reset superpower
else superpower = -1;
}
void Pacman::update_direction(Dir dir)
{
//make sure that pacman stays in the map and does not hit a wall or ghost wall
if (dir == Dir::UP){
if (row==30) return;
if ((*board)[row+1][col]!=nullptr){
if ((*board)[row+1][col]->getImage()== Wall::IMAGE_WALL || (*board)[row+1][col]->getImage()== Ghostwall::IMAGE_GHOSTWALL){
return;
}
}
}
else if (dir == Dir::DOWN){
if (row==0) return;
if ((*board)[row-1][col]!=nullptr){
if ((*board)[row-1][col]->getImage()== Wall::IMAGE_WALL || (*board)[row-1][col]->getImage()== Ghostwall::IMAGE_GHOSTWALL){
return;
}
}
}
else if (dir == Dir::LEFT){
if (col==0) return;
if ((*board)[row][col-1]!=nullptr){
if ((*board)[row][col-1]->getImage()== Wall::IMAGE_WALL || (*board)[row][col-1]->getImage()== Ghostwall::IMAGE_GHOSTWALL){
return;
}
}
}
else if (dir == Dir::RIGHT){
if (col==27) return;
if ((*board)[row][col+1]!=nullptr){
if ((*board)[row][col+1]->getImage()== Wall::IMAGE_WALL || (*board)[row][col+1]->getImage()== Ghostwall::IMAGE_GHOSTWALL){
return;
}
}
}
direction = dir;
}
void Pacman::eats_piece(Food* f)
{
//set status variable and increment points
has_eaten_piece = true;
addpoints = f->get_points();
}
void Pacman::not_eat_piece()
{
//reset status variables
has_eaten_piece = false;
addpoints = -1;
}
void Pacman::encounter_ghost()
{
//if pacman encounters ghost in classic mode
has_encountered_ghost = true;
--lives;
direction = Dir::NONE;
//reset pacman back to start, but has multiple cases, in case map is filled with ghosts
((*board)[this->row][this->col]) = nullptr;
if ((*board)[7][13] == nullptr) {
((*board)[7][13]) = this;
this->row = 7; this->col = 13;
}
else if ((*board)[7][12] == nullptr) {
((*board)[7][12]) = this;
this->row = 7; this->col = 12;
}
else if ((*board)[7][11] == nullptr) {
((*board)[7][11]) = this;
this->row = 7; this->col = 11;
}
else {
((*board)[7][10]) = this;
this->row = 7; this->col = 10;
}
}
void Pacman::eats_ghost(Ghost* g, int row, int col)
{
//set status variables and points when pacman eats ghosts in superpower mode
has_eaten_piece = true;
has_eaten_ghost = true;
addpoints = g->get_points();
if(mode == Mode::CLASSIC) {
//reset ghost status variables and move the ghost back to the box
g -> set_eatmode(false);
if ((*board)[15][12] == nullptr) g -> move(15, 12);
else if ((*board)[16][12] == nullptr) g -> move(16, 12);
else if ((*board)[15][15] == nullptr) g -> move(15, 15);
else if ((*board)[16][15] == nullptr) g -> move(16, 15);
else if ((*board)[15][14] == nullptr) g -> move(15, 14);
else if ((*board)[16][14] == nullptr) g -> move(16, 14);
else if ((*board)[15][13] == nullptr) g -> move(15, 13);
else if ((*board)[16][13] == nullptr) g -> move(16, 13);
g -> set_time_in_box(20);
}
else if(mode == Mode::REVERSE) {
//in reverse, remove the ghost from the game and add points depending on time remaining
(*board)[g->getRow()][g->getCol()] = nullptr;
pacmangame->remove_ghost(g->get_number());
g = nullptr;
addpoints += (superpower * 5);
}
//move pacman to new pixel
((*board)[this->row][this->col]) = nullptr;
((*board)[row][col]) = this;
this->row = row; this->col = col;
}
void Pacman::not_eat_ghost()
{
has_eaten_ghost = false;
}
bool Pacman::get_has_encountered_ghost()
{
if (has_encountered_ghost == true) {
has_encountered_ghost = false;
return true;
}
return false;
}
bool Pacman::get_has_eaten_ghost() const
{
return has_eaten_ghost;
}
int Pacman::get_points_to_add() const
{
return addpoints;
}
int Pacman::get_lives() const
{
return lives;
}
void Pacman::move(int row, int col)
{
//warping for pacman for edge case
if (col == -1 && row == 16) {
((*board)[this->row][this->col]) = nullptr;
((*board)[16][27]) = this;
this->row = 16; this->col = 27;
return;
}
if (col == 28 && row == 16) {
((*board)[this->row][this->col]) = nullptr;
((*board)[16][0]) = this;
this->row = 16; this->col = 0;
return;
}
//in case coordinates exceeds map size
if (row < 0 || col < 0 || row >= 31 || col >= 28) return;
//if ghost is directly beside pacman in non-superpower mode, then gets eaten
if ((*board)[this->row][this->col-1] != nullptr) {
if ((*board)[this->row][this->col-1]->getImage() == 'C' || (*board)[this->row][this->col-1]->getImage() == 'A' || (*board)[this->row][this->col-1]->getImage() == 'R')
{
encounter_ghost();
return;
}
}
if ((*board)[this->row][this->col+1] != nullptr) {
if ((*board)[this->row][this->col+1]->getImage() == 'C' || (*board)[this->row][this->col+1]->getImage() == 'A' || (*board)[this->row][this->col+1]->getImage() == 'R')
{
encounter_ghost();
return;
}
}
if ((*board)[this->row-1][this->col] != nullptr) {
if ((*board)[this->row-1][this->col]->getImage() == 'C' || (*board)[this->row-1][this->col]->getImage() == 'A' || (*board)[this->row-1][this->col]->getImage() == 'R')
{
encounter_ghost();
return;
}
}
if ((*board)[this->row+1][this->col] != nullptr) {
if ((*board)[this->row+1][this->col]->getImage() == 'C' || (*board)[this->row+1][this->col]->getImage() == 'A' || (*board)[this->row+1][this->col]->getImage() == 'R')
{
encounter_ghost();
return;
}
}
//move pacman to empty space
if ((*board)[row][col] == nullptr) {
((*board)[this->row][this->col]) = nullptr;
((*board)[row][col]) = this;
this->row = row; this->col = col;
return;
}
//pacman hits a wall
else if ((*board)[row][col] -> getImage() == 'W' || (*board)[row][col] -> getImage() == 'V') return;
//pacman eats some food
else if ((*board)[row][col] -> getImage() == 'F') {
eats_piece(dynamic_cast<Food*>((*board)[row][col]));
((*board)[this->row][this->col]) = nullptr;
((*board)[row][col]) = this;
this->row = row; this->col = col;
}
//pacman eats a supwerpower
else if ((*board)[row][col] -> getImage() == 'U') {
eats_piece(dynamic_cast<Food*>((*board)[row][col]));
gain = true;
((*board)[this->row][this->col]) = nullptr;
((*board)[row][col]) = this;
this->row = row; this->col = col;
}
//in case pacman and ghost collide on the same square
else if ((*board)[row][col] -> getImage() == 'C' || (*board)[row][col] -> getImage() == 'A' || (*board)[row][col] -> getImage() == 'R') {
encounter_ghost();
}
//pacman collides with a ghost in superpower mode
else if ((*board)[row][col] -> getImage() == 'E') {
eats_ghost(dynamic_cast<Ghost*>((*board)[row][col]), row, col);
}
}
| true |
a4da165598587b565f5984c72bac05b50397e415 | C++ | chanmufeng/data_structure | /heap/SortTestHelper.h | GB18030 | 1,502 | 3.78125 | 4 | [] | no_license | #ifndef BASIC_SORT_GENERATION_H
#define BASIC_SORT_GENERATION_H
#include <iostream>
#include <ctime>
#include <cassert>
namespace SortTestHelper {
//nԪص飬ÿԪصΧΪ[rangeL,rangeR]
int* generateRandomArray(int n,int rangeL,int rangeR) {
assert(rangeL <= rangeR);
int* arr=new int[n];
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i]=rand() % (rangeR - rangeL + 1) + rangeL;
}
return arr;
}
//ɽ
int* generateNearlyOrderedArray(int n,int swapTimes) {
int* arr=new int[n];
srand(time(NULL));
int posX,posY;
for (int i = 0;i < n;i ++){
arr[i] = i;
}
for (int i = 0; i < swapTimes; i ++) {
posX = rand()%n;
posY = rand()%n;
std::swap(arr[posX],arr[posY]);
}
return arr;
}
//鿽
int* copyArray(int arr[],int n){
int* dest =new int[n];
std::copy(arr,arr+n,dest);
return dest;
}
//õ
template<typename T>
void printArray(T arr[], int n) {
for (int i = 0; i < n; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
return;
}
template <typename T>
void testSort(std::string sortMethod,void (*sort)(T[],int ),T arr[],int n) {
clock_t startTime=clock();
sort(arr,n);
clock_t endTime=clock();
std::cout<< sortMethod << "" << n <<"Ԫع" <<double(endTime - startTime)/CLOCKS_PER_SEC <<"";
}
};
#endif
| true |
2c7d96827f6632bb21c110679d09b739d9525412 | C++ | Floopion/Home-Projects | /C++ Rouglike/Checkpoint/TileList.h | UTF-8 | 1,013 | 2.640625 | 3 | [] | no_license | /*
Program name: Rougelike
Project file name: TileList.h
Date: 15/05/2020
Language: C++
Platform: Microsoft Visual Studio 2017 - 2019
Purpose: To specify the methods and variables needed, whether they are public or private.
Description: Header file for the TileList, contains the variables and methods needed that will be implemented within the .cpp file.
Known Bugs: Nothing currently
*/
#pragma once
#include "Tile.h"
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
ref class TileList
{
private:
// variables
array<Tile^>^ tileArray;
int nTiles;
public:
// constructor
TileList(int startNTiles);
// methods
void SetTileArrayEntry(int tileIndex, Tile^ tileToEnter);
Bitmap^ GetTileBitmap(int tileIndex);
bool isTileWalkable(int tileIndex);
bool isEndTile(int tileIndex);
};
| true |
920ed967f040e545f917e84948748274557ecb9a | C++ | yuxz09/algsLearning | /程序员代码面试指南/KsortedlistToOne/KsortedlistToOne.cpp | UTF-8 | 2,004 | 3.8125 | 4 | [] | no_license | /*
给定k个有序链表的头节点,怎么把他们merge成一个有序的链表。
*/
#include <iostream>
#include <queue>//using std::priority_queue
using namespace std;
struct Node
{
int val;
Node* next;
Node(int value)
{
val = value;
}
};
struct cmp
{
bool operator()(Node* node1, Node* node2)
{
return node1->val > node2->val;
}
};
Node* KsortedlistToOne(vector<Node*> vect)
{
priority_queue<Node*, vector<Node*>, cmp> minheap;
for(int i = 0; i < vect.size(); i++)
{
if(vect[i] != NULL)
{
minheap.push(vect[i]);
}
}
struct Node* head = NULL;
struct Node* pre = NULL;
while(!minheap.empty())
{
struct Node* cur = minheap.top();
cout << cur -> val << endl;
minheap.pop();
if(head == NULL)
{
head = cur;
}
if(pre != NULL)
{
pre -> next = cur;
}
pre = cur;
if(cur -> next != NULL)
{
minheap.push(cur->next);
}
}
return head;
}
int main()
{
struct Node* node1 = new Node(1);
node1 -> next = NULL;
struct Node* node2 = new Node(14);
node1 -> next = NULL;
struct Node* node3 = new Node(3);
struct Node* node4 = new Node(8);
node3 -> next = node4;
node4 -> next = NULL;
struct Node* node5 = new Node(2);
struct Node* node6 = new Node(26);
node5 -> next = node6;
node6 -> next = NULL;
struct Node* node7 = new Node(5);
node7 -> next = NULL;
struct Node* node8 = new Node(4);
node8 -> next = NULL;
vector<Node*> v;
v.push_back(node1);
v.push_back(node2);
v.push_back(node3);
// v.push_back(node4);
v.push_back(node5);
// v.push_back(node6);
v.push_back(node7);
v.push_back(node8);
struct Node* res = KsortedlistToOne(v);
while(res != NULL)
{
cout << res -> val << endl;
res = res -> next;
}
}
| true |
66a58180dde0aabb1b694d9b2e1279e030414bbb | C++ | Noele/Cherri | /Response.h | UTF-8 | 418 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "sleepy_discord/sleepy_discord.h"
class Response {
public:
enum type {embed, message, action};
std::string rmessage;
SleepyDiscord::Embed rembed;
Response::type rtype;
Response (std::string rmessage, SleepyDiscord::Embed rembed, Response::type responseType) {
this->rmessage = rmessage;
this->rembed = rembed;
this->rtype = responseType;
}
Response() {}
};
| true |
8fc7138eacd4b06d7898bb0b0fb72839cc5f976b | C++ | jkrecek/ShutdownApp | /NOSA-Server/src/mainsocket.cpp | UTF-8 | 1,542 | 2.765625 | 3 | [] | no_license | #include "mainsocket.h"
#include <iostream>
#include <ctime>
#include "defines.h"
#ifndef _WIN32
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#endif
MainSocket::MainSocket(TCPSocket socket, sockaddr_in info)
: NetworkSocket(socket, info)
{
}
MainSocket* MainSocket::createSocket(Configuration* configuration)
{
hostent *host;
sockaddr_in sockInfo;
TCPSocket baseSocket;
const char* hostname = configuration->getString("REMOTE_ADDRESS").c_str();
if ((host = gethostbyname(hostname)) == NULL)
{
std::cout << "Wrong address" << std::endl;
return NULL;
}
if ((baseSocket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR)
{
std::cout << "Could not create socket" << std::endl;
return NULL;
}
sockInfo.sin_family = AF_INET;
sockInfo.sin_port = htons(SOCKET_PORT);
memcpy(&(sockInfo.sin_addr), host->h_addr, host->h_length);
if (connect(baseSocket, (sockaddr *)&sockInfo, sizeof(sockInfo)) == SOCKET_ERROR)
{
std::cout << "Could not link connection" << std::endl;
return NULL;
}
MainSocket* sock = new MainSocket(baseSocket, sockInfo);
sock->sendMsg(generateAuthMessage(configuration));
return sock;
}
const char* MainSocket::generateAuthMessage(Configuration *configuration)
{
char buffer[1024];
snprintf(buffer, 1024, "type=PC user=%s pass=%s", configuration->getString("USER").c_str(), configuration->getString("PASS").c_str());
return strdup(buffer);
}
| true |
b65ceeee4017bdd57e8950629a4071bc1ece6047 | C++ | Ioann87/houses | /main.cpp | UTF-8 | 2,801 | 3.421875 | 3 | [] | no_license | #include <cstring>
#include <ctime>
#include <iostream>
#include <vector>
using namespace std;
vector<char*> names = {
"Ivan",
"Petr",
"Viktor",
"Stepan",
"Josiph",
"Vladimir",
"Kiryll",
"Anton",
"Jury",
"Boris"
};
vector<char*> surnames = {
"Ivanov",
"Petrov",
"Viktorov",
"Stepanov",
"Josiphov",
"Vladimirov",
"Kiryllov",
"Antonov",
"Juryov",
"Borisov"
};
class Person {
private:
char* name;
char* surname;
int age;
public:
Person();
Person(char name);
~Person();
void init_person(char* name, char* surname, int age);
void show_info();
};
class Flat {
private:
Person* flats;
int size;
public:
Flat();
~Flat();
void init_flat();
void show_flat();
};
class House {
private:
Flat* flats_count;
int size;
public:
House();
~House();
void show_house();
void init_house();
};
int main()
{
srand(time(NULL));
House* houses = new House[5];
for (int i = 0; i < 3; i++) {
houses[i].init_house();
}
for (int i = 0; i < 3; i++) {
houses[i].show_house();
}
delete[] houses;
return 0;
}
Person::Person()
{
this->name = nullptr;
this->surname = nullptr;
this->age = 0;
}
Person::~Person()
{
delete name;
delete surname;
}
void Person::init_person(char* name, char* surname, int age)
{
this->name = new char[15];
strcpy(this->name, name);
this->surname = new char[15];
strcpy(this->surname, surname);
this->age = age;
return;
}
void Person::show_info()
{
cout << "Name: " << this->name << endl;
cout << "Surname: " << this->surname << endl;
cout << "Age: " << this->age << endl;
cout << endl;
}
Flat::Flat()
{
this->flats = nullptr;
this->size = 0;
}
Flat::~Flat()
{
delete[] flats;
}
void Flat::init_flat()
{
this->size = rand() % 3 + 1;
this->flats = new Person[this->size];
for (int i = 0; i < size; i++) {
flats[i].init_person(
names[rand() % 10],
surnames[rand() % 10],
rand() % 50 + 20);
}
return;
}
void Flat::show_flat()
{
for (int i = 0; i < this->size; i++) {
cout << "Flat #" << i + 1 << endl;
flats[i].show_info();
}
return;
}
House::House()
{
this->flats_count = nullptr;
this->size = 0;
}
House::~House()
{
delete[] flats_count;
}
void House::init_house()
{
this->size = rand() % 5 + 1;
this->flats_count = new Flat[size];
for (int i = 0; i < this->size; i++) {
flats_count[i].init_flat();
}
return;
}
void House::show_house()
{
for (int i = 0; i < this->size; i++) {
cout << "House #" << i + 1 << endl;
flats_count[i].show_flat();
}
}
| true |
4eb2776dd60cb3d61c93b913d4e3ffeaf94a437e | C++ | kentatakiguchi/GameCompetition2016_2 | /DXBase/DXBase/sources/Actor/Person/Enemy/FloorSearchPoint.cpp | SHIFT_JIS | 3,082 | 2.515625 | 3 | [] | no_license | #include "FloorSearchPoint.h"
#include "../../../ResourceLoader/ResourceLoader.h"
#include "../../Base/ActorGroup.h"
#include"../../Body/CollisionBase.h"
#include "../../../World/IWorld.h"
#include "../../../Math/Math.h"
#include "../../../Define.h"
FloorSearchPoint::FloorSearchPoint(
IWorld * world,
const Vector2& enemyPosition,
const Vector2& addPosition,
const Vector2& bodyScale
) :
Actor(world, "FSP", enemyPosition + addPosition,
CollisionBase(
Vector2((enemyPosition.x + addPosition.x) + bodyScale.x / 2.0f, (enemyPosition.y + addPosition.y) + bodyScale.y / 2.0f),
Vector2((enemyPosition.x + addPosition.x) - bodyScale.x / 2.0f, (enemyPosition.y + addPosition.y) + bodyScale.y / 2.0f),
Vector2((enemyPosition.x + addPosition.x) + bodyScale.x / 2.0f, (enemyPosition.y + addPosition.y) - bodyScale.y / 2.0f),
Vector2((enemyPosition.x + addPosition.x) - bodyScale.x / 2.0f, (enemyPosition.y + addPosition.y) - bodyScale.y / 2.0f)
)
),
turnCount_(0),
isFloor_(false),
isGround_(false),
isGroundBegin_(false),
direction_(1.0f, 1.0f),
enemyPosition_(enemyPosition),
addPosition_(addPosition),
floorPosition_(Vector2::Zero)
{
}
FloorSearchPoint::FloorSearchPoint(
IWorld * world,
const Vector2 & enemyPosition,
const Vector2 & addPosition,
const float radius) :
Actor(world, "FSP", enemyPosition + addPosition,
CollisionBase(position_, radius)),
turnCount_(0),
isFloor_(false),
isGround_(false),
isGroundBegin_(false),
direction_(1.0f, 1.0f),
enemyPosition_(enemyPosition),
addPosition_(addPosition),
floorPosition_(Vector2::Zero)
{
}
void FloorSearchPoint::onUpdate(float deltaTime)
{
auto addPos = Vector2(
addPosition_.x * direction_.x,
addPosition_.y * direction_.y);
position_ = enemyPosition_ + addPos;
isFloor_ = false;
isGround_ = false;
isGroundBegin_ = false;
}
void FloorSearchPoint::onDraw() const{
//auto vec3Pos = Vector3(position_.x, position_.y, 0.0f);
//vec3Pos = vec3Pos * inv_;
////// 摜̕\
//DrawGraph(
// vec3Pos.x, vec3Pos.y,
// ResourceLoader::GetInstance().getTextureID(TextureID::ENEMY_NEEDLE_TEX),
// true);
}
void FloorSearchPoint::onCollide(Actor & actor)
{
auto actorName = actor.getName();
// vC[֘ÃIuWFNgɓĂȂ
auto getFloorName = strstr(actorName.c_str(), "Floor");
// ɓĂAUZbg
if (getFloorName != NULL || actorName == "Door") {
turnCount_ = 0;
isGround_ = true;
isFloor_ = true;
return;
}
}
void FloorSearchPoint::onMessage(EventMessage event, void *){}
// ʒu̐ݒ
void FloorSearchPoint::setPosition(const Vector2& position)
{
enemyPosition_ = position;
}
// ̐ݒ
void FloorSearchPoint::setDirection(const Vector2& direction)
{
direction_ = direction;
}
// ƓԂ܂
bool FloorSearchPoint::isFloor()
{
return isFloor_;
}
bool FloorSearchPoint::isGround()
{
return isGround_;
}
// ƓꏊԂ܂
Vector2 FloorSearchPoint::getFloorPosition()
{
return floorPosition_;
}
| true |
a20d34ddf142dc31402d4dc46a9dfbf4a7947de5 | C++ | georgiosdoumas/ProgrammingCplusplus- | /CplusplusPrimer_5thEd_2012/chapter10/Exercise10.07.cpp | UTF-8 | 1,628 | 4.0625 | 4 | [] | no_license | /* Exercise 10.7: Determine if there are any errors in the following programs and, if so, correct the error(s):
(a) vector<int> vec; list<int> lst; int i;
while (cin >> i)
lst.push_back(i);
copy(lst.cbegin(), lst.cend(), vec.begin());
(b) vector<int> vec;
vec.reserve(10); // reserve is covered in § 9.4 (p. 356)
fill_n(vec.begin(), 10, 0); */
#include <algorithm>
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
int main()
{
std::vector<int> vec; // declaring and defining an empty vector
std::list<int> lst; // declaring and defining an empty list
int i;
std::cout << " Enter integers, to populate a vector, and a list that will be copy of the vector (ctr+d to finish):";
while (std::cin >> i)
lst.push_back(i); // lst is growing now
fill_n(back_inserter(vec), lst.size(), 0); // grow the vector by filling-expanding it with 0 values
copy(lst.cbegin(), lst.cend(), vec.begin());
std::cout << " Vector has elements: ";
for(auto elem: vec) std::cout << elem << " ";
std::cout<< std::endl;
std::cout << " List has elements: ";
for(auto elem: lst) std::cout << elem << " ";
std::cout<< std::endl;
std::vector<int> ivec;
//ivec.reserve(10); // WRONG! reserve() does not grow the actual vector, only allocates some memory for its easier expantion
//fill_n(ivec.begin(), 10, 0);
fill_n(back_inserter(ivec), 10, 0); // that is the correct way to grow it and fill it with 10 values of 0
for(auto elem: ivec) std::cout << elem << " ";
std::cout<< std::endl;
return 0;
}
// g++ -Wall -std=c++11 Exercise10.07.cpp -o Exercise10.07
| true |
3b9970aa939518f8835e786596f735af68d9969b | C++ | ZhongZeng/Leetcode | /lc944dltColSrt.cpp | UTF-8 | 606 | 2.90625 | 3 | [] | no_license |
/*
Leetcode 944. Delete Columns to Make Sorted
Test Cases:
["cba","daf","ghi"]
["a","b"]
["zyx","wvu","tsr"]
Runtime: 48 ms
*/
class Solution {
public:
int minDeletionSize(vector<string>& A) {
// remove all unsorted columns
if(A.size()<2||A[0].size()<1) return 0;
int rt=0;
for( int i=0; i<A[0].size(); i++){
for( int j=1; j<A.size(); j++){
if(A[j][i]<A[j-1][i]){
rt++;
break;
}
}
}
return rt;
}
}; | true |
7d090bc836a90fff1280d8287309ad2e54e62e9d | C++ | aditya865/LeetCode-June-Challenge | /week_1/day7.cpp | UTF-8 | 488 | 2.625 | 3 | [] | no_license | class Solution {
public:
int change(int amount, vector<int>& coins) {
int n=coins.size();
int table[amount+1];
memset(table,0,sizeof(table));
table[0]=1;
for(int i=0; i<n; i++)
{
for(int j=coins[i];j<=amount; j++)
table[j] += table[j-coins[i]];
for(int k=0;k<amount+1;k++)
{
cout<<table[k];
}
cout<<endl;
}
return table[amount];
}
}; | true |
85b50cad28d08f98dbd000ace9ad223cec8a6f85 | C++ | emctague/Tasks | /examples/Sensor Polling/SensorPolling.ino | UTF-8 | 774 | 3 | 3 | [] | no_license | #include <Tasks.h>
class SensorPolling : public Task {
private:
uint16_t lastReading;
const uint8_t pin;
void update()
{
lastReading = analogRead(pin);
}
public:
SensorPolling(uint8_t pin , uint16_t pollingInterval) : Task(pollingInterval), pin(pin) {
}
SensorPolling(uint8_t pin) : SensorPolling(pin, 0) {
}
uint16_t get()
{
return lastReading;
}
};
SensorPolling potentiometer = SensorPolling(A0, 20); //Important! quick updates.
SensorPolling mySensor = SensorPolling(A1, 120); //Less important.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("potentiometer: ");
Serial.print(potentiometer.get());
Serial.print(", mySensor: ");
Serial.println(mySensor.get());
} | true |
2016d9506dd745a0e5da847f3c20e3e4552e205e | C++ | n1ghtk1ng/Interview-Coding-Questions | /wormhole_without_dijkstra.cpp | UTF-8 | 960 | 2.734375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int cost=INT_MAX;
struct wormhole{
int sx;
int sy;
int ex;
int ey;
int cost;
wormhole(){}
wormhole(int a,b,c,d,e){
sx=a;
sy=b;
ex=c;
ey=d;
cost=e;
}
};
int sx,sy,dx,dy;
int calcdist(int i,wormhole w[],int a,int b){
if(i==-1){
int x=sx-dx;
int y=sy-dy;
return abs(x)+abs(y);
}
int x=abs(a-w[i].sx);
int y=abs(b-w[i].sy);
return x+y+w[i].cost;
}
void dfs(wormhole w[],int n,int i,int dist,bool vis[],int cnt,int a,int b){
dist+=calcdist(i,w,a,b);
if(i!=-1)
vis[i]=true;
if(cnt==n){
return;
}
for(int j=0;j<n;j++){
if(!vis[j]){
dfs(w,n,j,dist,vis,cnt+1,);
}
}
vis[i]=false;
}
int main(){
int n;
cin>>n;
wormhole w[n];
bool vis[n]={false};
cin>>sx>>sy>>dx>>dy;
for(int i=0;i<n;i++){
cin>>w[i].sx>>w[i].sy>>w[i].ex>>w[i].ey>>w[i].cost;
}
dfs(w,n,0);
cout<<cost;
return 0;
}
| true |
7fc5dcab357b897936ca105dc99c61ce3e9fa96a | C++ | AlixAbbasi/fsfw | /unittest/testtemplate/TestTemplate.cpp | UTF-8 | 955 | 3.015625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | #include <fsfw/unittest/catch2/catch.hpp>
#include <fsfw/unittest/core/CatchDefinitions.h>
/**
* @brief Template test file
* @details
* In each test case, the code outside the sections is executed
* for EACH section.
* The most common macros to perform tests are:
* - CHECK(...): assert expression and continues even if it fails
* - REQUIRE(...): test case fails if assertion fails
*
* Tests are generally sturctured in test cases and sections, see example
* below.
*
* More Documentation:
* - https://github.com/catchorg/Catch2
* - https://github.com/catchorg/Catch2/blob/master/docs/assertions.md
* - https://github.com/catchorg/Catch2/blob/master/docs/test-cases-and-sections.md
*/
TEST_CASE("Dummy Test" , "[DummyTest]") {
uint8_t testVariable = 1;
//perform set-up here
CHECK(testVariable == 1);
SECTION("TestSection") {
// set-up is run for each section
REQUIRE(testVariable == 1);
}
// perform tear-down here
}
| true |
65a6411816d9e3492b9d4eed1c6c7835b7b02b66 | C++ | zimkjh/-vmware_data_save | /algo/picnic1.cpp | UTF-8 | 1,296 | 3.234375 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int goodcase(int human, int group, int *groups){
bool checkL[human];
for (int i4 = 0; i4<human; i4++){
checkL[i4]= false;
} // make default false
}
int main() {
int cases;
cin >> cases;
for(int i1 = 0; i1<cases ; i1++) { // cases
int human, group;
cin>>human>>group;
int groups[group*2];
for(int i2 = 0; i2 < group ; i2++){
cin>>groups[i2*2]>>groups[i2*2+1];
}
//goodcase(human, group, groups);
bool checkL[human];
bool allchecked;
int casenum = 0;
for(int i3 = 0; i3 < group ; i3++){ // choose the first right group
for (int i4 = 0; i4<human; i4++){// make default false
checkL[i4]= false;
}
allchecked = true ;// make allchecked true
for(int i5 = i3; i5 < group ; i5++){
if(checkL[groups[i5*2]] == false && checkL[groups[i5*2+1]] == false){ // two all not checked than check!
checkL[groups[i5*2]] = true;
checkL[groups[i5*2+1]] = true;
}
//if one of them is checked, then pass
}
for(int i6= 0;i6<human; i6++){
if(checkL[i6] ==false){ //if something is unchecked , allchecked is false
allchecked = false;
}
}
if(allchecked ==true){
casenum += 1;
}
}
cout<<"case : "<< i1 << " ::::: "<<casenum<<endl;
}
}
| true |
e76d3fa61ecaa1de6e575991e2d02bfeec18592c | C++ | singhankush01/datastructure-algorithms | /maximum_sum_colum.cpp | UTF-8 | 568 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<limits>
using namespace std;
int main()
{
int m,n;
int ar[100][100];
cin>>m>>n;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>ar[i][j];
}
}
int max = INT_MIN,column;
for(int i=0;i<m;i++)
{
int sum = 0;
for(int j=0;j<n;j++)
{
sum+=ar[i][j];
}
if(sum>max)
{
max = sum;
column = i;
}
}
cout<<"Maximum Column:"<<column<<endl;
cout<<"Sum :"<<max;
return 0;
} | true |
5557d59cd03130b46bde6ac49f32b0b2108d956f | C++ | Tybus/AVLTree | /include/AVLTree.h | UTF-8 | 1,051 | 3.046875 | 3 | [] | no_license | #ifndef AVLTREE_H
#define AVLTREE_H
#include <stdexcept>
#include <iostream>
#include "AVLNode.h"
#include <string>
class AVLTree{
public:
//! Creates a empty AVLTREE
AVLTree();
//! Creates a AVLTree based on arrays of strings and cedulas
AVLTree(int i_ammount, AVLNode::NameAndID * i_aNameAndID);
//! Creates an AVLTree based on a String and a Cedula
AVLTree(AVLNode::NameAndID i_NameAndID);
//! Inserts a new entry to the AVL Tree
void AVLTreeInsert(AVLNode::NameAndID i_NameAndID);
//! Removes a entry from the AVL Tree using a Cedula
void AVLTreeRemove(uint32_t i_u32Cedula);
//! Removes an entry using a NameAndID data structure.
void AVLTreeRemove(AVLNode::NameAndID i_NameAndID);
//! Returns the Size of the AVL Tree
uint64_t AVLTreeGetSize(void);
//! Returns the Maxheight of the AVL Tree.
uint64_t AVLTreeGetMaxHeight(void);
//!Returns the higuestValue
uint64_t AVLTreeGetHighest(void);
//!Returns the LowestValue
uint64_t AVLTreeGetLowest(void);
private:
AVLNode * m_rootNode;
uint64_t m_size;
};
#endif //AVLNODE_H
| true |
98b576c4efe263933c5540000952a465155a11c3 | C++ | ChenGuyc/Projects | /silver_lining/include/singleton.hpp | UTF-8 | 1,715 | 3.421875 | 3 | [] | no_license |
/*
Singleton ensures a class only has a single instance and provides global point of access to it
T must have a default private ctor
Singleton must be a friend class T
Singleton has self-destruction
Version Date Comments
0.1 7.12.20 mentor approval
*/
#ifndef ILRD_HRD14_SINGLETON_HPP
#define ILRD_HRD14_SINGLETON_HPP
#include <mutex> // std::mutex
#include <atomic> // std::atomic
#include <memory> // std::sh
#include "scope_lock.hpp"
namespace hrd14
{
template <typename T>
class Singleton
{
public:
Singleton()= delete;
~Singleton()= delete;
Singleton(const Singleton&)= delete;
Singleton& operator=(const Singleton&)= delete;
static T* GetInstance();
private:
static std::mutex s_mutex;
static std::atomic<T*> s_instance;
static void FreeInstance();
};
template <typename T>
std::mutex Singleton<T>::s_mutex;
template <typename T>
std::atomic<T*> Singleton<T>::s_instance;
template <typename T>
T* Singleton<T>::GetInstance()
{
T* temp = s_instance.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (nullptr == temp)
{
ScopeLock<std::mutex> lock(s_mutex);
temp = s_instance.load(std::memory_order_relaxed);
if (nullptr == temp)
{
temp = new T;
std::atomic_thread_fence(std::memory_order_relaxed);
s_instance.store(temp, std::memory_order_relaxed);
atexit(FreeInstance);
}
}
return (temp);
}
template <typename T>
void Singleton<T>::FreeInstance()
{
delete s_instance.exchange(nullptr);
}
}//hrd14
#endif //ILRD_HRD14_SINGLETON_HPP | true |
c3b1dae5741636ff0acedac81afe5c624571854e | C++ | QinghuiXing/BinaryTree | /HuffmanTree.cpp | GB18030 | 6,082 | 2.578125 | 3 | [] | no_license | #include "pch.h"
#include "HuffmanTree.h"
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<algorithm>
void HuffmanCoding(HmTree & HT, HuffmanCode & HC, int * w, int n)
{
if (n < 1)return;
int m = 2 * n - 1;
HT = (HmTree)malloc((m+1)* sizeof(HTNode));
HC = (HuffmanCode)malloc(n * sizeof(char *));
HTNode* p = HT; int i = 1;
p++;
int s1, s2;
for (; i <= n; ++i, ++p, ++w)*p = { *w,0,0,0 };
for (; i <= m; ++i, ++p)*p = { 0,0,0,0 };
for (i = n + 1; i <= m;i++) {
Select(HT,i-1,s1,s2);
HT[s1].parent = i;
HT[s2].parent = i;
HT[i].lchild = s1;
HT[i].rchild = s2;
HT[i].weight = HT[s1].weight + HT[s2].weight;
}
char* cd = (char*)malloc(n * sizeof(char)), *ch1= (char*)malloc(n * sizeof(char));
cd[n - 1] = '\0';
for (int i = 1; i <= n; i++) {
int start = n - 1;
int f = HT[i].parent;
for (int c = i; f != 0; c = f, f = HT[f].parent) {
if (HT[f].lchild == c)cd[--start] = '0';
else cd[--start] = '1';
}
HC[i] = (char*)malloc((n - start) * sizeof(char));
//for (int k1 = start, k2 = n-2; k1 <=n-2; k1++,k2--) {
// ch1[k1] = cd[k2];
//}
//ch1[n - 1] = '\0';
strcpy(HC[i], &cd[start]);
}
free(cd);
}
void Select(HmTree & HT, int m, int &s1, int &s2)
{
for(int i=1;i<=m;i++)
if (HT[i].parent == 0) {
s1 = i;
break;
}
for (int i = 1; i <= m; i++) {
if (HT[i].weight < HT[s1].weight&&HT[i].parent==0)
s1 = i;
}
for (int i = 1; i <= m; i++)
if (HT[i].parent == 0 && i != s1) {
s2 = i;
break;
}
for (int i = 1; i <= m; i++) {
if (HT[i].weight < HT[s2].weight&&i != s1 && HT[i].parent == 0) {
s2 = i;
}
}
}
void LoadHuffmanTree(HmTree & HT, HuffmanCode & HC, int * &w, char * &ch, int & n, char* weightsfilename)
{
//char filename[weightsfilename.length + 1] = weightsfilename;
FILE *f = fopen(weightsfilename, "r+");
fscanf(f, "%d\n", &n);
w = (int*)malloc(n * sizeof(int));
ch = (char*)malloc(n * sizeof(char));
for (int i = 0; i < n; i++) {
fscanf(f, "%c ", &ch[i]);
fscanf(f, "%d\n", &w[i]);
}
fclose(f);
}
void SaveHuffmanTree(HmTree & HT, char* HuffTreefilename, int n)
{
//char filename[HuffTreefilename.length] = HuffTreefilename;
FILE *wr = fopen(HuffTreefilename, "w+");
int parent, weight, lchild, rchild;
for (int i = 1; i <= 2 * n - 1; i++) {
weight = HT[i].weight;
parent= HT[i].parent;
lchild = HT[i].lchild;
rchild = HT[i].rchild;
fprintf(wr, "%d %d %d %d\n", weight, parent, lchild, rchild);
}
fclose(wr);
}
void Encode(HuffmanCode & HC, char *ToBeTran, char *CodedFile)
{
FILE *tobetran, *codedfile;
tobetran = fopen(ToBeTran, "r+");
codedfile = fopen(CodedFile, "a+");
char n;
n = fgetc(tobetran);
do {
if (n == ' ')
fprintf(codedfile, "%s", HC[1]);
else if (n == '\n')
fprintf(codedfile, "\n");
else
fprintf(codedfile, "%s", HC[n - 'A' + 2]);
n = fgetc(tobetran);
} while (n!=-1);
fclose(tobetran);
fclose(codedfile);
}
void Decode(HmTree & HT, char * CodedFile, char * PlainFile, int n)
{
FILE *c = fopen(CodedFile, "r+"), *p = fopen(PlainFile, "a+");
char huffcodes[5000];
//char tmpch;
fscanf(c, "%s", huffcodes);
fclose(c);
//tmpch = fgetc(c);
int i = 0,j=2*n-1, len = strlen(huffcodes);
//int tmp = int(huffcodes[i]) - 48;
//if(c==0)
// fprintf(p,"%c",)
if (huffcodes[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
while (i <= len) {
if (HT[j].lchild == 0) {//Ҷ
if (j == 1)// '.'
fprintf(p, "%c", ' ');
else // A - Z
fprintf(p, "%c", char(j - 2 + 'A'));
i++;
if (huffcodes[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
}
else {
i++;
if (huffcodes[i] == '0')
j = HT[j].lchild;
else
j = HT[j].rchild;
}
}
fclose(p);
/*
if (tmp == 0) {//
if (HT[j].lchild == 0) {//Ҷ
if (j == 1) {// .
fprintf(p, "%c", '.');
j = 2 * n - 1;
i++;
if (huffcodes[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
}
else { // A - Z
fprintf(p, "%c", char(j - 2 + 'A'));
j = 2 * n - 1;
i++;
if (huffcodes[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
}
}//if
else {//Ҷڵ
j = HT[j].lchild;//ӽ
}
}
else {//Һ
if (HT[j].rchild == 0) {//Ҷ
if (j == 1) {// .
fprintf(p, "%c", '.');
j = 2 * n - 1;
i++;
if (huffcodes[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
}
else { // A - Z
fprintf(p, "%c", char(j - 2 + 'A'));
j = 2 * n - 1;
i++;
if (huffcodes[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
}
}//if
else {//Ҷڵ
j = HT[j].rchild;//Һӽ
}
}//if
i++;
tmp = int(huffcodes[i]) - 48;
}//while
*/
}
void EncodeStdin(HuffmanCode & HC)
{
//int len = str.length();
//int len = strlen(str);
char n='\0', str1[100];
int i = 0;
rewind(stdin);
do{
scanf("%c", &n);
str1[i++] = n;
} while (n != '\n');
for (int j = 0; j < i-1; j++) {
n = str1[j];
if (n == ' ')
printf("%s", HC[1]);
else
printf("%s", HC[n - 'A' + 2]);
}
}
void DecodeStdout(HmTree & HT, char * tobedecode, int n)
{
int i = 0, j = 2 * n - 1, len = strlen(tobedecode);
if (tobedecode[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
while (i <= len) {
if (HT[j].lchild == 0) {//Ҷ
if (j == 1)// '.'
printf("%c", ' ');
else // A - Z
printf("%c", char(j - 2 + 'A'));
i++;
if (tobedecode[i] == '0')
j = HT[2 * n - 1].lchild;
else
j = HT[2 * n - 1].rchild;
}
else {
i++;
if (tobedecode[i] == '0')
j = HT[j].lchild;
else
j = HT[j].rchild;
}
}
}
| true |
ea88f4b2f15baa684cc415d268db8783949d8e46 | C++ | alexsawyer13/TheGauntletCpp | /GauntletCpp/src/MoveContainer.h | UTF-8 | 687 | 3.640625 | 4 | [] | no_license | #pragma once
#include "Move.h"
#include <vector>
class MoveContainer
{
public:
Move Punch() { return Move("Punch", "Throws a punch at the target", 90, 30); }
Move BodySlam() { return Move("Body Slam", "Slams into the target.", 60, 90); }
Move GetMove(int index)
{
switch (index)
{
case 1: return Punch(); break;
case 2: return BodySlam(); break;
default: return Punch(); break; // Default move is punch
}
}
std::vector<Move> GetMoves(int* indices)
{
std::vector<Move> moves;
for (int i = 0; i < sizeof(indices) / sizeof(indices[0]); i++)
{
moves.push_back(GetMove(i));
}
delete[] indices;
return moves;
}
}; | true |
ea4b69c54cd28852d09d63c07e314d3acd55b018 | C++ | DriftingLQK/TrainCamp | /TrainTask/UnitTest_Solve/Test6.cpp | GB18030 | 1,358 | 2.546875 | 3 | [] | no_license | #include "stdafx.h"
void Test6(CString Title)
{
//// ȡ
int TestNum = GetPrivateProfileInt(Title, TestNumKey, 0, FILEPATH);
CString TitleFind, ArrayFind, ValueFind; //ʽϢ
ArrayFind = TestInputKey_Input;
ValueFind = TestOutputKey;
char SSS[DATASUM_BUFFER];
for (int i = 0; i < TestNum; i++) //for ѭԲ
{
_itoa(i + 1, SSS, 10);
CString index = SSS;
TitleFind = Title + "_" + index;
#pragma region ȡһ
char Iutputstr[GET_INI_MAXSIZE];
int len = GetPrivateProfileString(TitleFind, ArrayFind, "DefaultName", Iutputstr, GET_INI_MAXSIZE, FILEPATH);
char Outputbool[GET_INI_BOOL];
GetPrivateProfileString(TitleFind, ValueFind, "DefaultName", Outputbool, GET_INI_BOOL, FILEPATH);
#pragma endregion
#pragma region һݽַָ
vector<int>nums;
vector<int>flags;
if (Iutputstr[0]=='[')
{
for (int jj = 0; jj < len; jj++)
{
Iutputstr[jj] = Iutputstr[jj + 1];
}
len = len - 2;
}
int Numlen = StrToInt_New(Iutputstr, len, nums, flags);
#pragma endregion
#pragma region ԵõIJ
bool Expect_Value = (string(Outputbool) == "true");
bool Act_Value = ContainsDuplicate(nums);
Assert::AreEqual(Expect_Value, Act_Value);
#pragma endregion
} //for ѭԲ
} | true |
441306cd242253272b4d6c2adee63dc8dec6fa8b | C++ | nfb1799/IGME-209 | /Exam2/Exam2/Ogre.cpp | UTF-8 | 711 | 3.046875 | 3 | [] | no_license | #include "Ogre.h"
#include <iostream>
using namespace std;
Ogre::Ogre() : MovableObject()
{
inventoryIds = new int[3]{ 3, 9, 12 };
}
Ogre::Ogre(int _xPosition, int _yPosition) : MovableObject(_xPosition, _yPosition)
{
inventoryIds = new int[3]{ 3, 9, 12 };
}
Ogre::Ogre(int _xPosition, int _yPosition, int* _inventoryIds) : MovableObject(_xPosition, _yPosition)
{
inventoryIds = _inventoryIds;
}
Ogre::~Ogre()
{
delete[] inventoryIds;
inventoryIds = nullptr;
}
void Ogre::Display()
{
cout << "Object: Ogre" << endl;
cout << "Inventory IDs: " << inventoryIds[0] << ", " << inventoryIds[1] << ", " << inventoryIds[2] << endl;
cout << "Position: (" << xPosition << ", " << yPosition << ")" << endl;
} | true |
1df971e9bef6da5d9f915e0f30f6be1d2d403791 | C++ | hustlyhang/WSlyh | /http/timer.cpp | UTF-8 | 3,201 | 2.84375 | 3 | [] | no_license | #include "timer.h"
#include <string.h>
CHeapTimer::CHeapTimer(int _delaytime) {
m_iExpireTime = time(NULL) + _delaytime;
m_iPos = 0;
}
CTimerHeap::CTimerHeap(int _capacity):m_iCapacity(_capacity), m_iCurNum(0) {
m_aTimers = new CHeapTimer*[m_iCapacity]();
if (!m_aTimers) throw std::exception();
}
CTimerHeap::~CTimerHeap() {
delete [] m_aTimers;
for (int i = 0; i < m_iCurNum; ++i) m_aTimers[i] = nullptr;
}
// 小根堆
void CTimerHeap::HeapDown(int heap_node) {
CHeapTimer* tmp_timer = m_aTimers[heap_node];
int child = 0;
for (; heap_node * 2 + 1 < m_iCurNum; heap_node = child) {
child = heap_node * 2 + 1;
if (child + 1 < m_iCurNum && m_aTimers[child + 1]->m_iExpireTime < m_aTimers[child]->m_iExpireTime) child++;
if (tmp_timer->m_iExpireTime > m_aTimers[child]->m_iExpireTime) {
m_aTimers[heap_node] = m_aTimers[child];
m_aTimers[heap_node]->m_iPos = heap_node;
}
else break;
}
m_aTimers[heap_node] = tmp_timer;
m_aTimers[heap_node]->m_iPos = heap_node;
}
void CTimerHeap::AddTimer(CHeapTimer* add_timer) {
if (!add_timer) return;
if (m_iCurNum >= m_iCapacity) Resize();
int last_node = m_iCurNum++;
int parent = 0;
// 新加入的节点在最后,向上调整
for( ; last_node > 0; last_node = parent ) {
parent = ( last_node - 1 ) / 2;
if( m_aTimers[parent]->m_iExpireTime > add_timer->m_iExpireTime ) {
m_aTimers[last_node] = m_aTimers[parent];
m_aTimers[last_node]->m_iPos = last_node;
}
else {
break;
}
}
m_aTimers[last_node] = add_timer;
m_aTimers[last_node]->m_iPos = last_node;
LOG_INFO("add timer");
for (int i = 0; i < m_iCurNum; ++i) {
LOG_INFO("%d, %d", m_aTimers[i]->m_iExpireTime, m_aTimers[i]->m_iPos);
}
}
void CTimerHeap::Adjust(CHeapTimer* _tnode) {
HeapDown(_tnode->m_iPos);
}
void CTimerHeap::DelTimer( CHeapTimer* del_timer ) {
if( !del_timer ) return;
del_timer->callback_func = nullptr;
}
void CTimerHeap::PopTimer() {
if(!m_iCurNum) return;
if(m_aTimers[0]) {
m_aTimers[0] = m_aTimers[--m_iCurNum];
// m_aTimers[m_iCurNum] = nullptr;
HeapDown(0); // 对新的根节点进行下滤
}
}
void CTimerHeap::Tick() {
CHeapTimer* tmp_timer = m_aTimers[0];
time_t cur_time = time(NULL);
LOG_INFO("timer tick %d", cur_time);
while(m_iCurNum) {
if(!tmp_timer) break;
if(tmp_timer->m_iExpireTime > cur_time) break;
if(m_aTimers[0]->callback_func) {
m_aTimers[0]->callback_func(m_aTimers[0]->m_sClientData);
}
PopTimer();
LOG_INFO("pop timer");
tmp_timer = m_aTimers[0];
}
}
void CTimerHeap::Resize() {
LOG_INFO("resize");
CHeapTimer** tmp = new CHeapTimer*[m_iCapacity * 2]();
if(!tmp) throw std::exception();
memcpy(tmp, m_aTimers, m_iCurNum * sizeof(CHeapTimer*));
m_iCapacity *= 2;
delete[] m_aTimers;
m_aTimers = tmp;
}
CHeapTimer* CTimerHeap::GetTop(){
if (m_iCurNum != 0) {
return m_aTimers[0];
}
return nullptr;
} | true |
1db3b3503e1a65195e0d6609b44c2b860f406d6b | C++ | shubha360/CPP-Practice-Codes | /DS & Algo (Bari tutorial)/Stack/Infix to postfix 1/main.cpp | UTF-8 | 1,156 | 3.53125 | 4 | [] | no_license |
// only supports +,-,*,/
#include<iostream>
#include<stack>
using namespace std;
bool isOperand(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/')
return 0;
return 1;
}
int precedence(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
return 0;
}
string convert (string infix) {
stack<char> st;
string postfix;
auto it = infix.begin();
while (it != infix.end()) {
if (isOperand(*it))
postfix.push_back(*it++);
else {
if (st.empty() || precedence(*it) > precedence(st.top()))
st.push(*it++);
else {
postfix.push_back(st.top());
st.pop();
}
}
}
while (!st.empty()) {
postfix.push_back(st.top());
st.pop();
}
return postfix;
}
int main() {
string infix = "a+b*c/d+e-f";
string postfix = convert(infix);
cout << postfix << endl;
return 0;
} | true |
f3f68376718cf24cefacac920649899716f6af25 | C++ | orangewangjie/Algorithm-Dryad | /05.LinkedList/143.重排链表.cpp | UTF-8 | 2,326 | 3.484375 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=143 lang=cpp
*
* [143] 重排链表
*
* https://leetcode-cn.com/problems/reorder-list/description/
*
* algorithms
* Medium (59.50%)
* Likes: 500
* Dislikes: 0
* Total Accepted: 77.9K
* Total Submissions: 130.9K
* 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.
*
*/
// @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 {
ListNode* split(ListNode* head) {
auto pre = head;
auto s1 = head;
auto s2 = head;
while (s2 && s2->next) {
pre = s1;
s1 = s1->next;
s2 = s2->next->next;
}
return s2 ? s1 : pre;
}
ListNode* reverse(ListNode* head) {
ListNode dummy;
auto p = head;
while (p) {
auto back = p->next;
p->next = dummy.next;
dummy.next = p;
p = back;
}
return dummy.next;
}
public:
void reorderList(ListNode* head) {
if (!head || !head->next) {
return;
}
auto mid = split(head);
auto front = head;
auto back = mid->next;
mid->next = nullptr;
back = reverse(back);
ListNode dummy;
ListNode* tail = &dummy;
bool is_front = true;
while (front || back) {
if (!back || is_front && front) {
tail->next = front;
tail = tail->next;
front = front->next;
} else {
tail->next = back;
tail = tail->next;
back = back->next;
}
is_front = !is_front;
}
tail->next = nullptr;
}
};
// @lc code=end
| true |
39b2c6e57c36c1d2051f62fe9d7ed7df7484f1cb | C++ | zitanguo/sph_cpp_serial | /calculate_variables.cpp | UTF-8 | 3,459 | 2.609375 | 3 | [] | no_license | #include <mpi.h>
#include <hdf5.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <vector>
#include <iterator>
#include "particle.h"
void calculate_sml_den_prs(int NumoNgb, int NumoPar, std::vector<Particle *> VecoPtr2Par,
double gamma, double &SmtLenMax)
{
for (size_t i = 0; i < NumoPar; i++)
{
//*****find the smoothing length first*****
//cpp maps are sorted, so just use the # of ngbth's distance as the smt
std::map<double, Particle *>::iterator temp_stopper = VecoPtr2Par[i] -> GetDisMap().begin();
if(NumoNgb <= VecoPtr2Par[i] -> GetDisMap().size())
{
std::advance(temp_stopper, NumoNgb - 1); //move the iterator to the ngb th distance}
VecoPtr2Par[i] -> SetSmtLen(temp_stopper -> first); //"fisrt" is the key or the distance, set to the smt
}
else
{
std::cout << "warning: insufficient neighbours: " << VecoPtr2Par[i] -> GetDisMap().size()<<std::endl;
temp_stopper = VecoPtr2Par[i] -> GetDisMap().end();
VecoPtr2Par[i] -> SetSmtLen(temp_stopper -> first); //"fisrt" is the key or the distance, set to the smt
}
if(temp_stopper -> first > SmtLenMax){SmtLenMax = temp_stopper -> first;}
//*****then find the density using the just found smoothing length*****
int temp_counter = 0; //count the times of iteration
double temp_density = 0.0;
//this for loop needs -std=c++17
for(auto const& [Dis, Ptr2Par] : VecoPtr2Par[i] -> GetDisMap()){
temp_counter++;
temp_density += Ptr2Par -> GetMas() * kernel_2d3(Dis, temp_stopper -> first);
if (temp_counter >= NumoNgb) break;
}
VecoPtr2Par[i] -> SetDen(temp_density);
//*****then set the pressure using density and internal energy*****
VecoPtr2Par[i] -> CalPrs(gamma);
if(i % 10000 == 0){
std::cout << "mark 4.4.1 this particle's h, rho, prs: "<<temp_stopper -> first <<" "<<temp_density
<<" "<<VecoPtr2Par[i] -> GetPrs() <<std::endl;}
}
}
//This loop is dependent on the pressure, density and sml of every particle so has to be carried out after the first one.
void calculate_acc_intengvel_timstp(int NumoNgb, int NumoPar, std::vector<Particle *> VecoPtr2Par, double &TimStp, std::vector<double> Bdr)
{
for (size_t i = 0; i < NumoPar; i++)
{
VecoPtr2Par[i] -> CalAccIntEngVel(NumoNgb, Bdr);
//clear the map here because the assignment isn't particlely linear (it's meshly linear)
VecoPtr2Par[i] -> GetDisMap().clear();
if(i % 10000 == 0){
std::cout << "mark 4.5.1 this particle's engvel, acc: "<<VecoPtr2Par[i] -> GetIntEngVel()<<" ";
for (auto acc : VecoPtr2Par[i] -> GetAcc()) {std::cout << acc << " ";}
std::cout << std::endl;
}
//calculate timestep
double temp_time_step = pow(VecoPtr2Par[i] -> GetSmtLen() / VecoPtr2Par[i] -> GetAccAbs(), 0.5);
// std::cout <<i <<" "<<VecoPtr2Par[i] -> GetDen()<<" "<<VecoPtr2Par[i] -> GetMas() <<" "<<VecoPtr2Par[i] -> GetIntEng()<<" "
// <<VecoPtr2Par[i] -> GetSmtLen()<<" "<<VecoPtr2Par[i] -> GetPrs()<<" "<<VecoPtr2Par[i] -> GetAcc()[0]<<" "
// <<VecoPtr2Par[i] -> GetAcc()[1]<<" "<< VecoPtr2Par[i] -> GetAccAbs()<<std::endl;
//std::cout <<temp_time_step<<" " <<TimStp<<std::endl;
if( temp_time_step < TimStp)
TimStp = temp_time_step;
}
std::cout << "mark 4.5.2 finished calculating acc with timestep "<<TimStp<<std::endl;
}
| true |
6b523e25a1f00eda90df0f4b7e6a743c55d64f20 | C++ | ankenman/CS162_Winter2020 | /Final/final.cc | UTF-8 | 3,646 | 4.15625 | 4 | [] | no_license | #include <iostream>
using namespace std;
// TODO: use a loop and pointers to add all elements in array ptr
// There shouldn't be any square brackets [] in the solution
// 15 points
double sumLoop(double* ptr, size_t size) {
return 0.0;
}
// TODO: use recursion to sum all the elements in array ptr
// Define your base case and recursive call
// 15 points
double sumRec(double* ptr, size_t size) {
return 0.0;
}
class LinkedList {
public:
LinkedList() {
// TODO: initialize list
// head can point to a dummy node or to null, but ensure that your
// member functions adhere to that representation
// 5 points
}
~LinkedList() {
// Deallocate all nodes in the list. You can use a loop or recursive helper
// Suggestion: use your popFront member function
// 10 points
}
void printList() {
// TODO: Call recursive helper function to print out the list
// Use this form (no need to check for end of list):
// { 1.0 2.0 3.0 }
// 10 points
}
void pushFront(double newData) {
// TODO: Add element to front of list
// 10 points
}
void pushBack(double newData) {
// TODO: Add an element to the back of the list using helper function
// 15 points
}
double popFront() {
// TODO: Remove and return element from front of list
// ASSUMEPTION: We will not remove from an empty list
// Do NOT do any error checking for that
// 15 points
return 0.0;
}
int getLength() {
// TODO: Call recursive helper function to count the number of nodes
// 10 points
return 0;
}
private:
struct Node {
double data;
Node *next;
};
Node *head;
// Private helper functions
void printHelper(Node *n) {
// TODO: Print out list recursively
// 15 points
}
int countNodes(Node *n) {
// TODO: Recursively count nodes
// 15 points
return 0;
}
Node* findEnd(Node *n) {
// TODO: Retrun last node of the list
// e.g., the node that is pointing to null
// 15 points
return nullptr;
}
};
int main() {
double array[] = { 3.4, -5.6, 1.2, -3.5 };
int size = 4;
cout << "Testing sumLoop ****************\n";
cout << "\t Expecting -4.5, got " << sumLoop(array, size) << endl;
cout << "Testing sumRec ****************\n";
cout << "\t Expecting -4.5, got " << sumRec(array, size) << endl;
cout << "\n\nTesting LinkedList ****************\n";
LinkedList list;
for (double i = -8.4; i < 8.0; i += 3.3) {
list.pushFront(i);
}
cout << "\tTesting pushFront, printList, getLength\n";
cout << "\tprintList: Expecting { 4.8 1.5 -1.8 -5.1 -8.4 } and got ";
list.printList();
cout << endl;
cout << "\tgetLength: Expecting 5 and got " << list.getLength() << endl;
cout << "\n\tTesting pushBack\n";
list.pushBack(3.4);
cout << "\tprintList: Expecting { 4.8 1.5 -1.8 -5.1 -8.4 3.4 } and got ";
list.printList();
cout << endl;
cout << "\tgetLength: Expecting 6 and got " << list.getLength() << endl;
cout << "\n\tTesting popFront\n";
double poppedValue = list.popFront();
cout << "\tExpected 4.8 and got " << poppedValue << endl;
list.printList();
cout << endl;
return 0;
}
| true |
f923a919ab982a68db19d4671d574859ac982bfc | C++ | nchkdxlq/Algorithm | /Algorithm/Algorithm/Graph/SparseGraph.hpp | UTF-8 | 1,478 | 3.15625 | 3 | [
"MIT"
] | permissive | //
// SparseGraph.hpp
// Algorithm
//
// Created by nchkdxlq on 2017/9/13.
// Copyright © 2017年 nchkdxlq. All rights reserved.
//
#ifndef SparseGraph_hpp
#define SparseGraph_hpp
#include <stdio.h>
#include <vector>
using namespace std;
/*
稀疏图 邻接表
缺点:
1.
*/
class SparseGraph {
private:
int m_v; // 顶点的个数 (vertex count)
int m_e; // 边数 (edge count)
bool m_directed;
vector<vector<int>> m_graph;
public:
SparseGraph(int n, bool directed);
~SparseGraph();
int V();
int E();
bool hasEdge(int v, int w);
void addEdge(int v, int w);
void show();
class Iterator {
private:
SparseGraph &m_G;
int m_vertex;
int m_index;
public:
Iterator(SparseGraph &g, int v): m_G(g) {
m_vertex = v;
m_index = -1;
}
~Iterator() {
}
int begin() {
m_index = 0;
if (m_G.m_graph[m_vertex].size() > 0)
return m_G.m_graph[m_vertex][0];
return -1;
}
int next() {
m_index++;
if (m_index < m_G.m_graph[m_vertex].size())
return m_G.m_graph[m_vertex][m_index];
return -1;
}
bool end() {
return m_index >= m_G.m_graph[m_vertex].size();
}
};
};
#endif /* SparseGraph_hpp */
| true |
cc59cb549447be754a3fbefb6062fefdbab55e28 | C++ | mvdsanden/mvds | /Process/execute.cc | UTF-8 | 1,835 | 2.953125 | 3 | [] | no_license | #include "process.ih"
#include <cstdlib>
#include <fcntl.h>
#include <iostream>
#include "../FDStream/fdstream.hh"
#include "../IOError/ioerror.hh"
int Process::execute(std::string const &command)
{
d_inPipe[0] = 0;
d_inPipe[1] = 0;
// Create the pipes
if (pipe(d_inPipe) < 0)
throw IOError(errno,"Process: error creating in pipe");
if (pipe(d_outPipe) < 0)
throw IOError(errno,"Process: error creating out pipe");
if (pipe(d_errPipe) < 0)
throw IOError(errno,"Process: error creating err pipe");
// Fork!
d_pid = fork();
if (d_pid < 0)
throw runtime_error("Process: error forking");
else if (!d_pid) { // We are the child process!
try {
close(d_inPipe[1]);
close(d_outPipe[0]);
close(d_errPipe[0]);
// Redirect stdin to the in pipe.
if (dup2(d_inPipe[0],0) < 0)
throw IOError(errno,"Process: redirecting stdin to in pipe");
close(d_inPipe[0]);
// Redirect the stdout to the out pipe.
if (dup2(d_outPipe[1],1) < 0)
throw IOError(errno,"Process: redirecting stdout to out pipe");
close(d_outPipe[1]);
// Redirect the stderr to the err pipe.
if (dup2(d_errPipe[1],2) < 0)
throw IOError(errno,"Process: redirecting stderr to err pipe");
close(d_errPipe[1]);
// Run the command.
if (execl("/bin/sh","/bin/sh","-c",command.c_str(),static_cast<char*>(0)) < 0)
throw IOError(errno,"Process: executing process");
} catch (runtime_error &e) {
cerr << "Process error in fork: " << e.what() << endl;
// If it returns an error has occured...
exit(1);
}
} else {
// Close the end of the pipes we do not use.
close(d_inPipe[0]);
close(d_outPipe[1]);
close(d_errPipe[1]);
// Create stl streams from them.
d_in = new OFDStream(d_inPipe[1]);
d_out = new IFDStream(d_outPipe[0]);
d_err = new IFDStream(d_errPipe[0]);
}
return d_pid;
}
| true |
ca4b0600873cb8ded22578c9e3bc8534102b1070 | C++ | hobbang2/Algorithm | /legacy/백준알고리즘/boj6044_애너그램.cpp | UTF-8 | 1,060 | 3.109375 | 3 | [] | no_license | //#include <iostream>
//#include <string>
//#include <vector>
//#include <set>
//#include <algorithm>
//using namespace std;
//
//int main()
//{
// int N;
// cin >> N;
// getchar();
//
// vector <vector <char> > word_dict(N);
// char alpha = '0';
//
// for(int i = 0; i < N ; i++)
// {
// while (scanf("%c", &alpha), alpha != '\n')
// {
// word_dict[i].push_back(alpha);
// }
//
// sort(word_dict[i].begin(), word_dict[i].end());
// do
// {
// for (auto it = word_dict[i].begin(); it != word_dict[i].end(); it++)
// {
// cout << *it;
// }
// cout << "\n";
// } while (next_permutation(word_dict[i].begin(), word_dict[i].end()));
// }
//
//
// return 0;
//}
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
int N;
cin >> N;
getchar();
char alpha = '0';
for (int i = 0; i < N; i++)
{
string word;
cin >> word;
sort(word.begin(), word.end());
do
{
cout << word<<"\n";
} while (next_permutation(word.begin(), word.end()));
}
return 0;
} | true |
2a25ad3edcb6b83415b771ebb691a34959ecf916 | C++ | d3v1c3nv11/eduArdu | /SOFTWARE/3_eduArdu_LightSensor/Light_Sensor.cpp | UTF-8 | 259 | 3 | 3 | [
"Apache-2.0"
] | permissive | #include "Light_Sensor.h"
Light_Sensor::Light_Sensor (int _Pin)
{
Pin = _Pin;
pinMode (Pin, INPUT_PULLUP);
}
int Light_Sensor::Read ()
{
return analogRead(Pin);
}
float Light_Sensor::ReadPercentage ()
{
return Read() * 100.0/1023.0;
}
| true |
7d07a07c3c573fb1b779eb6a8701dffdb42f80f0 | C++ | ruher/libcanon | /include/libcanon/eldag.h | UTF-8 | 35,799 | 2.890625 | 3 | [
"MIT"
] | permissive | /** Canonicalization of edge-labelled directed acyclic graphs.
*
* Edge-labelled directly acyclic graphs (ELDAGs) are generalization of the
* normal DAGs with a label for each edge. And the labels for the edges can
* possibly be permuted. The algorithm here is based on the spirit of the
* algorithm by B McKay for normal graphs.
*/
#ifndef LIBCANON_ELDAG_H
#define LIBCANON_ELDAG_H
#include <algorithm>
#include <cassert>
#include <iterator>
#include <memory>
#include <numeric>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include <libcanon/partition.h>
#include <libcanon/perm.h>
#include <libcanon/sims.h>
#include <libcanon/string.h>
#include <libcanon/utils.h>
namespace libcanon {
//
// Type for eldags
// ---------------
//
/** Data type for an Eldag.
*
* This is basically a CSR format to stored the children of each node. This
* data structure should have very high cache friendliness.
*
* Note that variant information like the colour and symmetry at each node is
* not stored here.
*
* It is implemented here as a struct since the structure should be transparent
* to developers.
*/
struct Eldag {
/** The edges from each node to other nodes.
*
* Stored as list of indices for the index of the nodes that they are
* connected to.
*/
std::vector<size_t> edges;
/** The start index for the connections of each node.
*
* This is basically the same as the IA array for CSR.
*/
std::vector<size_t> ia;
/** Gets the number of nodes in the Eldag.
*/
size_t size() const { return ia.size() - 1; }
/** Gets the number of edges in the Eldag.
*/
size_t n_edges() const { return edges.size(); }
/** Gets the number of valences of a node.
*/
size_t n_valences(Point node) const
{
assert(node >= 0 && node < size());
return ia[node + 1] - ia[node];
}
/** Creates an Eldag of a given size.
*
* Note that here the vectors are only set to the correct size without any
* valid content.
*/
Eldag(size_t n_nodes, size_t n_edges)
: edges(n_edges)
, ia(n_nodes + 1)
{
}
/** Creates an empty Eldag.
*
* This empty Eldag is not completely empty, a zero is already added to the
* ia array.
*/
Eldag()
: edges()
, ia{ 0 }
{
}
/** Constructs an eldag directly from its edges and ia.
*/
template <typename T1, typename T2,
typename = std::enable_if_t<
std::is_constructible<std::vector<size_t>, T1>::value>,
typename = std::enable_if_t<
std::is_constructible<std::vector<size_t>, T2>::value>>
Eldag(T1&& edges, T2&& ia)
: edges(std::forward<T1>(edges))
, ia(std::forward<T2>(ia))
{
}
/** Copy constructs an eldag.
*/
Eldag(const Eldag& eldag) = default;
/** Move constructs an eldag.
*/
Eldag(Eldag&& eldag) = default;
/** Copy assignment for an eldag.
*/
Eldag& operator=(const Eldag& eldag) = default;
/** Move assignment for an eldag.
*/
Eldag& operator=(Eldag&& eldag) = default;
/** Pushes the current number of edges into ia.
*
* This method can be helpful after finish adding edges from a node.
*/
void update_ia() { ia.push_back(edges.size()); }
/** Evaluates the hash of an Eldag.
*
* This is a very simple-minded hash function, just the values in the two
* arrays are combined.
*/
size_t hash() const
{
size_t seed = 0;
for (size_t i : edges) {
combine_hash(seed, i);
}
for (size_t i : ia) {
combine_hash(seed, i);
}
return seed;
}
/** Compares two eldags for equality.
*/
bool operator==(const Eldag& other) const
{
return ia == other.ia && edges == other.edges;
}
/** Compares two eldges lexicographically.
*
* This comparison does not have any actual physical meanings. However, it
* does constitute a total order on the set of all eldags.
*/
bool operator<(const Eldag& other) const
{
return ia < other.ia || (ia == other.ia && edges < other.edges);
}
};
//
// Utilities for node symmetries and permutations
// ----------------------------------------------
//
/** The data type to given symmetries for the nodes in an Eldag.
*
* Here the container is fixed to vector for the ease of coding. Null values
* are considered to be the absence of any symmetries.
*
* This type is going to be mainly used as input for the symmetries of nodes in
* the public driver functions for Eldag canonicalization.
*/
template <typename P> using Node_symms = std::vector<const Sims_transv<P>*>;
/** The data type for the permutations to be applied to nodes in an Eldag.
*
* A vector of unique pointer to the given permutation type. This is going to
* be mainly in the return value of the public driver function for Eldag
* canonicalization. Note that here the value owns the reference to the
* permutations.
*/
template <typename P> using Node_perms = std::vector<std::unique_ptr<P>>;
/** Data type for owned references to node symmetries.
*/
template <typename P>
using Owned_node_symms = std::vector<std::unique_ptr<Sims_transv<P>>>;
/** Data type for borrowed references to node permutations.
*/
template <typename P> using Borrowed_node_perms = std::vector<const P*>;
/** Borrows references from owned references.
*
* It is here implemented with vector hard-coded. This is designed solely for
* the node symmetry and permutation types.
*/
template <typename T>
std::vector<const T*> borrow_pointers(
const std::vector<std::unique_ptr<T>>& owned_pointers)
{
std::vector<const T*> res;
std::transform(owned_pointers.begin(), owned_pointers.end(),
std::back_inserter(res), [](const auto& i) { return i.get(); });
return res;
}
/** Acts permutations on an Eldag.
*
* Here the global permutation of the nodes should be given in a
* permutation-like object supporting operators `<<` and `>>`, the local
* permutation acting on each node should be given as an indexable container
* containing pointer-like objects pointing to the actual permutations on each
* node. Null values indicates the absence of any permutation.
*/
template <typename G, typename L>
Eldag act_eldag(const G& gl_perm, const L& perms, const Eldag& eldag)
{
size_t size = eldag.size();
Eldag res(size, eldag.n_edges());
res.ia.clear();
// The index that the next connection is going to be written to.
size_t curr_idx = 0;
res.ia.push_back(curr_idx);
// Constructs the nodes in the result one-by-one.
for (size_t curr = 0; curr < size; ++curr) {
Point pre_img = gl_perm >> curr;
size_t prev_base = eldag.ia[pre_img];
size_t valence = eldag.ia[pre_img + 1] - prev_base;
for (size_t i = 0; i < valence; ++i) {
size_t offset = i;
if (perms[pre_img]) {
offset = *perms[pre_img] >> offset;
}
assert(offset >= 0 && offset < valence);
Point conn = gl_perm << eldag.edges[prev_base + offset];
res.edges[curr_idx] = conn;
++curr_idx;
}
res.ia.push_back(curr_idx);
}
return res;
}
/** Data type for a permutation on an Eldag.
*
* Inside it, we have not only the global permutation of the nodes, but the
* permutation on valences of each nodes as well.
*
* Note that the permutation stored in the graph automorphism are not of
* this type, but rather simple permutations of the nodes. This is
* achieved by delegate to proxy types for the expression `g | ~h`.
*/
template <typename P> struct Eldag_perm {
/** The permutations on each of the nodes. */
Node_perms<P> perms;
/** The global partition of the nodes.
*
* It should be a singleton partition already.
*/
Partition partition;
/** The class for the inversion of an Eldag permutation. */
struct Inv_eldag_perm {
const Eldag_perm& operand;
};
/** Inverses a permutation.
*
* No actual inversion is done. Just a proxy is returned.
*/
Inv_eldag_perm operator~() const { return { *this }; }
/** Forms an automorphism.
*
* This function will be called by the generic canonicalization
* function by the evaluation of the expression `p | ~q`.
*/
Simple_perm operator|(const Inv_eldag_perm& inv)
{
size_t size = partition.size();
std::vector<Point> pre_imgs(size);
const auto& p = partition.get_pre_imgs();
const auto& q = inv.operand.partition.get_pre_imgs();
for (size_t i = 0; i < size; ++i) {
// By ~q, q[i] <- i;
pre_imgs[q[i]] = p[i];
}
return std::move(pre_imgs);
}
/** Gets the pre-image of a given point.
*/
Point operator>>(Point point) const { return partition >> point; }
/** Gets the permutations for each node.
*
* The returned vector will have borrowed reference for the permutations.
*/
Borrowed_node_perms<P> get_perms() const { return borrow_pointers(perms); }
};
/** Acts an eldag with a given permutation.
*
* This is a convenience wrapper function for acting the permutations
* encapsulated in an Eldag_perm object onto an Eldag.
*/
template <typename P>
Eldag act_eldag(const Eldag_perm<P>& perm, const Eldag& eldag)
{
return act_eldag(perm.partition.make_perm(), perm.get_perms(), eldag);
}
//
// Core canonicalization support
// -----------------------------
//
/** Data type for a coset in the canonicalization of an Eldag.
*
* Basically, it has a global partition of the nodes, the symmetries and
* applied permutations for each of the nodes, which can be from the parent
* coset or from the refined permutation and symmetries owned by itself.
*/
template <typename P> class Eldag_coset {
public:
/** Constructs a coset based on initial partition and symmetries.
*
* This is useful for the creation of root coset.
*
* The templating here is just for perfect forwarding. The initial
* partition is assumed to be a Partition object.
*/
template <typename T>
Eldag_coset(
const Eldag& eldag, T&& init_part, const Node_symms<P>& init_symms)
: partition_(std::forward<T>(init_part))
, perms_(init_part.size(), nullptr)
, symms_(init_symms)
, refined_perms_(init_part.size())
, refined_symms_(init_part.size())
, individualized_(init_part.size())
{
assert(init_part.size() == init_symms.size());
refine(eldag);
}
/** Constructs a coset by individualizing a point.
*
* This is useful for the individualization step. Note that this
* construction is better used on cosets after refinement.
*/
Eldag_coset(const Eldag& eldag, const Eldag_coset& base, Point point)
: partition_(base.partition_, point)
, perms_(base.perms_)
, symms_(base.symms_)
, refined_perms_(eldag.size())
, refined_symms_(eldag.size())
, individualized_(point)
{
refine(eldag);
}
/** Constructs a coset by acting a permutation.
*
* This is useful for the pruning of the refinement tree. Note that the
* created coset is not actually fully valid one. Just the individualized
* point is correctly set for the sake of removing the actual coset in a
* hash set/map.
*/
Eldag_coset(const Eldag_coset& base, const Simple_perm& perm)
: partition_()
, perms_()
, symms_()
, refined_perms_()
, refined_symms_()
, individualized_(perm << base.individualized())
{
}
//
// Individualization support
//
// The cosets with individualized node needs to be able to be looped over
// lazily.
//
/** Container for a non-singleton cell.
*
* In addition to storing a pair of iterators for the points in the cell,
* here we also have reference to the eldag and the parent coset. In this
* way, it can be iterable to get the cosets from individualizing the
* points in the cell.
*
* For convenience, it is implemented as a template in case we need other
* forms of iterators.
*/
template <typename Cell_it> class Nonsingleton_cell {
public:
/** Constructs a non-singleton cell.
*/
Nonsingleton_cell(const Eldag& eldag, const Eldag_coset& coset,
Cell_it cell_begin, Cell_it cell_end)
: eldag_(eldag)
, parent_(coset)
, cell_begin_(cell_begin)
, cell_end_(cell_end)
{
}
/** Gets the begin of the iterator over the cell.
*
* Here we make a copy that is slightly redundant. In this way, the
* cell can be iterated over multiple times when it is really needed.
*/
Cell_it cell_begin() const { return cell_begin_; }
/** Gets the end of the iterator over the cell.
*/
Cell_it cell_end() const { return cell_end_; }
/** Gets the eldag.
*/
const Eldag& eldag() const { return eldag_; }
/** Gets the parent coset.
*/
const Eldag_coset& parent() const { return parent_; }
private:
/** The eldag that the coset is for.
*/
const Eldag& eldag_;
/** The parent coset.
*/
const Eldag_coset& parent_;
/** The begin of the iterators for the non-singleton cell.
*/
Cell_it cell_begin_;
/** Sentinel for iterating over the points in the non-singleton cell.
*/
Cell_it cell_end_;
};
/** Forms a non-singleton cell instance.
*
* Let's just hope for earlier wide adoption of C++17.
*/
template <typename Cell_it>
static Nonsingleton_cell<Cell_it> make_nonsingleton_cell(const Eldag& eldag,
const Eldag_coset& coset, Cell_it cell_begin, Cell_it cell_end)
{
return { eldag, coset, cell_begin, cell_end };
}
/** Iterator for iterating over cosets from individualizing points in cell.
*/
template <typename Cell_it> struct Invididualized_it {
/** The actual iterator over the points.
*/
Cell_it curr;
/** Reference to the non-singleton cell.
*/
const Nonsingleton_cell<Cell_it>& cell;
/** Increments the iterator.
*/
Invididualized_it& operator++()
{
++curr;
return *this;
}
/** Dereferences the iterator.
*
* Note that here the dereferencing gives values directly (R-value).
*/
Eldag_coset operator*() const
{
return { cell.eldag(), cell.parent(), *curr };
}
/** Compares two iterators for equality.
*/
bool operator==(const Invididualized_it& other) const
{
return curr == other.curr;
}
/** Compares two iterators for inequality.
*/
bool operator!=(const Invididualized_it& other) const
{
return !(*this == other);
}
/** The reference type.
*
* This iterator generates the points as R-value directly.
*/
using reference = Eldag_coset;
/** The value type.
*/
using value_type = Eldag_coset;
/** The iterator category.
*/
using iterator_category = std::input_iterator_tag;
/** The pointer type.
*
* Here we temporarily do not implement the -> operator. It can be
* added when portability problem occurs.
*/
using pointer = void;
/** Different type.
*
* Here we just use the major signed int type.
*/
using difference_type = ptrdiff_t;
};
/** Begins the iteration over the individualized cosets.
*/
template <typename Cell_it>
friend Invididualized_it<Cell_it> begin(
const Nonsingleton_cell<Cell_it>& nonsingleton_cell)
{
return { nonsingleton_cell.cell_begin(), nonsingleton_cell };
}
/** Gets the sentinel for iterating over individualized cosets.
*/
template <typename Cell_it>
friend Invididualized_it<Cell_it> end(
const Nonsingleton_cell<Cell_it>& nonsingleton_cell)
{
return { nonsingleton_cell.cell_end(), nonsingleton_cell };
}
/** Individualizes the refined partition.
*
* Here we return a lazy iterable that can be looped over to get the actual
* cosets from individualizing the points in the first non-singleton cell.
*/
auto individualize_first_nonsingleton(const Eldag& eldag) const
{
auto cell = std::find_if(partition_.begin(), partition_.end(),
[&](auto cell) { return partition_.get_cell_size(cell) > 1; });
// When used correctly, we should find a non-singleton cell here.
assert(cell != partition_.end());
return make_nonsingleton_cell(eldag, *this,
partition_.cell_begin(*cell), partition_.cell_end(*cell));
}
//
// End of individualization section.
//
/** Tests if the result is a leaf.
*/
bool is_leaf(const Eldag& eldag) const { return partition_.is_discrete(); }
/** Gets a perm from the coset.
*
* This method can only be called on leaves. And it will *move* the
* information about the permutation into the result.
*/
Eldag_perm<P> get_a_perm() const
{
// Here we can skip some unnecessary copy by having the refined
// permutations and partitions as mutable.
//
Node_perms<P> node_perms(size());
for (size_t i = 0; i < size(); ++i) {
if (!perms_[i]) {
// When we have never applied a permutation on the node.
continue;
} else if (refined_perms_[i]) {
// When the leaf coset actually owns the permutation.
node_perms[i] = std::move(refined_perms_[i]);
} else {
// Or we have to make a copy since it might still going to be
// used by earlier cosets.
node_perms[i] = std::make_unique<P>(*perms_[i]);
}
}
return { std::move(node_perms), std::move(partition_) };
}
/** Gets the point individualized during its construction.
*/
Point individualized() const { return individualized_; }
/** Gets the size of the graph.
*
* Here we use the size of the immutable permutations vector, in case the
* contents in mutable members has been moved out.
*/
size_t size() const
{
size_t size = perms_.size();
assert(symms_.size() == size);
return size;
}
/** Compares two cosets for equality.
*
* Here only the point that is individualized is compared. So it is
* actually only applicable to peers.
*/
bool operator==(const Eldag_coset& other) const
{
return individualized() == other.individualized();
}
/** Evaluates the hash of a coset.
*
* Note that only the individualized point is used. So it is only
* useful for retrieval amongst it peers.
*/
size_t hash() const { return individualized(); }
private:
//
// Core refinement facilities
//
// Data types for node distinguishing.
/** The orbit label of valences of a node.
*
* Values of this type can be used to map a valence of a node to its orbit
* label. Here longer orbits are considered smaller so that nodes with
* higher degree will be given smaller index, which might be more natural.
*/
class Orbit : public std::vector<Point> {
public:
/** Alias for the base type.
*/
using Base = std::vector<Point>;
/** Inheriting all the constructors from the base type.
*/
using Base::Base;
/** Makes revdeg comparison.
*/
bool operator<(const Orbit& other) const
{
return is_degrev_less<std::vector<Point>>(*this, other);
}
};
/** The orbits of nodes in an Eldag.
*
* The orbit vector for any node should be able to be queried by indexing
* it.
*/
using Orbits = std::vector<Orbit>;
/** An edge in detail.
*
* It is a sorted list of all the orbit labels of all the edges from
* the parent node to the children.
*/
using Detailed_edge = std::vector<size_t>;
/** Detailed description of the in/out edges between a node and a cell.
*
* The result should be sorted for set semantics. It is implemented as a
* struct here to have better control over the comparison order among them.
* Since the values are mostly only used for lexicographical comparison,
* without need to be queried for a specific edge, here it is based on
* vector rather than multi-set for better cache friendliness with the same
* complexity.
*/
class Detailed_edges : public std::vector<Detailed_edge> {
public:
/** Compares two for order.
*
* Here larger number of connections is considered smaller. In
* this way, when we sweep the cells from beginning to end, nodes
* with more connection with nodes of earlier colour will be put
* earlier.
*/
bool operator<(const Detailed_edges& other) const
{
return is_degrev_less<std::vector<Detailed_edge>>(*this, other);
}
};
/** Detailed description of the connection between a node and a cell.
*
* Here we have information about both the in and the out edges. Default
* lexicographical order will be used.
*
* Normally for Eldag, either the in edges or the out edges are just empty.
*/
using Conn = std::pair<Detailed_edges, Detailed_edges>;
/** The connection information of all nodes.
*
* This vector is designed to be directly indexed by node labels for the
* connection description. Note that normally only the entries for nodes
* in the same cell are comparable.
*/
using Conns = std::vector<Conn>;
// Driver function.
/** Refines the global partition and local symmetries.
*
* Most of the actual work of the canonicalization of Eldag actually
* comes here.
*/
void refine(const Eldag& eldag)
{
// Refine until fixed point.
while (true) {
// First refine the automorphism at each node and form the orbits.
refine_nodes(eldag);
Orbits orbits = form_orbits(eldag);
//
// Unary split based on orbits.
//
bool split = false;
// Back up the current partition for unary split, which does not
// benefit from the repeated refinement.
std::vector<size_t> curr_partition(
partition_.begin(), partition_.end());
for (auto i : curr_partition) {
split |= partition_.split_by_key(i,
[&](auto point) -> const Orbit& { return orbits[point]; });
}
if (split) {
// Binary split is expensive. Refine as much as possible
// before carrying it out.
continue;
}
// Now all the nodes in the same cell must have identical orbit
// labelling. So that their comparison by connection labels start
// to make sense.
//
// Binary split.
//
split = false;
Conns conns(size());
// Here for each loop, we always take advantage of the latest
// refine due to the special semantics of looping over cells in a
// partition.
for (auto splittee_i = partition_.rbegin();
splittee_i != partition_.rend(); ++splittee_i) {
for (auto splitter_i = partition_.begin();
splitter_i != partition_.end(); ++splitter_i) {
// Short-cut singleton partitions. It is put here rather
// than the upper loop since a cell might be partitioned to
// singleton early before all the splitters are looped
// over.
if (partition_.get_cell_size(*splittee_i) < 2)
break;
update_conns4cell(
conns, eldag, orbits, *splittee_i, *splitter_i);
split |= partition_.split_by_key(*splittee_i,
[&](auto point) -> const Conn& { return conns[point]; },
splittee_i, splitter_i);
} // End loop over splitters.
} // End loop over splittees.
if (split) {
continue;
} else {
// Now we reached a fixed point.
break;
}
}; // End main loop.
}
// Local refinement of the symmetries.
/** The class representing the valences of a node.
*
* This class is designed to be directly interoperable with the string
* canonicalization facilities.
*/
class Valence {
public:
Valence(const Eldag& eldag, const Partition& partition, Point node,
const P* perm)
: eldag_(&eldag)
, partition_(&partition)
, node_(node)
, perm_(perm)
{
assert(eldag.size() == partition.size());
assert(0 <= node && node < partition.size());
}
/** Gets the colour of the node connected to a given slot.
*/
Point operator[](size_t slot) const
{
size_t offset = slot;
if (perm_) {
offset = *perm_ >> slot;
}
auto base_idx = eldag_->ia[node_];
assert(offset >= 0 && offset < eldag_->n_valences(node_));
return partition_->get_colour(eldag_->edges[base_idx + offset]);
}
private:
/** The Eldag that the valence is for.
*/
const Eldag* eldag_;
/** The current partition of the nodes in the Eldag.
*/
const Partition* partition_;
/** The node label for this.
*/
Point node_;
/** The current permutation of the node.
*/
const P* perm_;
};
/** Refines the automorphism of all nodes.
*
* In this function, the permutations and symmetries for each node will be
* refined as much as possible based on the current partition of the nodes.
*/
void refine_nodes(const Eldag& eldag)
{
// Refinement for nodes are independent.
for (size_t i = 0; i < size(); ++i) {
auto curr_symm = symms_[i];
if (!curr_symm) {
// Nodes without symmetry, without need for *further*
// refinement.
continue;
}
Valence valence(eldag, partition_, i, perms_[i]);
auto canon_res = canon_string(valence, *curr_symm);
if (!perms_[i]) {
// When nothing has ever been applied to the node.
refined_perms_[i]
= std::make_unique<P>(std::move(canon_res.first));
} else {
// Just to be safe about the order of evaluation.
auto new_perm
= std::make_unique<P>(*perms_[i] | canon_res.first);
refined_perms_[i] = std::move(new_perm);
}
refined_symms_[i] = std::move(canon_res.second);
perms_[i] = refined_perms_[i].get();
symms_[i] = refined_symms_[i].get();
}
}
/** Forms the orbit label array for all nodes.
*/
Orbits form_orbits(const Eldag& eldag) const
{
Orbits res{};
for (size_t node = 0; node < eldag.size(); ++node) {
size_t n_valences = eldag.n_valences(node);
Orbit orbit(n_valences);
std::iota(orbit.begin(), orbit.end(), 0);
for (size_t base = 0; base < n_valences; ++base) {
for (const Sims_transv<P>* transv = symms_[node];
transv != nullptr; transv = transv->next()) {
for (const auto& perm : *transv) {
orbit[perm << base] = orbit[base];
}
}
}
res.push_back(std::move(orbit));
}
return res;
}
// Binary refinements.
/** Updates the connection information.
*/
void update_conns4cell(Conns& conns, const Eldag& eldag,
const Orbits& orbits, Point splittee, Point splitter)
{
// Normally this function should not be called on singleton cells,
// since it can be just purely waste.
assert(partition_.get_cell_size(splittee) > 1);
std::for_each(partition_.cell_begin(splittee),
partition_.cell_end(splittee), [&](Point base) {
Detailed_edges& ins = conns[base].first;
Detailed_edges& outs = conns[base].second;
ins.clear();
outs.clear();
std::for_each(partition_.cell_begin(splitter),
partition_.cell_end(splitter), [&](Point curr) {
// Add connection with the current point.
add_detailed_edges(ins, eldag, orbits, curr, base);
add_detailed_edges(outs, eldag, orbits, base, curr);
});
std::sort(ins.begin(), ins.end());
std::sort(outs.begin(), outs.end());
});
}
/** Adds detailed edge from a point to another if there is any.
*
* Empty connection will not be added.
*/
void add_detailed_edges(Detailed_edges& dest, const Eldag& eldag,
const Orbits& orbits, Point from, Point to)
{
Detailed_edge edge{};
size_t base_idx = eldag.ia[from];
size_t n_valences = eldag.n_valences(from);
for (size_t i = 0; i < n_valences; ++i) {
Point conn_node = eldag.edges[base_idx + i];
if (conn_node == to) {
size_t index = perms_[from] ? *perms_[from] << i : i;
edge.push_back(orbits[from][index]);
}
}
if (edge.size() == 0)
return;
std::sort(edge.begin(), edge.end());
dest.push_back(std::move(edge));
return;
}
//
// Data fields
//
/** The partition of graph nodes.
*
* It will be refined in the initialization. It is set to be mutable here
* so that the constant method for getting a permutation can move its
* content out without copying.
*/
mutable Partition partition_;
//
// Here we have two arrays for both node permutations and node symmetries,
// with one being owned pointers and another being borrowed.
//
// The rationale for this is that the borrowed pointers are for the
// symmetries and permutations passed in from earlier cosets. And the
// owned ones will be for the symmetries and permutations refined from the
// current step. When further refinement is carried out for a node in the
// current step, the two are actually identical. Or when further
// refinement is not carried out for a node, the owned pointer will stay to
// be null and the borrowed pointers will stay what it was set to be.
//
/** The current permutations applied to the nodes.
*/
Borrowed_node_perms<P> perms_;
/** The current symmetries for each of the nodes.
*/
Node_symms<P> symms_;
/** The permutation on each node after refinement.
*
* It is set to be mutable here so that the constant method for getting a
* permutation can extract its content out.
*/
mutable Node_perms<P> refined_perms_;
/** Refined symmetries for each node.
*/
Owned_node_symms<P> refined_symms_;
/**
* The point that is individualized in the construction of this coset.
*/
Point individualized_;
};
/** The actual refiner for Eldag canonicalization.
*/
template <typename P> class Eldag_refiner {
public:
//
// Types required by the refiner protocol.
//
using Coset = Eldag_coset<P>;
using Structure = Eldag;
//
// Types not required by the refiner protocol.
//
// They are included here just for convenience.
using Perm = Eldag_perm<P>;
/** Refines the given coset.
*/
auto refine(const Eldag& eldag, const Coset& coset)
{
return coset.individualize_first_nonsingleton(eldag);
}
/** Decides if a coset is a leaf.
*/
bool is_leaf(const Eldag& eldag, const Coset& coset)
{
return coset.is_leaf(eldag);
}
/** Gets a permutation from a coset.
*/
Perm get_a_perm(const Coset& coset) { return coset.get_a_perm(); }
/** Acts a permutation on an Eldag.
*/
Eldag act(const Perm& perm, const Eldag& eldag)
{
return act_eldag(perm, eldag);
}
/** Left multiplies an automorphism onto a coset.
*/
Coset left_mult(const Simple_perm& perm, const Coset& coset)
{
return { coset, perm };
}
/** Creates a transversal system for automorphisms.
*/
auto create_transv(const Coset& upper, const Coset& lower)
{
assert(upper.size() == lower.size());
return std::make_unique<Sims_transv<P>>(
lower.individualized(), upper.size());
}
};
/** Canonicalizes the given Eldag.
*
* Similar to the case of string canonicalization, here the permutation bring
* the Eldag into canonical form is returned. But the automorphism group
* returned is with respect to the original graph rather than the canonical
* form.
*/
template <typename P, typename F>
std::pair<Eldag_perm<P>, std::unique_ptr<Sims_transv<P>>> canon_eldag(
const Eldag& eldag, const Node_symms<P>& symms, F init_colour)
{
Partition init_part(eldag.size());
init_part.split_by_key(0, init_colour);
Eldag_refiner<P> refiner{};
Eldag_coset<P> root_coset(eldag, init_part, symms);
using Container = std::unordered_map<Eldag, Eldag_perm<P>>;
Container container{};
auto aut = add_all_candidates(refiner, eldag, root_coset, container);
const auto& canon_form
= std::min_element(container.begin(), container.end(),
[](const auto& a, const auto& b) { return a.first < b.first; });
auto min_aut = min_transv(std::move(aut));
return { std::move(canon_form->second), std::move(min_aut) };
}
} // End namespace libcanon.
//
// Std namespace injection for default hashing.
//
namespace std {
/** Hasher for Eldag.
*/
template <> struct hash<libcanon::Eldag> {
size_t operator()(const libcanon::Eldag& eldag) const
{
return eldag.hash();
}
};
/** Hash for Eldag coset.
*/
template <typename P> struct hash<libcanon::Eldag_coset<P>> {
size_t operator()(const libcanon::Eldag_coset<P>& coset) const
{
return coset.hash();
}
};
} // End namespace std
#endif // LIBCANON_ELDAG_H
| true |
7d154998f07095fd1f467eaa0ec4a087177878ea | C++ | tomaszkrysiuk/szkolenieWroclaw | /buyablesquare.cpp | UTF-8 | 684 | 2.6875 | 3 | [] | no_license | #include "buyablesquare.h"
void BuyableSquare::onEnter(Player& enteringPlayer)
{
if(owner)
chargeFee(enteringPlayer);
else
proposePurchase(enteringPlayer);
}
void BuyableSquare::chargeFee(Player& playerToCharge)
{
auto fee = getFee();
if(owner)//todo
(*owner)->giveMoney(playerToCharge.takeMoney(fee));
}
void BuyableSquare::proposePurchase(Player& enteringPlayer)
{
if(enteringPlayer.proposePurchase(this))
owner = std::experimental::make_optional(&enteringPlayer);
}
void BuyableSquare::iOwnYou(Player& newOwner)
{
owner = &newOwner;
}
void BuyableSquare::free()
{
owner = std::experimental::optional<Player*>();
}
| true |
c4bdfcaf5be8e883514c2064626b6f7c4aa8edc8 | C++ | attkke/FuckCATS | /subject-4/OPT.cpp | UTF-8 | 2,722 | 3.109375 | 3 | [] | no_license | // FILENAME: OPT.cpp
#include <iostream>
using namespace std;
int main() {
int memory[4] = {-1, -1, -1, -1};
int page[12] = {0, 6, 1, 5, 3, 7, 6, 7, 4, 3, 6, 1}; // the test pages
int count = 0; // missing page count
int replace[12]; // replace page record
int pr = 0; // pointer of replace
cout << "######OPT#######" << endl;
// search begin
for (int i = 0; i < 12; i++) {
// there are 3 memory pages in memory ,so if i<3,just put it in memory
if (i < 4) {
memory[i] = page[i];
count++;
} else {
// check if this page is in memory already
bool exist = false;
for (int j = 0; j < 4; j++) {
if (page[i] == memory[j]) {
exist = true;
break;
}
}
if (exist == false) {
//###############################
// begin to choose a memory page to replace
int later = 0;
bool ok[4];
for (int j = 0; j < 4; j++) ok[j] = false;
// check from i step -1 till 0
for (int j = i + 1; j < 12; j++) {
for (int k = 0; k < 4; k++) {
if (page[j] == memory[k]) {
ok[k] = true;
later++;
break;
}
}
if (later == 2) break;
}
// check which ok ==false
for (int j = 0; j < 4; j++) {
if (ok[j] == false) {
// replace this memory[j]
count++;
replace[pr] = memory[j];
pr++;
memory[j] = page[i];
break;
}
}
//#############################
}
}
// output
cout << page[i] << ": [ ";
for (int j = 0; j < 4; j++) {
if (memory[j] == -1)
cout << "* ";
else
cout << memory[j] << " ";
}
cout << "]" << endl;
}
cout << "######################" << endl;
cout << "the lack page count = " << count << endl;
cout << "repalce pages are : ";
for (int i = 0; i < pr; i++) {
cout << replace[i] << " ";
}
cout << endl;
cout << "the rate of page lack is " << count / 12.0 * 100 << "%" << endl;
return 0;
}
| true |
27ad147e0ed12ed969f7baae1f362726e7987e4c | C++ | Aya-ZIbra/Dijkstra | /Heap.h | UTF-8 | 1,943 | 3.40625 | 3 | [] | no_license |
/**
* A simple Heap class.
*
* @author
* Aya Zaki Ibrahim <aya.zaki.2012@gmail.com>
*/
/* supported operation
- extractMin
- removeMin
- insert(key)
- delete(key)
- decreaseKey(key)
*/
#ifndef HEAP_H
#define HEAP_H
#include <vector>
template <typename T>
class Heap{ // no brackets after class name
public:
// if no constructor is present, we have an automatic default constructor
// automatic default constructor initializes all member variables to their default values.
Heap(); // custom default constructor: default = takes no arguments / custom = overrides default
Heap(std::vector<T>& items); // custom non-default constructor
T extractMin();
void removeMin();
void buildHeap();
void insert(T);
std::ostream& print(std::ostream&);
private:
// Naming convention of private members
// variables use _ after their name
// functions use _ befor their name
int capacity_;
std::vector<T> container_;
int _getLastIdx();
void _heapifyUp(int);
void _heapifyDn(int);
void _swap(int, int);
bool _isLeaf(const int);
int _getLeftChildIdx(const int idx);
int _getRightChildIdx(const int idx);
static int _getParentIdx(const int idx){
/* 1 : 2, 3
2: 4, 5
3: 6, 7
parent = idx/2
zero indexed : (idx+1)/2 -1 = (idx-1)/2
*/
return (idx-1)/2;
}
}; // notice the ; after class definition
//template <typename T>
//std::ostream& operator<<(std::ostream&, const Heap<T>&);
// for template class, declarations are not enough.
// Function implementations need to be included
// the implementations will be compiled within the client cpp file. No compilation is done to the hpp files.
#include "Heap.hpp"
#endif | true |
215a6633727dd09991dd2c16f691a0f516a6188e | C++ | PeachChen/test | /public/libutil/MyStream.h | GB18030 | 9,258 | 2.953125 | 3 | [] | no_license | //ݲ
#pragma once
#include "DefineHeader.h"
enum
{
STREAM_MAX_STRING_LEN=1024*1024*10,
STREAM_MAX_VECTOR_LEN=1024*1024*10,
STREAM_MAX_MAP_LEN=1024*1024*10,
};
enum EStreamError
{
EStreamError_Error,
EStreamError_OK,
EStreamError_BufferFull,
EStreamError_BadArg,
};
//ݽӿ
class BaseStream
{
public:
uint8 m_StreamError; //
BaseStream() :m_StreamError(EStreamError_OK){};
virtual ~BaseStream(){};
EStreamError GetError() const { return (EStreamError)m_StreamError; }
bool IsOK() const { return (m_StreamError == EStreamError_OK); }
//л
virtual BaseStream& BytesSerialize(const void* data, size_t size) = 0;
//л
virtual BaseStream& BytesDeserialize(void* data, size_t size) = 0;
//ʼַ
//virtual uint8* GetBuffer() = 0;
//ƫ
virtual size_t GetOffset() = 0;
//ܴС
virtual size_t GetSize() = 0;
//дС
virtual size_t GetSpace() { return GetSize() - GetOffset(); }
#define BASESTREAM_SERIALIZE(valueType) \
BaseStream& operator << (valueType value) \
{\
return BytesSerialize(&value, sizeof(valueType)); \
}\
BaseStream& operator >> (valueType& value) \
{\
return BytesDeserialize(&value, sizeof(valueType));\
}
BASESTREAM_SERIALIZE(int);
BASESTREAM_SERIALIZE(uint);
BASESTREAM_SERIALIZE(int8);
BASESTREAM_SERIALIZE(uint8);
BASESTREAM_SERIALIZE(int16);
BASESTREAM_SERIALIZE(uint16);
BASESTREAM_SERIALIZE(int64);
BASESTREAM_SERIALIZE(uint64);
BASESTREAM_SERIALIZE(float);
BASESTREAM_SERIALIZE(double);
BaseStream& operator << (bool value)
{
uint8 i = (value ? 1 : 0);
return BytesDeserialize(&i, sizeof(uint8));
}
BaseStream& operator >> (bool& value)
{
uint8 i = 0;
BytesDeserialize(&i, sizeof(uint8));
value = (i == 1);
return *this;
}
BaseStream& operator << (const char* str)
{
if (str == NULL)
{
m_StreamError = EStreamError_BadArg;
return *this;
}
uint size = (uint)strlen(str);
if (size > STREAM_MAX_MAP_LEN)
{
m_StreamError = EStreamError_BadArg;
return *this;
}
BytesSerialize(&size, sizeof(uint));
return BytesSerialize(str, size);
}
BaseStream& operator << (const string& str)
{
uint size = (uint)str.length();//64λ32λһ
if (size > STREAM_MAX_STRING_LEN)
{
m_StreamError = EStreamError_BadArg;
Assert(false);
return *this;
}
BytesSerialize(&size, sizeof(uint));
return BytesSerialize(str.c_str(), size);
}
BaseStream& operator >> (string& str)
{
uint size = 0;
BytesDeserialize(&size, sizeof(uint));
str.clear();
if (size > 0)
{
if (size > STREAM_MAX_STRING_LEN)
{
m_StreamError = EStreamError_BadArg;
Assert(false);
return *this;
}
str.insert(0, size, 0);
return BytesDeserialize(&(str[0]), size);
}
return *this;
}
//for Lua script system
int8 ReadInt8()
{
int8 v = 0;
BytesDeserialize(&v, sizeof(int8));
return v;
}
void WriteInt8(int8 v)
{
BytesSerialize(&v, sizeof(int8));
}
uint8 ReadUint8()
{
uint8 v = 0;
BytesDeserialize(&v, sizeof(uint8));
return v;
}
void WriteUint8(uint8 v)
{
BytesSerialize(&v, sizeof(uint8));
}
int ReadInt()
{
int v = 0;
BytesDeserialize(&v, sizeof(int));
return v;
}
void WriteInt(int v)
{
BytesSerialize(&v, sizeof(int));
}
std::string ReadStr()
{
uint size = 0;
BytesDeserialize(&size, sizeof(uint));
std::string str;
str.clear();
if (size > 0)
{
str.insert(0, size, 0);
BytesDeserialize(&str[0], size);
}
return str;
}
};
//ȫģ ͨ͵л
//ҪͨԼʵSerializeDeserialize
template<typename T>
inline BaseStream& operator<<(BaseStream& os, const T& data)
{
data.Serialize(os);
return os;
}
template<typename T>
inline BaseStream& operator>>(BaseStream& is, T& data)
{
data.Deserialize(is);
return is;
}
//vector л
template<typename T>
inline BaseStream& operator<<(BaseStream& os, const std::vector<T>& data)
{
uint size = (uint)data.size();
if (size > STREAM_MAX_VECTOR_LEN)
{
os.m_StreamError = EStreamError_BadArg;
return os;
}
os << size;
for (uint i = 0; i < size; ++i)
{
os << data[i];
}
return os;
}
template<typename T>
inline BaseStream& operator>>(BaseStream& is, std::vector<T>& data)
{
uint size =0;
is >> size;
if (size > STREAM_MAX_VECTOR_LEN)
{
is.m_StreamError = EStreamError_BadArg;
return is;
}
data.resize((size_t)size);
for (uint i = 0; i < size; ++i)
{
is >> data[i];
}
return is;
}
//̶
class Stream :public BaseStream
{
protected:
bool m_IsNew;
uint8* m_Buffer; //ʼַ
uint8* m_Pointer;//ǰַ
size_t m_Size; //ܴС
public:
//ⲿݳʼ
Stream(uint8* pBuffer, size_t size);
//ڲ̶size
Stream(size_t size);
virtual ~Stream(){ ReleaseBuffer(); }
bool IsOk() const { return (m_StreamError == EStreamError_OK); }
//ͷڴ
void ReleaseBuffer();
//ƫ
virtual size_t GetOffset() { return (size_t)(m_Pointer - m_Buffer); }
//ܴС
virtual size_t GetSize() { return m_Size; }
//ָӿ
uint8* GetBuffer() { return m_Buffer; }
uint8* GetOffsetPointer(){ return m_Pointer; }
void ResetPointer(){ m_Pointer = m_Buffer; }
void SetPointer(size_t size);
//д
bool SetData(size_t pos, const void* data, size_t size)
{
if (pos + size > m_Size)
{
assert(false);
m_StreamError = EStreamError_BufferFull;
return false;
}
memcpy(&(m_Buffer[pos]), data, size);
return true;
}
//ƫǰ
bool Ignore(size_t size)
{
if (GetSpace() < size)
{
assert(false);
m_StreamError = EStreamError_BufferFull;
return false;
}
m_Pointer += size;
return true;
}
//л
virtual BaseStream& BytesSerialize(const void* data, size_t size)
{
if (GetSpace() < size)
{
assert(false);
m_StreamError = EStreamError_BufferFull;
return *this;
}
memcpy(m_Pointer, data, size);
m_Pointer += size;
return *this;
}
//л
virtual BaseStream& BytesDeserialize(void* data, size_t size)
{
if (GetSpace() < size)
{
m_StreamError = EStreamError_BufferFull;
return *this;
}
memcpy(data, m_Pointer, size);
m_Pointer += size;
return *this;
}
//лԼ
virtual void Serialize(BaseStream& streamTo)
{
if (this == &streamTo)
{
return;
}
streamTo.BytesSerialize(GetBuffer(), GetOffset());
}
virtual void Deserialize(BaseStream& streamFrom)
{
if (this == &streamFrom)
{
return;
}
size_t len = streamFrom.GetOffset();
streamFrom.BytesDeserialize(GetBuffer(), len);
SetPointer(len);
}
};
//̶С
template<uint BufferSize>
class BufferStream :public Stream
{
protected:
uint8 m_MemBuffer[BufferSize];
public:
BufferStream() :Stream(m_MemBuffer, BufferSize)
{
memset(m_MemBuffer, 0, sizeof(m_MemBuffer));
}
};
//̬С
class StringStream :public BaseStream
{
protected:
vector<int8> m_Buffer;
size_t m_Offset;
public:
StringStream() { m_Offset = 0; }
virtual ~StringStream() {}
virtual size_t GetOffset(){ return m_Offset; }
virtual size_t GetSize() { return m_Buffer.size(); }
vector<int8>& GetBuffer() { return m_Buffer; }
const vector<int8>& GetBuffer() const { return m_Buffer; }
void ResetOffset() { m_Offset = 0; }
void Clean()
{
ResetOffset();
m_Buffer.clear();
}
//м
bool SetData(size_t pos, const void* data, size_t size)
{
m_Buffer.resize(m_Offset + size);
memcpy(&(m_Buffer[pos]), data, size);
return true;
}
void swap(StringStream& rs)
{
m_Buffer.swap(rs.m_Buffer);
std::swap(m_Offset, rs.m_Offset);
}
//л
virtual BaseStream& BytesSerialize(const void* data, size_t size)
{
if (data == NULL)
{
m_StreamError = EStreamError_BadArg;
return *this;
}
if (size)
{
m_Buffer.resize(m_Offset + size);
memcpy(&(m_Buffer[m_Offset]), data, size);
m_Offset += size;
}
return *this;
}
virtual BaseStream& BytesDeserialize(void* data, size_t size)
{
if (data == NULL)
{
m_StreamError = EStreamError_BadArg;
return *this;
}
if (m_Offset + size > m_Buffer.size())
{
m_StreamError = EStreamError_BufferFull;
return *this;
}
memcpy(data, &(m_Buffer[m_Offset]), size);
m_Offset += size;
return *this;
}
//лԼ
virtual void Serialize(BaseStream& streamTo)
{
if (this == &streamTo)
{
assert(false);
return;
}
streamTo << (int)GetOffset();
streamTo.BytesSerialize(&GetBuffer()[0], GetOffset());
}
virtual void Deserialize(BaseStream& streamFrom)
{
if (this == &streamFrom)
{
m_StreamError = EStreamError_BadArg;
return;
}
int dataSize = 0;
streamFrom >> dataSize;
m_Buffer.resize(dataSize);
streamFrom.BytesDeserialize(&GetBuffer()[0], dataSize);
}
};
| true |
e18cbc630434a91791542ad8ca5ef8030f7bd5ff | C++ | m43/fer-ooup | /lab3/ex1-3/myfactory.h | UTF-8 | 1,613 | 3.125 | 3 | [] | no_license | //
// Created by m43 on 18. 05. 2020..
//
#ifndef FER_OOUP_MYFACTORY_H
#define FER_OOUP_MYFACTORY_H
#include <map>
#include <memory>
using namespace std;
template<typename PRODUCT>
class MyFactory {
public:
typedef PRODUCT *(*CREATORFUN)(const string &);
static MyFactory<PRODUCT> &instance();
int registerCreator(const string &name, CREATORFUN creatorFunction);
const map<string, CREATORFUN> &getCreators();
CREATORFUN getCreator(const string &name);
private:
MyFactory() = default;;
~MyFactory() = default;
map<std::string, CREATORFUN> creatorsMap_;
};
// NOTE: decl and def are in one file cause:
// https://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file
// https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
template<typename PRODUCT>
MyFactory<PRODUCT> &MyFactory<PRODUCT>::instance() {
static MyFactory instance_;
return instance_;
}
template<typename PRODUCT>
int MyFactory<PRODUCT>::registerCreator(const string &name, MyFactory::CREATORFUN creatorFunction) {
creatorsMap_[name] = creatorFunction;
return creatorsMap_.size() - 1;
}
template<typename PRODUCT>
const map<string, typename MyFactory<PRODUCT>::CREATORFUN> &MyFactory<PRODUCT>::getCreators() {
return creatorsMap_;
}
template<typename PRODUCT>
typename MyFactory<PRODUCT>::CREATORFUN MyFactory<PRODUCT>::getCreator(const string &name) {
auto creator = creatorsMap_.find(name);
if (creator == creatorsMap_.end()) {
return nullptr;
}
return creator->second;
}
#endif //FER_OOUP_MYFACTORY_H
| true |
73310cce16aff975853ef18e261608f0b3dcfe17 | C++ | akuzdeuov/kangaroo_x2_sabertooth32 | /include/motorControl.h | UTF-8 | 1,442 | 2.859375 | 3 | [] | no_license | //
// Created by askat on 1/6/20.
//
#ifndef MOTORCONTROL_MOTORCONTROL_H
#define MOTORCONTROL_MOTORCONTROL_H
#include <iostream>
#include <utility>
// C library headers
#include <string.h>
// Linux headers
#include <fcntl.h> // Contains file controls like O_RDWR
#include <termios.h> // Contains POSIX terminal control definitions
#include <unistd.h> // write(), read(), close()
class Kangaroo{
public:
// constructors
Kangaroo() = default;
Kangaroo(std::string &pn, speed_t &br){
portName = pn;
baudRate = br;
}
// open the serial port
void openSerialPort();
// configure the serial port
void configureSerialPort();
// close the serial port
void closeSerialPort();
// start motors
void startMotor(char &motorID);
// get motor position
std::pair<int, bool> getPosition(char &motorID);
// get motor speed
std::pair<int, bool> getSpeed(char &motorID);
// set a reference position
void setPosition(char &motorID, int &pos);
// set a reference position and speed
void setPositionSpeed(char &motorID, int &pos, int &speed);
// home position
void homePosition(char &motorID);
private:
std::string portName = "/dev/ttyUSB0";
speed_t baudRate = B19200;
int fd = 0; // // file description for the serial port
useconds_t readTime = 25000; // time to read position (microsecond)
};
#endif //MOTORCONTROL_MOTORCONTROL_H
| true |
4b69ae59d313f7dac7ba9743a530776436ea0577 | C++ | danlipsa/foamvis | /AverageCacheT1KDEVelocity.h | UTF-8 | 952 | 2.75 | 3 | [] | no_license | /**
* @file AverageCacheT1KDEVelocity.h
* @author Dan R. Lipsa
* @date 10 March 2011
* @ingroup model
* @brief Cache of 2D averages for T1KDE and velocity.
*/
#ifndef __AVERAGE_CACHE_T1KDE_VELOCITY_H__
#define __AVERAGE_CACHE_T1KDE_VELOCITY_H__
/**
* @brief Cache of 2D averages for T1KDE and velocity.
*/
class AverageCacheT1KDEVelocity
{
public:
void SetT1KDE (vtkSmartPointer<vtkImageData> average)
{
m_t1KDE = average;
}
vtkSmartPointer<vtkImageData> GetT1KDE () const
{
return m_t1KDE;
}
void SetVelocity (vtkSmartPointer<vtkImageData> average)
{
m_velocityAverage = average;
}
vtkSmartPointer<vtkImageData> GetVelocity () const
{
return m_velocityAverage;
}
private:
vtkSmartPointer<vtkImageData> m_t1KDE;
vtkSmartPointer<vtkImageData> m_velocityAverage;
};
#endif //__AVERAGE_CACHE_T1KDE_VELOCITY_H__
// Local Variables:
// mode: c++
// End:
| true |
904162db3b5d16ba335e2b04d1487bb274616368 | C++ | NUC-NCE/algorithm-codes | /codes - ac/Gym/101653W/19564434_AC_15ms_236kB.cpp | UTF-8 | 1,555 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e7 + 5;
const int maxn = 2e5 + 5;
const int inf = 2e9;
int T;
int p, w, q;//点数,虫洞数,询问数
double a[100][100];
map<string, int>mp;
struct Node {
double x, y, z;
}point[100];
double dist(double x1, double y1, double z1, double x2, double y2, double z2) {
return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2));
}
void floyed() {
for (int k = 1; k <= p; k++) {
for (int i = 1; i <= p; i++) {
for (int j = 1; j <= p; j++) {
if (a[i][j] > a[i][k] + a[k][j])
a[i][j] = a[i][k] + a[k][j];
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin >> T;
for(int cas=1;cas<=T;cas++) {
memset(a,0,sizeof(a));
cin >> p;
for (int i = 1; i <= p; i++) {
string t;
double x, y, z;
cin >> t >> x >> y >> z;
mp[t] = i;
point[i].x = x; point[i].y = y; point[i].z = z;
}
for (int i = 1; i <= p; i++) {
Node tem1 = point[i];
for (int j = 1; j <= p; j++) {
if (i == j)continue;
Node tem2 = point[j];
a[i][j] = dist(tem1.x, tem1.y, tem1.z, tem2.x, tem2.y, tem2.z);
}
}
cin >> w;
for (int i = 1; i <= w; i++) {
string t, s;
cin >> t >> s;
a[mp[t]][mp[s]] = 0;
}
floyed();
cin >> q;
cout<<"Case "<<cas<<":"<<endl;
for(int i=1;i<=q;i++){
string t, s;
cin >> t >> s;
cout<<"The distance from "<<t<<" to "<<s<<" is "<< (int)(a[mp[t]][mp[s]]+0.5)<<" parsecs." << endl;
}
}
return 0;
}
/*
3
4
e 0 0 0
p 5 0 0
b 5 5 0
s 0 5 0
2
e b
b s
6
e b
b s
*/ | true |
586e2977ed3c251494c24e20d2ddb161e29cbcfc | C++ | bmstu-ics7/computer-graphics | /lab_07/mymath.cpp | UTF-8 | 378 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "mymath.h"
int absx(int x)
{
return x >= 0 ? x : -x;
}
double absx(double x)
{
return x >= 0 ? x : -x;
}
int myRound(double x)
{
return int(x + 0.5 * (x / x));
}
int signx(double x)
{
return x == 0.0 ? 0 : x > 1 ? 1 : -1;
}
int signx(int x)
{
return x == 0 ? 0 : x > 1 ? 1 : -1;
}
int negative(int cx, int x)
{
return cx - absx(cx - x);
}
| true |
5e8cf6b43db3669af58e1154151df8e6002dc224 | C++ | Yangmila/c_code | /4/4-10-11.cpp | UTF-8 | 184 | 2.828125 | 3 | [] | no_license | #include <iostream.h>
int a[8]={1,3,5,7,9,11,13};
void fun(int b[],int n)
{
for(int i=0;i<n-1;i++)
b[7]+=b[i];
}
void main()
{
int m=8;
fun(a,m);
cout<<a[7]<<endl;
}
| true |
18742e25209c7fa3d831451c8c4f9ec360100b0a | C++ | protim2001/LeetCode | /power-of-two/power-of-two.cpp | UTF-8 | 895 | 3.375 | 3 | [] | no_license | class Solution {
public:
bool isPowerOfTwo(int n)
{
//1. doing AND: O(1)
/* if(n <= 0)
return false;
return n && (!(n & n - 1)); */
//2. taking log: log2(n)
/*if(n <= 0)
return false;
return floor(log2(n)) == ceil(log2(n)); */
//3. count set bits : O(number of set bits)
/*if(n <= 0)
return false;
int count = 0;
while(n)
{
n &= n - 1;
count++;
}
if(count == 1)
return true;
return false; */
//4. using while loop : O(log2n)
if(n <= 0)
return false;
while(n != 1)
{
if(n % 2 != 0)
return false;
n /= 2;
}
return true;
}
}; | true |
74ac70a85dda14bf8194ab40071e162b62f76083 | C++ | BackhausL/cgv | /libs/vr/vr_kit.cxx | UTF-8 | 941 | 2.671875 | 3 | [] | permissive | #include "vr_kit.h"
namespace vr {
/// construct
vr_kit::vr_kit(vr_driver* _driver, void* _handle, const std::string& _name, bool _ffb_support, bool _wireless) :
driver(_driver), device_handle(_handle), name(_name), force_feedback_support(_ffb_support), wireless(_wireless) {}
/// declare virtual destructor
vr_kit::~vr_kit()
{
}
/// return driver
const vr_driver* vr_kit::get_driver() const { return driver; }
/// return device handle
void* vr_kit::get_device_handle() const { return device_handle; }
/// return name of vr_kit
const std::string& vr_kit::get_name() const { return name; }
/// return last error of vr_kit
const std::string& vr_kit::get_last_error() const { return last_error; }
/// return whether vr_kit is wireless
bool vr_kit::is_wireless() const { return wireless; }
/// return whether controllers support force feedback
bool vr_kit::has_force_feedback() const { return force_feedback_support; }
}
| true |
cd8402bb15547ac5561e86ad7241b5400c254d3d | C++ | troytoman/Project4 | /StockServer/stock.cpp | UTF-8 | 2,766 | 3.15625 | 3 | [] | no_license | /*
* stock.cpp
* StockServer
*
* Created by Troy Toman on 4/17/10.
* Copyright 2010 Troy Toman. All rights reserved.
*
*/
#include "stock.h"
void Stock::createlisting (string ssymbol, float sprice, string coname) {
stocksymbol = ssymbol;
price = sprice;
companyname = coname;
}
void Stock::updatePrice () {
float r = (float)rand()/(float)RAND_MAX;
// if (stocksymbol == "AAPL")
// cout << stocksymbol << ": " << price << endl;
if((rand() % 2) && price > 1.0) {
price = price - (price*r/10000.0);
} else {
price = price + (price*r/10000.0);
}
// if (stocksymbol == "AAPL")
// cout << stocksymbol << ": " << price << endl;
}
// Stock constructor allocates the stock and starts a thread to update the price
StockHolding::StockHolding () {
shares = 0;
s = sm.getStock("NULL");
};
// Change the amount of shares in the Stock by numshares. If there are not enough
// shares to sell that many, return.
int StockHolding::Sell (int numshares) {
if (numshares > shares) {
return(0);
}
else {
shares -= numshares;
return(numshares);
}
};
// Change the amount of shares in the Stock by numshares. If there are not enough
// shares to sell that many, return -1.
int StockHolding::Buy (int numshares) {
shares += numshares;
return shares;
};
int StockHolding::setStock(string stocksymbol) {
s = sm.getStock(stocksymbol);
if (s==0) {
return 0;
} else {
return 1;
}
};
string Stock:: view() {
stringstream retstr;
retstr << "Stock: " << companyname << "( " << stocksymbol << " ) Price: " << price;
return retstr.str();
}
string StockHolding::view() {
stringstream retstr;
retstr << s->view() << " Shares: " << shares;
return retstr.str();
}
void StockMarket::gopricing(){ //Handles price changes
//Walks through the stocklist and adjusts the price up or down by a randomly generated percentage
while (1) {
for (int i=0; i<NUMSTOCKS; i++) {
stocklist[i].updatePrice();
}
}
};
StockMarket::StockMarket(){ //Starts up the StockMarket and initiates the pricing thread
ifstream stockfile ("stocks.txt");
string ssym, coname;
float openprice;
if (stockfile.is_open()) {
//Read the stock list and get the initial prices
for (int i=0; i<NUMSTOCKS; i++) {
stockfile >> ssym;
stockfile >> openprice;
stockfile >> coname;
stocklist[i].createlisting(ssym, openprice, coname);
cout << "Created company name: " << coname << endl;
}
} else {
cout << "stockfile not found\n";
}
stocklist[NUMSTOCKS].createlisting("NULL", 0, "NULL");
stockfile.close();
};
Stock * StockMarket::getStock(string stsym) { //Provides a pointer to the stock object
for (int i=0; i<=NUMSTOCKS; i++) {
if (stsym == stocklist[i].getsymbol()) {
return &stocklist[i];
}
}
return 0;
}
| true |
19fddaa94973a12b4bb7eccad6ad99cc35bf4fab | C++ | amikai/flv2ts | /src/bin/parse-flv.cc | UTF-8 | 3,479 | 2.546875 | 3 | [] | no_license | #include <flv/parser.hh>
#include <iostream>
#include <inttypes.h>
int main(int argc, char** argv) {
if(argc != 2) {
std::cerr << "Usage: parse-flv FLV_FILE" << std::endl;
return 1;
}
const char* filepath = argv[1];
flv2ts::flv::Parser parser(filepath);
if(! parser) {
std::cerr << "Can't open file: " << filepath << std::endl;
}
std::cout << "[file]" << std::endl
<< " path: " << filepath << std::endl
<< std::endl;
flv2ts::flv::Header header;
if(! parser.parseHeader(header)) {
std::cerr << "parse flv header failed" << std::endl;
return 1;
}
// header
std::cout << "[header]" << std::endl
<< " signature: " << header.signature[0] << header.signature[1] << header.signature[2] << std::endl
<< " version: " << (int)header.version << std::endl
<< " is_audio: " << (header.is_audio ? "true" : "false") << std::endl
<< " is_video: " << (header.is_video ? "true" : "false") << std::endl
<< " data_offset: " << header.data_offset << std::endl
<< std::endl;
parser.abs_seek(header.data_offset);
// body
for(int i=0;; i++) {
size_t offset = parser.position();
flv2ts::flv::Tag tag;
uint32_t prev_tag_size;
if(! parser.parseTag(tag, prev_tag_size)) {
std::cerr << "parse flv tag failed" << std::endl;
return 1;
}
if(parser.eos()) {
break;
}
std::cout << "[tag:" << i << ":" << offset << "]" << std::endl
<< " filter: " << (tag.filter ? "true" : "false") << std::endl
<< " type: " << (int)tag.type << std::endl
<< " data_size: " << tag.data_size << std::endl
<< " timestamp: " << tag.timestamp << std::endl
<< " stream_id: " << tag.stream_id << std::endl;
switch(tag.type) {
case flv2ts::flv::Tag::TYPE_SCRIPT_DATA: {
std::cout << " [script_data]" << std::endl
<< " payload_size: " << tag.script_data.payload_size << std::endl;
break;
}
case flv2ts::flv::Tag::TYPE_AUDIO: {
std::cout << " [audio]" << std::endl
<< " sound_format: " << (int)tag.audio.sound_format << std::endl
<< " sound_rate: " << (int)tag.audio.sound_rate << std::endl
<< " sound_size: " << (int)tag.audio.sound_size << std::endl
<< " sound_type: " << (int)tag.audio.sound_type << std::endl;
if(tag.audio.sound_format == 10) {
std::cout << " aac_packet_type: " << (int)tag.audio.aac_packet_type << std::endl;
}
std::cout << " payload_size: " << tag.audio.payload_size << std::endl;
break;
}
case flv2ts::flv::Tag::TYPE_VIDEO: {
std::cout << " [video]" << std::endl
<< " frame_type: " << (int)tag.video.frame_type << std::endl
<< " codec_id: " << (int)tag.video.codec_id << std::endl;
if(tag.video.codec_id == 7) {
std::cout << " avc_packet_type: " << (int)tag.video.avc_packet_type << std::endl
<< " composition_time: " << (int)tag.video.composition_time << std::endl;
}
std::cout << " payload_size: " << tag.video.payload_size << std::endl;
break;
}
default:
std::cerr << "unknown tag type: " << (int)tag.type << std::endl;
return 1;
}
std::cout << std::endl;
}
return 0;
}
| true |
d43b483367eb8b8ae0e921429ff43500ce843055 | C++ | flourpower/cpp | /rev/rev.cpp | UTF-8 | 1,202 | 3.6875 | 4 | [] | no_license | //reverse the words in an input string
#include <iostream>
#include <vector>
using namespace std;
void tokenize(const string& str,
vector<string>& tokens,
const string& delimiters = " \t")
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
void rev(string str){
//reverse the words in this string
int j;
vector<string> words;
tokenize(str, words, " \t");
for(vector<string>::iterator i = words.begin(); i != words.end(); i++){
for(j = (i->size()) - 1; j >= 0; j--){
cout << (*i)[j];
}
cout << " ";
}
}
int main(int argc, char** argv){
rev("my name is fred");
cout << endl;
}
| true |
076234d23fa0a561af0e3436ae7bdbf2d262c21b | C++ | Karlodun/c- | /Milestone 1/Spiel_des_Lebens_GUI/raptors.cpp | UTF-8 | 2,280 | 3.046875 | 3 | [] | no_license | #include "raptors.h"
#include "Raptors.h"
Raptors::Raptors()
{
Locations = new int [Population];
Age = new int [Population];
}
Raptors::~Raptors()
{
delete [] Locations;
delete [] Age;
}
int Raptors::Grow(int newID){
// create and fill BackPack:
BackPack = new int [Population];
for (int i=0; i<Population; i++) BackPack[i]=Locations[i];
// increase population, fix Locations length and copy BackPack back
Population++;
Locations = new int [Population];
for (int i=0; i<Population; i++) Locations[i]=BackPack[i];
// add new animal to locations:
Locations[Population]=newID;
// procede with Age
for (int i=0; i<Population; i++) BackPack[i]=Age[i];
Age = new int [Population];
for (int i=0; i<Population; i++) Age[i]=BackPack[i];
Age[Population]=0;
delete [] BackPack;
return newID;
}
int Raptors::Decay(int deadID){
Population--;
BackPack = new int [Population];
// drop id of dead animal
// copy all values before dead animal
for (int i=0; i<deadID; i++) BackPack[i]=Locations[i];
// copy all values after dead animal
for (int i=deadID; i<=Population; i++) BackPack[i]=Locations[i+1];
// recreate and fill Locations
Locations = new int [Population];
for (int i=0; i<=Population; i++) Locations[i]=BackPack[i];
// procede with Age
for (int i=0; i<deadID; i++) BackPack[i]=Age[i];
// copy all values after dead animal
for (int i=deadID; i<=Population; i++) BackPack[i]=Age[i+1];
// recreate and fill Locations
Age = new int [Population];
for (int i=0; i<=Population; i++) Age[i]=BackPack[i];
delete [] BackPack;
return deadID;
}
int Raptors::Move(int herdID, int newID, int newIDType){
/* randomization could be realized with a herdIds shuffle
* like:
* random_shuffle(std::begin(herdIDs), std::end(herdIDs));
* neither the necessary variables, nor functionality is implemented here
* since there is just no need
*/
if (newIDType==1) Age[herdID]=0;//we had some food, reset age
else Age[herdID]++; // we had no food, thus olden
if (Age[herdID]>maxAge) return 0; // we tell the caller, that cell has reached end of life
else Locations[herdID] = newID;
return 1;
}
| true |
0f7150238ac741733af85aeb20fc41db7ae0816b | C++ | platinum78/cs_learning | /04_Programming Exercise/SWExpertAcademy/7853/7853.cpp | UTF-8 | 1,069 | 2.9375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#define DIV 1000000007
char strBuf[1001];
long tripleCmp(long n1, long n2, long n3)
{
if (n1 == n2)
{
if (n2 == n3)
return 1;
else
return 2;
}
else
{
if (n2 == n3)
return 2;
else if (n1 == n3)
return 2;
else
return 3;
}
}
long charReplacable(int len)
{
long totalCase = 1;
if (strBuf[0] != strBuf[1])
totalCase *= 2;
// else
// ++totalCase;
for (int i = 1; i < len - 1; i++)
totalCase = totalCase * tripleCmp(strBuf[i - 1], strBuf[i], strBuf[i + 1]) % DIV;
if (strBuf[len - 2] != strBuf[len - 1])
totalCase *= 2;
// else
// ++totalCase;
return totalCase % DIV;
}
int main(void)
{
freopen("input.txt", "r", stdin);
int tcCnt;
scanf("%d", &tcCnt);
for (int tc = 1; tc <= tcCnt; tc++)
{
scanf("%s", strBuf);
printf("#%d %ld \n", tc, charReplacable(strlen(strBuf)));
}
return 0;
}
| true |
970cd139ea2e575e3279187965de7974cc0951f4 | C++ | venkat78/agrid | /surface_mesh/hole_filler.hpp | UTF-8 | 3,045 | 2.765625 | 3 | [] | no_license | /*
* hole_filler.hpp
*
* Created on: Nov 28, 2011
*/
#ifndef _SURFACE_MESH_HOLE_FILLER_HPP_
#define _SURFACE_MESH_HOLE_FILLER_HPP_
#include <queue>
using namespace std;
#include "surface_mesh_class.hpp"
class cHOLE_VERTEX_RECORD {
public:
cHOLE_VERTEX_RECORD();
VOID VertexIndex(cSURFACE_MESH::cVERTEX* vertex) {VertexIndex(vertex->Index());}
VOID VertexIndex(iVERTEX vertexIndex) {m_vertex_index = vertexIndex;}
VOID IncomingHE(cSURFACE_MESH::cHALF_EDGE* inHE) {m_in_half_edge = inHE;}
VOID OutgoingHE(cSURFACE_MESH::cHALF_EDGE* outHE) {m_out_half_edge = outHE;}
cSURFACE_MESH::cHALF_EDGE *IncomingHE() {return m_in_half_edge;}
cSURFACE_MESH::cHALF_EDGE *OutgoingHE() {return m_out_half_edge;}
REAL ComputeAngleCosine(cSURFACE_MESH *m_mesh);
REAL AngleCosine() const {return m_angle_cosine;}
iVERTEX VertexIndex() const {return m_vertex_index;}
private: //fields
iVERTEX m_vertex_index;
cSURFACE_MESH::cHALF_EDGE *m_in_half_edge;
cSURFACE_MESH::cHALF_EDGE *m_out_half_edge;
REAL m_angle_cosine;
};
struct sHOLE_VERTEX_RECORD_CMP {
BOOL operator() ( const cHOLE_VERTEX_RECORD &hvr1, const cHOLE_VERTEX_RECORD &hvr2) {
if (fabs(hvr1.AngleCosine() - hvr2.AngleCosine()) <= cLIMITS::Epsilon())
return hvr1.VertexIndex() < hvr2.VertexIndex();
else
return hvr1.AngleCosine() < hvr2.AngleCosine();
}
};
class cHOLE_FILLER {
public:
cHOLE_FILLER(cSURFACE_MESH *mesh); //constructor
BOOL Perform();
private: //methods
BOOL CloseHole1();
BOOL FindCycle();
BOOL FillHole();
VOID CollectCycleVertices(iVERTEX terminalVtx,
BOOL checkTerminalVtx);
VOID PrepareVetexRecords();
cSURFACE_MESH::cHALF_EDGE*
RegisterVertexRecord(cSURFACE_MESH::cHALF_EDGE* currBorderHE);
INT FillAtSmallestAngleVertex();
INT FillAtVertexZeroTriangles(cHOLE_VERTEX_RECORD &vertexRecord);
INT FillAtVertexOneTriangle(cHOLE_VERTEX_RECORD &vertexRecord);
INT FillAtVertexTwoTriangles(cHOLE_VERTEX_RECORD &vertexRecord);
INT FillAtVertexThreeTriangles(cHOLE_VERTEX_RECORD &vertexRecord);
// std::list<cHOLE_VERTEX_RECORD>::iterator FindSmallestAngleVertexRecord();
private: //fields
cSURFACE_MESH *m_mesh;
std::vector<BOOL> m_vertexVisited;
std::vector<iVERTEX> m_cycleVertices;
std::stack<cSURFACE_MESH::cHALF_EDGE*> m_boundaryHalfEdges;
std::priority_queue<cHOLE_VERTEX_RECORD, std::vector<cHOLE_VERTEX_RECORD>, sHOLE_VERTEX_RECORD_CMP > m_vertex_records;
REAL m_cosine_0; //adjacent edges are merged
REAL m_cosine_1; //generates a single triangle
REAL m_cosine_2; //generates two triangles
REAL m_small_edge_length_squared; //size of a degenerate edge to be immediately removed
REAL m_comparable_edge_size_coeff;
REAL m_max_half_edge_squared_length;
REAL m_min_half_edge_squared_length;
iFACET m_first_hole_facet_index;
iVERTEX m_first_hole_vertex_index;
};
#endif // _SURFACE_MESH_HOLE_FILLER_HPP_
| true |
194c787d2b50bb744d10e0fcaf1d6b5dd7b74432 | C++ | Aarafat77VU/Data-Structure-Lab-Linked-List | /l.cpp | UTF-8 | 521 | 3.203125 | 3 | [] | no_license | #include<iostream>
#include<list>
using namespace std;
class Queue
{
list<int>mylist;
public:
void Push(int x)
{
mylist.push_back(x);
}
void Pop()
{
mylist.pop_front();
}
int Front()
{
cout<<mylist.front()<<endl;
}
int Back()
{
cout<< mylist.back()<<endl;
}
};
int main()
{
Queue q;
q.Push(1);
q.Push(2);
q.Push(2);
q.Push(4);
q.Front();
q.Pop();
q.Pop();
q.Front();
}
| true |
22436f642d2d56414b48bff272255531b860112c | C++ | yumdeer/daily_practice | /vs_project/extern/extern/extern.cpp | UTF-8 | 272 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
//fun.h
template <typename T>
void fun(T t) {
cout << t << endl;
}
//use1.cpp
void test1() {
fun<int>(1);
}
//use2.cpp
//extern template void fun<int>(int);
void test2() {
fun<int>(2);
}
int main()
{
test1();
test2();
} | true |
d3497eba634af586e32fe818db6f1fcd7f43b740 | C++ | WhiZTiM/coliru | /Archive2/ce/969fb443886ae9/main.cpp | UTF-8 | 388 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <type_traits>
struct A {
int m;
};
struct B {
int m1;
private:
int m2;
};
struct C {
virtual void foo();
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_standard_layout<A>::value << '\n';
std::cout << std::is_standard_layout<B>::value << '\n';
std::cout << std::is_standard_layout<C>::value << '\n';
} | true |
6e3f8ed7e6789b4e9e0bbad23691f5999c25ad9a | C++ | google/fully-homomorphic-encryption | /transpiler/examples/calculator/calculator_test.cc | UTF-8 | 1,265 | 3.0625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | // Copyright 2021 Google LLC
//
// 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 "calculator.h"
#include "gtest/gtest.h"
TEST(CalculatorTest, Sum) {
Calculator st;
int result = st.process(64, 45, '+');
EXPECT_EQ(result, 109);
}
TEST(CalculatorTest, SumNegativeValue) {
Calculator st;
int result = st.process(64, -45, '+');
EXPECT_EQ(result, 19);
}
TEST(CalculatorTest, SumTwoNegativeValues) {
Calculator st;
int result = st.process(-64, -45, '+');
EXPECT_EQ(result, -109);
}
TEST(CalculatorTest, Subtraction) {
Calculator st;
int result = st.process(64, 45, '-');
EXPECT_EQ(result, 19);
}
TEST(CalculatorTest, Multiplication) {
Calculator st;
int result = st.process(10, 20, '*');
EXPECT_EQ(result, 200);
}
| true |
16607cd7d9e74cfd95926e05463b56b5255806d4 | C++ | Josedm92/UD2 | /pipiiiii.cpp | UTF-8 | 1,179 | 3.828125 | 4 | [] | no_license | //Ejemplo 3.5.2 de la página 82 - Programa que calcula el valor de pi con una precisión establecida.
#include <iostream> //Incluimos librería iostream que permite la entrada por teclado y la salida por pantalla.
#include <cmath> //Incluimos librería cmath para poder usar la raíz cúbica (cbrt) y la potencia (pow).
#include <iomanip> //Incluimos librería iomanip para poder establecer la precisión en el cálculo de pi (setprecision).
using namespace std; //Sentencia obligatoria.
//Inicio del programa.
int main () {
//Declaración e inicialización de variables.
int precision;
long double sumandos=0.0;
long double valor=0.0;
//Pedimos por pantalla el numero de sumandos que se quieran para calcular pi.
cout << "Introduzca el número de sumandos con los que se desea calcular pi: ";
cin >> precision;
//Bucle que calcula el valor de pi.
for (int i=0; i<=precision; i++) {
sumandos+=pow(-1.0,i)/pow(((2.0*i)+1.0),3); //Cálculo con los sumandos actuales.
valor=cbrt(32.0*sumandos); //Cálculo de pi.
//Sacamos por pantalla el valor actual de pi.
cout << "Valor de PI aproximado (" << i << "): " << setprecision(precision) << valor << endl;
}
}
| true |
27994073e5c5624203ad5bc8eac2bb5a940b32a3 | C++ | Innand/ProjetInfo2 | /Complet_sauf_k-connexe/Version22/accueil.cpp | ISO-8859-1 | 2,342 | 2.828125 | 3 | [] | no_license | #include "accueil.h"
/***************************************************
THING (test)
Cette classe correspond au cadre en bas gauche
avec diffrents bidules interactifs assembls dessus
VOIR LE CONSTRUCTEUR ET LA METHODE UPDATE EN DETAIL
( dans test.cpp ) pour dcrypter l'utilisation
des widgets proposs ( vous pouvez en ajouter d'autres
en compltant widget.h et widget.cpp, rpertoire
de projet grman )
****************************************************/
/// Le constructeur de la classe (pas forcment par dfaut !)
/// initialise les donnes des widgets, place la hirarchie des sous-cadres etc...
/// Tous les widgets sont des attributs directs (PAS DES POINTEURS, PAS DE NEW)
/// de la classe encapsulante (ici Thing) de telle sorte qu'ils sont dtruits
/// automatiquement quand la classe Thing est dtruite.
Thing::Thing()
{
/// Menu test
m_menu.add_child(m_graphe_1);
m_graphe_1.set_pos(235, 195);
m_graphe_1.set_dim(310,40);
m_menu.add_child(m_graphe_2);
m_graphe_2.set_pos(235, 260);
m_graphe_2.set_dim(310,40);
m_menu.add_child(m_graphe_3);
m_graphe_3.set_pos(235, 322);
m_graphe_3.set_dim(310,40);
m_menu.add_child(m_exit);
m_exit.set_dim(35,18);
m_exit.set_pos(765, 0);
m_exit.set_bg_color(ROUGE);
}
/// Une mthode update de la classe doit tre appele dans la boucle de jeu
/// et cette mthode doit propager l'appel update sur les widgets contenus...
/// Cette mthode fait le lien entre l'interface, les vnements, et les consquences
void Thing::update2()
{
m_menu.update();
}
std::string Thing::accueil(BITMAP* fond_menu, bool *stop, bool *fin_boucle)
{
std::string nom="";
blit(fond_menu,grman::page, 0,0,0,0, SCREEN_W, SCREEN_H);
if(m_graphe_1.clicked())
{
nom="pics";
*stop=true;
}
if(m_graphe_2.clicked())
{
nom="pics2";
*stop=true;
}
if(m_graphe_3.clicked())
{
nom="pics3";
*stop=true;
}
if(m_exit.clicked())
{
*stop=true;
*fin_boucle=true;
}
return nom;
}
/// On a des allocations dynamiques dans m_dynaclowns => nettoyer dans le destructeur
Thing::~Thing() {}
| true |
cfbee69c702829e27e3e07e5f0f13b8673f5113a | C++ | BoHauHuang/Leetcode | /easy/110. Balanced Binary Tree/Balanced Binary Tree.cpp | UTF-8 | 689 | 3.375 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool ok = true;
int dfs(TreeNode* root){
if(!root || !ok) return 0;
int L = dfs(root->left);
int R = dfs(root->right);
if(abs(L-R) > 1) ok = false;
return max(L, R)+1;
}
bool isBalanced(TreeNode* root) {
dfs(root);
return ok;
}
};
| true |
6bca3912108f1bc514f98d8c0b5a0cff5bae4ee6 | C++ | wojtek5739g/Programy | /main (14).cpp | UTF-8 | 380 | 3.203125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int funkcja (int k)
{
int w;
for (int i=1; i<=k; i++)
{
if (i*i*i==k)
{
w=i;
}
}
if (w*w*w==k) return 1;
else return 0;
}
int main()
{
for (int i=1; i<=1000; i++)
{
if (funkcja(i)==1)
cout << i << endl;
}
return 0;
}
| true |
48bea8d9356df141edd00bc67788ed9950fcc314 | C++ | hliuliu/USACO | /milk/milk.cpp | UTF-8 | 813 | 2.84375 | 3 | [] | no_license |
/*
ID: heng_li1
TASK: milk
LANG: C++11
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
int main() {
ofstream fout ("milk.out");
ifstream fin ("milk.in");
int n,m;
fin >> n >> m;
vector<PII> markets (m,PII());
for (PII &p: markets) {
fin >> p.first >> p.second;
}
sort(markets.begin(),markets.end(), [] (PII &a,PII &b) {return a.first<b.first;});
int ans =0;
for (PII &p: markets) {
int delta = min(n, p.second);
ans += p.first*delta;
n-= delta;
if (!n) {
break;
}
}
fout << ans << endl;
fout.close();
return 0;
}
| true |